I am trying to copy a vector of pair to another:
vector<pair<int,int>> vp = {pair<int,int>(1,1), pair<int,int>(2,2)};
vector<pair<int,int>> vp2;
for_each(vp.begin(), vp.end(), [vp2](pair<int,int> p){
if(/*some condition*/){
vp2.push_back(p);
}
});
I get this compiler error:
error: passing ‘const std::vector<std::pair<int, int> >’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(value_type&&) [with _Tp = std::pair<int, int>, _Alloc = std::allocator<std::pair<int, int> >, value_type = std::pair<int, int>]’ discards qualifiers
Using gcc 4.5.1 on ubuntu.
Copying is much easier than that:
or even:
The error in your code is that you capture
vp2by value which effectively makes itconstin your anonymous method, and you cannot callpush_backon aconst vector. The following should work:But there’s no reason to use this instead of the simpler code.