C++学习之路之容器(unordered_map)–无序(元素不允许相同)
#include<iostream>
#include<string>
#include<unordered_map>//无序
#include<algorithm>
using namespace std;
int main(){
//构造
unordered_map<string, string> data{{"0","C#"}};
data.emplace("1","C++");
data.insert({"2","python"});
data["3"] = "C";
// data.insert(make_pair("2", "Alice"));
unordered_map<string, string> data1(data);
unordered_map<string, string> data2(data1.begin(),data1.end());
cout << "data.size :"<< data2.size()<< endl;
data.empty();//若容器为空,则返回 true;否则 false。
data.size();// 返回当前容器中存有键值对的个数。
data.max_size();//返回容器所能容纳键值对的最大个数,不同的操作系统,其返回值亦不相同。
data.at("1");//返回容器中存储的键 key 对应的值,如果 key 不存在,则会抛出 out_of_range 异常。
cout<< data.at("2")<< endl;
auto item = data.find("3");
cout << item->second << endl;
data.count("C");//计数
cout << data.count("C")<< endl;
data.erase("1");
data1.clear();
data1.swap(data2);
//迭代
for(auto it = data.begin() ; it!=data.end();it++){
cout << "data : " << it->first << " " << it->second << endl;
}
unordered_map<string , string >::iterator it=data.begin();
while( it != data.end()){
cout << "while data : " << it->first << " " << it->second << endl;
it++;
}
}
编译:g++ unordered_map.cpp -o unordered_map