【问题标题】:how to use unordered map in c++如何在 C++ 中使用无序映射
【发布时间】:2020-04-06 09:20:59
【问题描述】:

我正在编写一个使用无序映射的程序。经过在此之前的一些研究,我知道要使用无序地图,首先我们需要放置标题。但它没有奏效。提前感谢任何提示。哦,这是错误信息

 #error This file requires compiler and library support for the \
  ^
umap.cpp: In function 'int main()':
umap.cpp:21:2: error: 'unordered_map' was not declared in this scope
  unordered_map<string, int> siswa;
  ^
umap.cpp:21:22: error: expected primary-expression before ',' token
  unordered_map<string, int> siswa;
                      ^
umap.cpp:21:24: error: expected primary-expression before 'int'
  unordered_map<string, int> siswa;
                        ^
umap.cpp:24:2: error: 'siswa' was not declared in this scope
  siswa["saleh"]=90;
  ^

这是程序

#include <iostream>
#include <unordered_map>
#include <bits/stdc++.h> 

using namespace std;

void cari(string key){

    if(siswa.find(key)==siswa.end())
        cout<<siswa[key]<<endl;
    else
        cout<<"n/a"<<endl;
}


int main(){


    unordered_map<string, int> siswa;


    siswa["saleh"]=90;
    siswa["mutiara"]=85;
    siswa["icam"]=70;

    int t;
    cin>>t;
    string key;
    for(int i=0;i<t;i++){

        getline(cin,key);
        cari(key);
    }
}

顺便说一句,对不起我乱七八糟的语法:v

【问题讨论】:

标签: c++ c++11 header unordered-map


【解决方案1】:

范围错误与函数cari在其范围内无法访问您的无序映射有关,您可以为此包含相应数据类型的无序映射作为参数:

void cari(string key, unordered_map<string,int> x)
{
  if(x.find(key)==x.(end))
   cout<<x[key]<<"\n";
  else
   cout<<"n/a"<<"\n";
}

其他注意事项:

  • 正如 cmets 中已经提到的,避免使用 &lt;bits/stdc++.h&gt;。它被提及了数千次,但它的反复使用并不令人意外,因为 CP 中的新手被误导或倾向于使用它,最常见的原因是为了节省编写 STL 中包含的标头的时间。但是,您可以随时在必要时使用预先编写的模板。此外,大多数问题不涉及超过四个标题,因此在比赛期间编写它们也不是什么麻烦事。
    不鼓励使用此头文件,主要是因为它包含整个 STL 头文件系列,这使程序变得多余,进而导致编译速度变慢。此外,虽然它在在线评委/编译器中受支持,但在大多数 IDE(例如:Visual Studio)和编译器中不受支持。在生产代码中也强烈建议不要使用它,因此请避免使用它。

  • 使用std::string 或包含&lt;cstring&gt;/&lt;string.h&gt; 标头。请注意,如果您不声明命名空间std(再次使用它被视为bad practice),则必须在需要时使用std:: 作为前缀,例如cincoutstringunordered_map 在这里。该函数的参数将如下所示:

void cari(std::string key, std::unordered_map<std::string,int> x)
  • 使用\n 而不是endl,因为后者会调用对std::flush() 的不必要调用。

  • while(t--) 比用于迭代 t(或我假设的测试用例)的 for 循环更好,因为它更短,并且丢弃了额外循环变量的使用。

【讨论】:

  • @MuhammadSaleh 如果有帮助,请考虑接受答案(点击投票下方的勾号)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多