Anurag Kumar
Anurag Kumar

Reputation: 3

Can std::swap swap two structs in an array

I have an array of structs

struct ItemType
{
    value_type data;
    size_type priority;
};

Can std::swap be used to swap the structs in the array so that I could do

std::swap(array[i], array[i+1]);

and come out with the intended result?

Upvotes: 0

Views: 977

Answers (2)

Klaus
Klaus

Reputation: 25603

You don't tell us anything about the types you want to swap.

From std::swap we can read, that the data types which should be swapped, must be fullfill the following requirements:

Type requirements

T must meet the requirements of MoveConstructible and MoveAssignable.

struct A 
{   
    double x;
    std::vector<std::string> y;  
    void Print() const 
    {
        std::cout << x << std::endl;
        for ( auto& el: y ) { std::cout << el << " "; }
        std::cout << std::endl;
    }

};  

int main() {
    A arr[]={{1.234,{"This","is","a","test"}},{ 5.678, {"which","is","simple"}}};
    arr[0].Print();
    arr[1].Print();

    std::swap(arr[0], arr[1]);
    arr[0].Print();
    arr[1].Print();
    return 0;
} 

As long your types fulfill the requirements, it doesn't matter, that both are located in an array or not.

If your types are currently not fulfilling the requirements, it is typically possible to make them swappable by adding appropriated constructors to the struct.

Upvotes: 2

coder_jam
coder_jam

Reputation: 94

Yes, it comes out with intended result. You can test the below code to see that it works.

#include <iostream>
using namespace std;

struct A {
  int x;
  string y;
};

int main() {
  A a1;
  a1.x = 5;
  a1.y = "hi";
  A a2;
  a2.x = 7;
  a2.y = "bye";
  A arr[2];
  arr[0] = a1;
  arr[1] = a2;
  swap(arr[0], arr[1]);
  cout << arr[0].x << " " << arr[1].y << "\n";
  return 0;
}

Upvotes: 0

Related Questions