Help with simple swap

Mar 1, 2012 at 8:57pm
I have a vector v[] full of class objects called kajigger with private members _thing1 and _thing2.

How do I swap the entire class objects within the vector? So far I have only been able to swap member values. This is one of those things I know was recently explained to me but has slipped my memory in a moment of need, and I know it's not complicated.

Any advice is greatly appreciated.
Mar 1, 2012 at 9:07pm
It is not clear how you are going to swap elements of your vector.
Mar 1, 2012 at 9:14pm
"vlad from moscow" lol thanks series of tubes

I have a class:

1
2
3
4
5
Class Example{
private:
int _thing;
int _another;
};


That's code that allows you to create grouped "objects"

So later I can be like:

1
2
3
4
5
6
7
Example object;
int x;
object._thing + object._another = int x;

//in my case, I am making a vector(array) of the objects:

vector<Example> v;


Explaining the usefulness of objects is something I am not going to attempt to do because I am a total newb and wouldn't do it justice. All I know at the moment is that they're a huge, huge element of object oriented design and they make C++ awesome.



Mar 1, 2012 at 9:21pm
i guess you need a temp variable

1
2
3
4
5
YourType temp;

temp = data[2];
data[2] = data[3];
data[3] = temp;


i could be wrong though.....
Mar 1, 2012 at 9:25pm
Sorry but in your example I have not seen where you are doing swapping. I only have undestood that you are going to use vector.

vector has swap function so you can swap two vectors.
Mar 1, 2012 at 9:26pm
No, you're right. I have it working like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
		
//temps
int super;
string pro;

super = v[i]._thing1;
pro = v[i]._thing2;

v[i]._thing1 = v[k]._thing1;
v[i]._thing2 = v[k]._thing2;

v[k]._id = super;
v[k]._vote = pro;


That works fine, but I know for a fact there is a way to do this in one line. Imagine a class object with 100 members being swapped in this fashion!
Mar 1, 2012 at 9:30pm
In header <algorithm> there is standard function std::swap. You can use it to swap your objects.
Topic archived. No new replies allowed.