24,860
社区成员




#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
map<string,int> mapCount;
map<string,int> mapCountTemp;
bool notCopy(pair<string,int> key_value){
return key_value.second==2;
}
int main(){
mapCount.insert(make_pair("000",0));
mapCount.insert(make_pair("001",1));
mapCount.insert(make_pair("002",2));
mapCount.insert(make_pair("003",1));
remove_copy_if(mapCount.begin(),mapCount.end(),mapCountTemp.begin(),notCopy);
cout<<mapCountTemp.size()<<endl;
getchar();
}
请问,拷贝map容器的内容后,如何进行交换呢?
map<TKey, TValue> 作为容器时其元素为 pair<const TKey, TValue> ,不能通过对其 *iterator 的直接赋值来修改内容。况且就算能修改内容,你直接使用 mapCountTemp.begin() 也没有办法分配空间。应该考虑使用 inserter(mapCountTemp, mapCountTemp.begin()) 替代。
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
map<string,int> mapCount;
map<string,int> mapCountTemp;
bool notCopy(pair<string,int> key_value){
return key_value.second==2;
}
int main(){
mapCount.insert(make_pair("000",0));
mapCount.insert(make_pair("001",1));
mapCount.insert(make_pair("002",2));
mapCount.insert(make_pair("003",1));
remove_copy_if(mapCount.begin(),mapCount.end(),inserter(mapCountTemp, mapCountTemp.end()),notCopy);
cout<<mapCountTemp.size()<<endl;
getchar();
}