Swapping a single pointer item in vector?

H

Howard

Hi all,
is there an easy way to swap one pointer item in a vector with a pointer
that's not yet in the vector?

Currently, I'm using begin()+index to get an iterator to the item I want
to swap out, then deleting the pointer there, then using erase to get rid of
the vector item itself and get an iterator to the next item, and finally
using insert to put my new pointer in the correct place. Is there an easier
way?

Thanks,
-Howard
 
A

Alf P. Steinbach

* Howard:
is there an easy way to swap one pointer item in a vector with a
pointer that's not yet in the vector?

std::swap comes to mind.

Cheers, & hth.,

- Alf
 
J

Jim Langston

Howard said:
Hi all,
is there an easy way to swap one pointer item in a vector with a
pointer that's not yet in the vector?

Currently, I'm using begin()+index to get an iterator to the item I
want to swap out, then deleting the pointer there, then using erase to get
rid of the vector item itself and get an iterator to the next item, and
finally using insert to put my new pointer in the correct place. Is there
an easier way?

Just change it. The output of the following program is
10 20
10 10

#include <iostream>
#include <vector>

int main()
{
std::vector<int*> MyVect;
int a = 10;
int b = 20;

MyVect.push_back( &a );
MyVect.push_back( &b );

for ( std::vector<int*>::iterator it = MyVect.begin(); it !=
MyVect.end(); ++it )
std::cout << *(*it) << " ";
std::cout << "\n";

std::vector<int*>::iterator it = MyVect.begin() + 1;
*it = &a;

for ( std::vector<int*>::iterator it = MyVect.begin(); it !=
MyVect.end(); ++it )
std::cout << *(*it) << " ";
std::cout << "\n";
}
 
H

Howard

----- Original Message -----
From: "Jim Langston" <[email protected]>
Newsgroups: comp.lang.c++
Sent: Tuesday, December 04, 2007 7:01 PM
Subject: Re: Swapping a single pointer item in vector?

Just change it. std::vector<int*>::iterator it = MyVect.begin() + 1;
*it = &a;

D'oh! Of course! :) Thanks, Jim
-Howard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top