copying vector of pair
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.
As an alternative to Konrad's answer; if the goal is simply to copy the elements of the first vector if they match a certain condition, would std::copy_if
not be a better match?
vector<pair<int,int>> vp = {pair<int,int>(1,1), pair<int,int>(2,2)};
vector<pair<int,int>> vp2;
copy_if(vp.begin(), vp.end(), back_inserter(vp2), [](pair<int,int> p) { return /* some condition */; });
Copying is much easier than that:
vector<pair<int,int>> vp2(vp.begin(), vp.end());
or even:
vector<pair<int,int>> vp2 = vp; // or
vector<pair<int,int>> vp2(vp);
The error in your code is that you capture vp2
by value which effectively makes it const
in your anonymous method, and you cannot call push_back
on a const vector
. The following should work:
for_each(vp.begin(), vp.end(), [&vp2](pair<int,int> p){vp2.push_back(p);});
But there’s no reason to use this instead of the simpler code.
精彩评论