P
pwalker
Hi everyone,
I am trying to get my head around iterators used on vectors. Let's take the
code below:
-------------
std::vector<int> v1;
std::vector<int> v2;
v1.push_back( 1 );
v1.push_back( 2 );
v1.push_back( 3 );
v2.push_back( 10 );
v2.push_back( 20 );
v2.push_back( 30 );
v1.insert(v1.end(), v2.begin(), v2.begin());
for(int j = 0; j < v1.size(); j++)
std::cout << v1[j] << " ";
-------------
I'm confused why we dont get the output 1 2 3 10
Doesn't the insert method insert to the back of v1 everything between
v2.begin() and v2.begin(), which is namely 10?
I realise that to get the desired result I need to instead use
v1.insert(v1.end(), v2.begin(), v2.begin()+1) but i fail to understand the
logic in this.
I know that v2.begin() points to 10, and v2.end() (which is the same as
v2.begin()+3) points to one-beyond-30.
I guess all it comes down to is if I specify v1.insert(v1.end(), v2.begin(),
v2.begin()+N) it will append to the back of v1 (namely as position
one-beyond-3) the first N values of v2.
Any help on understanding this whole concept would be great!
Cheers,
Peter
I am trying to get my head around iterators used on vectors. Let's take the
code below:
-------------
std::vector<int> v1;
std::vector<int> v2;
v1.push_back( 1 );
v1.push_back( 2 );
v1.push_back( 3 );
v2.push_back( 10 );
v2.push_back( 20 );
v2.push_back( 30 );
v1.insert(v1.end(), v2.begin(), v2.begin());
for(int j = 0; j < v1.size(); j++)
std::cout << v1[j] << " ";
-------------
I'm confused why we dont get the output 1 2 3 10
Doesn't the insert method insert to the back of v1 everything between
v2.begin() and v2.begin(), which is namely 10?
I realise that to get the desired result I need to instead use
v1.insert(v1.end(), v2.begin(), v2.begin()+1) but i fail to understand the
logic in this.
I know that v2.begin() points to 10, and v2.end() (which is the same as
v2.begin()+3) points to one-beyond-30.
I guess all it comes down to is if I specify v1.insert(v1.end(), v2.begin(),
v2.begin()+N) it will append to the back of v1 (namely as position
one-beyond-3) the first N values of v2.
Any help on understanding this whole concept would be great!
Cheers,
Peter