Reputation: 5823
I am trying to find a way to copy elements of a vector to another vector.
int main()
{
std::vector<int> aVec{0,1,2,3,4};
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin()+3;
std::vector<int> aVecNew;
// How to insert elements ranging from itBegin till itEnd(including itEnd) to
// the vector aVecNew
return 0;
}
Most of the insert methods appear not to include itEnd. Is there a clean way to do this?
EDIT: If I am not sure ++itEnd is the end iterator or not. In such case it would fail. Is there any safer way without the mess ?
Upvotes: 2
Views: 1306
Reputation: 1736
In the general case - the target vector does already exist - the copy onto a back_insert_iterator until just before ++itEnd
is the right way, but in your case,
std::vector<int> aVecNew(itBegin, ++itEnd);
is the appropriate measure. std::vector
has ctor #(4) for that; no reason to first create and then populate the vector
here.
#include <vector>
#include <iostream>
#include <iterator> // ostream_iterator
#include <algorithm> // copy
int main()
{
std::vector<int> aVec{0,1,2,3,4}; // this is c++ of 2011 or later...
// ... thus this
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin() + 3;
// (if used) would at least be a case for "auto"
std::vector<int> aVecNew(itBegin, ++itEnd);
std::copy(aVecNew.begin(), aVecNew.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return EXIT_SUCCESS;
}
output:
0 1 2 3
live at Coliru's
Upvotes: 0
Reputation: 2241
Beyond the ways already mentioned, std::vector
has a constructor that will do exactly what you want (take the elements from range given begin and end iterators).
std::vector<int> aVecNew(itBegin, ++itEnd);
Upvotes: 1
Reputation: 6440
You can use std::copy
from <algorithms>
and std::back_inserter
from <iterator>
:
int main(int a, char**){
std::vector<int> aVec{ 0, 1, 2, 3, 4 };
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin() + 3;
std::vector<int> aVecNew;
std::copy(itBegin, itEnd, std::back_inserter(aVecNew));
return 0;
}
PS: Also, as it was mentioned in the comment, this code copies excluding itEnd. If you want to copy elements including itEnd, just increment its value by 1:
int main(int a, char**){
std::vector<int> aVec{ 0, 1, 2, 3, 4 };
std::vector<int>::iterator itBegin = aVec.begin();
std::vector<int>::iterator itEnd = aVec.begin() + 3;
std::vector<int> aVecNew;
std::copy(itBegin, ++itEnd, std::back_inserter(aVecNew));
return 0;
}
Some documentation on back_inserter and copy.
Upvotes: 1