How do you swap array elements using indexes?

closed account (oN3h0pDG)
Hello, I am trying to swap two array values using indexes but I am getting very confused and frustrated with how to do that. '

I'm trying to swap two string elements with each other. Please help this is making me crazy frustrated. Thanks for your help.

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  void printArray(string names[]) {

	for (int i = 0; i < 7; i++) {

		cout << names[i] << " ";

		}
}
int main() {
	int x = 0;
	string answer, name1, name2;
	int nameIndex1, nameIndex2;
	string names[7] = {"John", "Dave", "Jim", "Amanda", "Kelsey", "Don", "Jennifer"};

	while (x < 1) {
	printArray(names);

	cout << endl << "Do you want to swap students? " << endl;
	cin >> answer;

	if (answer == "Yes" || answer == "yes") {

		cout << "Who would you like to swap?" << endl;
		cin >> name1;

		for(int a = 0; a < 7; a++) {

		if (names[a] == name1) {

			nameIndex1 = a;
			cout << "Yes, " << name1 << " is in the line." << endl;
			



			}

			}

		cout << "Who would you like to swap " << name1 << " for?" << endl;
		cin >> name2;

		for(int b = 0; b < 7; b++) {

		if (names[b] == name2) {

			
                        nameIndex2 = b;
			cout << "Yes, " << name2 << " is in the line!!!" << endl;
			



			}

		}




	} else {

		cout << endl << "Thanks, please behave now, students!" << endl;
		x++;


	}
	}
	return 0;

}
for swapping use std::swap(element1,element2); for example use names[a] and name[b].

closed account (oN3h0pDG)
We're not allowed to use std::swap, we gotta do it with indexes unfortunately.
then a swap use a third variable temp.
auto temp = names[a];
names[a] = names[b];
names[b] = temp;
Topic archived. No new replies allowed.