1. 程式人生 > 其它 >貨倉選址(貪心)

貨倉選址(貪心)

技術標籤: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;