Hello, I recently encountered a small debate with myself about a struct thing which is swapping elements in an array of struct.
For example
1 2 3 4 5 6
struct Test{
int data;
float x;
char a[10];
}b[10];
now for example, if I switch b[0].data with b[1].data, by testing I saw it switched the entire b[0] elements with entire b[1] elements not just replace their data values, why does that happen instead of only replacing 1 value.
struct Test{
int data;
float x;
char a[10];
}b[10];
int main()
{
for(int i = 0; i < 9; i++){
int temp = b[i].data;
b[i].data = b[i+1].data;
b[i+1].data = temp;
}
return 0;
}
Ignore the logic behind this loop whatsoever I just wanted to know what's the reason behind the fact that the entire b[i] with all its data gets swapped with b[i+1] and all its data, instead of just the member value. Like that code will make it so that if
b[0].data = 5
b[0].x = 5.0
b[0].a = "Hi"
b[1].data = 10
b[1].x = 10.0
b[1].a = "Hiiiiii"
Now what I mean is, if I call a swap on b[#].data and b[##].data it'll swap the entire array element not just the .data value for b[#] and b[##]. that means if I call this swap on .data for the above:
1 2 3
int temp = b[i].data;
b[i].data = b[i+1].data;
b[i+1].data = temp;
And assuming i is equal 0, b[0].data becomes = 10, b[0].x becomes = 10.0 and b[0].a becomes "Hiiiii" why did it swap the entire thing instead of just the values of the member "data" for both struct array elements.
Sorry if I repeated myself over and over I am trying to deliver the point as much as I can.
is this what you are trying to do?
class::swapmember(class x)
{
std::swap(x.member, this->member);
}
I think you have to make an overload for your class if you want to call std swap on it, but I don't recall if that is always true or just true under some conditions. I also don't recall if you need assignment op & copyctor (defaults or not) to make it work. Sorry, I don't swap things much, and when I do, its usually just a pointer or a POD type.