在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數
阿新 • • 發佈:2021-01-03
技術標籤:C++學習
7、unordered_map的初始化、插入、輸出、查詢。
#include <unordered_map>
unordered_map<std::string, int> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
cout << "february -> " << months["february" ] << endl;//輸出february -> 28
unordered_map<std::string, int> months={{"a",3}};//初始化
months.insert(pair<string,int>("b",6));//插入
unordered_map<std::string, int>::iterator it;
for(it=months.begin();it!=months.end();it++){
cout<<it->first<< ","<<it->second<<endl;
}//迭代取值
unordered_map<std::string, int>::iterator i=months.find("c");
cout<<i->first<<","<<i->second<<endl;
Map與unordered_map區別
https://blog.csdn.net/zjajgyy/article/details/65935473
8、用unordered_map統計陣列中相同元素個數。
unordered_map<int, int> months;
int arr[10] = {0,1,2,2,2,5,5,7,7,7};
vector<int>p(arr,arr+10);
for (int num : arr) {
++months[num];//這裡num代表key
}
unordered_map<int, int>::iterator it;
for(it=months.begin();it!=months.end();it++){
cout<<it->first<<","<<it->second<<endl;
}
cout<<"months[0]"<<months[0]<<endl;cout<<"months[7]"<<months[7]<<endl;//這裡的0和7代表key
unordered_map<string, int> months;
string s[11] = {"aa","aa","aa","aa","aa","ba","ba","ba","ba","ba","ba"};
vector<string>p(s,s+11);
for (string num : s) {
++months[num];
}
unordered_map<string, int>::iterator it;
for(it=months.begin();it!=months.end();it++){
cout<<it->first<<","<<it->second<<endl;
}
cout<<"months[aa]"<<months["aa"]<<endl;cout<<"months[ba]"<<months["ba"]<<endl;
int a=months.count("ca");//檢視months中是否有key=ca,如果有返回1,無返回0
cout<<a<<endl;