Copy vectors

I want to copy part of one vector onto another vector. Is this a good way to do this . . .

1
2
3
4
5
6
7
8
std::vector <int> vector1;
std::vector <int> vector2;
for (int n=0; n<3) vector1.push_back(n+1);
 
std::vector <int> temp(vector1);
temp.pop_back;
swap(temp,vector2);
temp.clear();


And could the last two lines be put into a for loop?
Before asking questions about basic functions, you can look them up:

http://www.cplusplus.com/reference/stl/vector/

You will see that the STD vector has an "=" operator.
closed account (zb0S216C)
@LowestOne: He/she only want part of the std::vector.

I recommend that you use iterators:

1
2
3
4
5
6
std::vector<int> a_(6, 0);

std::vector<int>::const_iterator end_(a_.begin() + 4);
std::vector<int> b_;
for(std::vector<int>::iterator at_(a_.begin()); at_ < end_; ++at_)
    b_.push_back(*at_);

Wazzak
A really easy way to do it is to use the assign() function.
http://www.cplusplus.com/reference/stl/vector/assign/

1
2
3
4
5
6
std::vector<int> vector1;
std::vector<int> vector2;
for (int n=0; n<3; ++n) vector1.push_back(n+1);

std::vector<int>::iterator end = vector1.begin() + 2;
vector2.assign(vector1.begin(), end);
Last edited on
It is done very simply.

Instead of this compound code



1
2
3
4
5
6
7
8
std::vector <int> vector1;
std::vector <int> vector2;
for (int n=0; n<3) vector1.push_back(n+1);
 
std::vector <int> temp(vector1);
temp.pop_back;
swap(temp,vector2);
temp.clear(); 


you can use the following

1
2
3
4
5
std::vector<int> vector1;

for ( int n = 0; n < 3; n++ ) vector1.push_back( n+1 );

std::vector<int> vector2( vector1.begin(), std::prev( vector1.end() ) );



Last edited on
Topic archived. No new replies allowed.