Vector elements not what they say they are?

I have created a vector storing floats. I want to 'shuffle' the array so that elements are swapped. I do this using the function below.

1
2
3
4
5
6
7
8
9
10
void shuffleArray()
{
	int a = 5;
	for (int c = 8; c > 2; c--) {
		//swap(bodyPos[c], bodyPos[a]);
		float temp = bodyPos.at(a);
		bodyPos[c] = temp;
		a--;
	}
}


the idea is that for the vector of length 9, the 9th element will contain data from the 6th, the 8th data from the 5th, the 7th data from the 4th etc.

However, even though viewing state of variable when the program is run (and even printouts of the variable) suggest it has swapped the elements data... In reality when I use the data it doesn't work and is usually 0 in spite of whatever was there.

I really could do with a heads up on where I'm going wrong!
This doesn't swap anything.
It overwrites the value at bodyPos[c] with what is at bodyPos[a] - but does not change [b]bodyPos[a]
Last edited on
In order to do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<vector>

using namespace std;

void shuffleArray(vector<int> &v);

int main()
{
	vector<int>v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	v.push_back(6);
	v.push_back(7);
	v.push_back(8);
	v.push_back(9);
	shuffleArray(v);
	for(int i=0;i<v.size();i++)
	{
		cout << v[i] << "  ";
	}
	return 0;
}

void shuffleArray(vector<int> &v)
{
	vector<int> res(9);
	for(int i=8;i>=3;i--)
	{
		res[i-3] = v[i];
	}
	for(int i=0;i<3;i++)
	{
		res[i+6] = v[i];
	}
	v = res;
}


And this outputs:
4  5  6  7  8  9  1  2  3  
Topic archived. No new replies allowed.