How to copy a vector column?

I have a 2nd vector let's 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 to another 2d vector, for example

vector < vector < int > > test;

test = 4 5
       9 0 
       1 1
       2 2

How can I do this efficiently?

+3
source share
2 answers

Maybe so?

#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());
}
+3
source

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 didn’t increase your arms, I would go with the usual loop. But I don’t think I would use nested first std::vector. If you have only two rows with two columns, it is best to use a vector boost::array<int, 2>.

+3
source

Source: https://habr.com/ru/post/1783526/


All Articles