Reputation: 3075
I've a 2d vector say
vector < vector < int > > sample;
sample = 1 2 3 4 5
6 7 8 9 0
1 1 1 1 1
2 2 2 2 2
Now I want to copy only the last two columns into another 2d vector like
vector < vector < int > > test;
test = 4 5
9 0
1 1
2 2
How can I do this efficiently ?
Upvotes: 3
Views: 2165
Reputation: 25739
Maybe like this?
#include <algorithm>
vector<vector<int> > new_vector;
new_vector.resize(sample.size());
for (size_t i = 0; i < new_vector.size(); ++i) {
new_vector[i].resize(2);
copy(sample[i].end() - 2, sample[i].end(), new_vector[i].begin());
}
Upvotes: 3
Reputation: 506905
I heard boost has a foreach loop
std::vector< std::vector<int> > v;
BOOST_FOREACH(std::vector<int> const &i, test) {
v.push_back(std::vector<int>(i.end() - 2, i.end()));
}
If you haven't boost at hands, I would go with a usual for loop. But I don't think I would use nested std::vector
in the first place. If you only ever have two-column rows, best use a vector of boost::array<int, 2>
.
Upvotes: 3