Skip to content

Instantly share code, notes, and snippets.

@kyle-go
Last active August 29, 2015 13:56
Show Gist options
  • Save kyle-go/9245144 to your computer and use it in GitHub Desktop.
Save kyle-go/9245144 to your computer and use it in GitHub Desktop.
std::<int, std::string>map,删除key(first)小于20的元素。
#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