lower_bound & upper_bound 練習
set- #include<bits/stdc++.h>
- using namespace std;
- set<int> s;
- //set<int> s={9,7,5,12,2};
- int main()
- {
- s.insert(9);
- s.insert(2);
- s.insert(5);
- s.insert(2);
- s.insert(12);
- s.insert(7);
- cout<<s.size()<<endl;
- cout<<"-----"<<endl;
- for(int i: s)
- cout<<i<<endl;
- cout<<"-----"<<endl;
- for(auto it=s.begin(); it!=s.end(); it++)
- cout<<*it<<endl;
- cout<<"-----"<<endl;
- auto it=s.upper_bound(8);
- //cout<<it-s.begin()<<endl; //行不通
- cout<<*it<<endl;
- cout<<*--it<<endl;
- cout<<"-----"<<endl;
- it=s.upper_bound(13);
- if(it==s.end())
- cout<<"no find"<<endl;
- else
- cout<<*it<<endl;
- it=--s.lower_bound(2);
- if(it==s.end())
- cout<<"no find"<<endl;
- else
- cout<<*it<<endl;
- return 0;
- }
- // 2 5 7 9 12
複製代碼 map- #include<bits/stdc++.h>
- using namespace std;
- map<int, string> mp;
- //map<int, string> mp={{3, "t"},{1, "o"}};
- int main()
- {
- mp[9]="n";
- mp[5]="f";
- mp[12]="t";
- mp[7]="s";
- mp[2]="t";
- //mp.insert(mp.begin(), {3, "t"});
- cout<<mp.size()<<endl;
- for(pair<int, string> p: mp)
- cout<<p.first<<": "<<p.second<<endl;
- cout<<"-------"<<endl;
- for(auto it=mp.begin(); it!=mp.end(); it++)
- cout<<(*it).first<<": "<<(*it).second<<endl;
- cout<<"-------"<<endl;
- auto it=mp.upper_bound(8);
- cout<<(*it).first<<": "<<(*it).second<<endl;
- it=--mp.upper_bound(8);
- cout<<(*it).first<<": "<<(*it).second<<endl;
- cout<<"-------"<<endl;
- it=mp.upper_bound(12);
- if(it==mp.end())
- cout<<"no find"<<endl;
- else
- cout<<(*it).first<<": "<<(*it).second<<endl;
- it=--mp.lower_bound(2);
- if(it==mp.end())
- cout<<"no find"<<endl;
- else
- cout<<(*it).first<<": "<<(*it).second<<endl;
- return 0;
- }
- // 2 5 7 9 12
複製代碼 |