代码改变世界

c++ 用lambda删除vector中元素

2012-07-09 19:12  youxin  阅读(824)  评论(0)    收藏  举报
vector<string> vec,vec2;
    string str;
    
    while(cin>>str)
        vec.push_back(str);
    
    cin.sync();
    cin.clear();
    while(cin>>str)
        vec2.push_back(str);
    typedef vector<string>::iterator Iter;
    string s;
 
    vec.erase(remove_if(vec.begin(),vec.end(), [=](string s) ->bool
        {
             
            vector<string>::const_iterator retEnd=find(vec2.begin(),vec2.end(),s);
            if(retEnd!=vec2.end())
                return true;
            return false;
             
             
    }),vec.end());

   程序虽小,但是有很多需要注意的地方。画红线的必须是const_iterator ,不能使iterator,否则提示无法从const_iterator 转换为iterator,lambda是常量调用,const Container后,返回的迭代器是const_iterator.