Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy specified vector content to another vector [duplicate]

Tags:

c++

copy

vector

I created a vector:

std::vector<std::string> mero; // earlier it filled with more than 500 data

After that I would like to create another vector which only takes a portion of the mero vector. (example: from 100th to 250th)

like image 426
szuniverse Avatar asked Mar 18 '13 13:03

szuniverse


3 Answers

There's a constructor for std::vector (number 4 in this link) that takes two iterators. It constructs a new vector including all elements from the first iterator (inclusive) to the second iterator (exclusive).

std::vector<std::string> partOfMero(mero.begin() + 100, mero.begin() + 250);

This will include mero[100] through mero[249] in the newly-constructed vector.

like image 162
David Schwartz Avatar answered Oct 31 '22 12:10

David Schwartz


You can get the first iterator using begin, and advance it by whatever amount you need:

vector<int> sub(advance(begin(miro), 100),
                advance(begin(miro), 250));
like image 26
Peter Wood Avatar answered Oct 31 '22 12:10

Peter Wood


std::vector has a constructor that takes two iterators, so you can specify a range to copy:

std::vector<std::string> v1;
std::vector<std::string>::const_iterator first = v1.begin() + 100;
std::vector<std::string>::const_iterator last = v1.begin() + 250;
std::vector<std::string> v2(first, last)

This will construct v2 such that it contains copies of all the elements from v1.begin()+100 to one before v1.begin()+250.

like image 39
juanchopanza Avatar answered Oct 31 '22 12:10

juanchopanza