Last active
August 29, 2015 13:56
-
-
Save kyle-go/9245144 to your computer and use it in GitHub Desktop.
std::<int, std::string>map,删除key(first)小于20的元素。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <map> | |
| #include <string> | |
| void print(const std::map<int, std::string> &map) | |
| { | |
| for (auto it=map.begin(); it!=map.end(); it++) { | |
| printf("key = %d, value=%s\n", it->first, it->second.c_str()); | |
| } | |
| } | |
| void mothed1(const std::map<int, std::string> &m) | |
| { | |
| printf("***********MOTHED 1*************\n"); | |
| print(m); | |
| auto map = m; | |
| for (auto it=map.begin(); it!=map.end();) { | |
| if (it->first < 20 ) { | |
| map.erase(it++); | |
| } else { | |
| break; | |
| } | |
| } | |
| printf("************************\n"); | |
| print(map); | |
| } | |
| void mothed2(const std::map<int, std::string> &m) | |
| { | |
| printf("***********MOTHED 2*************\n"); | |
| print(m); | |
| auto map = m; | |
| for (auto it=map.begin(); it!=map.end();) { | |
| if (it->first < 20 ) { | |
| it = map.erase(it); | |
| } else { | |
| break; | |
| } | |
| } | |
| printf("************************\n"); | |
| print(map); | |
| } | |
| void mothed3(const std::map<int, std::string> &m) | |
| { | |
| printf("***********MOTHED 3*************\n"); | |
| print(m); | |
| auto map = m; | |
| auto it = std::find_if(map.begin(), map.end(), [](std::pair<int, std::string> t){return t.first>=20;}); | |
| if (it != map.end()) { | |
| map.erase(map.begin(), it); | |
| } else { | |
| map.clear(); //remove all | |
| } | |
| printf("************************\n"); | |
| print(map); | |
| } | |
| void func() | |
| { | |
| srand(time(0)); | |
| std::map<int, std::string> map; | |
| for (int i=0; i<16; i++) { | |
| map.insert(std::make_pair(rand()%30, "value1")); | |
| } | |
| //删除key小于20的元素 | |
| mothed1(map); | |
| mothed2(map); | |
| mothed3(map); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment