Swap Struct in C++

Hello,
I want to swap elements of an array but I have an error. Why?


Severity Code Description Project File Line Suppression State
Error C2676 binary '[': 'Student' does not define this operator or a conversion to a type acceptable to the predefined operator


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
 #include <iostream>
#include<string>
using namespace std;
struct Student
{
    int phoneNumber;
    string name;
};

int main()
{
    Student myStudent[10];
    int num; string name;
    for (int i = 0; i < 5; i++)
    {
        cout << "Name " << i + 1 << ":";
        getline(cin >> ws, myStudent[i].name);
        cout << "Phone Number " << i + 1 << " :";
        cin >> myStudent[i].phoneNumber;
    }
    for (int i = 0; i < 5; i++)
    {
        for (int j = i + 1; j < 5; j++)
        {
            if (myStudent[i].name > myStudent[j].name)
            {
                //swap(myStudent[i], myStudent[j]); It's OK.
                Student TStudent = myStudent[i]; // ERROR
                myStudent[i] = myStudent[j];
                myStudent[j] = myStudent;
            }
        }
    }
    for (int i = 0; i < 5; i++)
    {
        cout << "Name " << i + 1 << ": " << myStudent[i].name; cout << endl;
        cout << "Phone Number " << i + 1 << ": " << myStudent[i].phoneNumber;
    }
    return 0;
}
Last edited on
Perhaps if you gave your variables better names, the issue might be more obvious.
You have an array of students called "myStudent" (singular).
You then create a variable called TStudent on line 28.
But then, on line 30, you attempt to assign myStudent (your array of students) to myStudent[j] (a Student).

You probably meant to assign TStudent.
Last edited on
usually you want to set it up so you swap a pointer, not an object, for large numbers of items or large numbers of swaps (like sorting).
You'd (generally) prefer pointers if it's large sizes of data per element. If each element in the array is relatively small, even if you have thousands of elements, you'd still prefer by-value swaps rather than dealing with pointers, since using pointers could cause tons of cache misses. (But in this case, since std::strings already have a pointer in them, I imagine the benefits either way are little. Just a guess, didn't measure.)
Last edited on
I was not saying to make the data dynamic (that would indeed cause cache misses).
Keep the data in a solid block, as you said.
Topic archived. No new replies allowed.