Home > Net >  Flip order of std::pair
Flip order of std::pair

Time:01-22

How can I flip the order of std::pair? Is there an in-build command or I need to create a new pair.

Currently I am doing this by creating a new pair.

std::pair el_ids(0,1);
el_ids = std::make_pair(el_ids.second, el_ids.first);

CodePudding user response:

As long as both types of the pair are the same you can just swap them (like @273k has pointed out in the comments), e.g.:

godbolt example

std::pair p = {1, 2};
std::swap(p.first, p.second);

If the types are different you'd have to write a small utility function for it, since there's no built-in way to do that, e.g.:

godbolt example

template<class T>
constexpr auto pair_swap(T&& pair) {
    return std::make_pair(
        std::forward<T>(pair).second,
        std::forward<T>(pair).first
    );
}

// Usage Example:
std::pair p = {std::string{"A"}, 12};
auto p2 = pair_swap(std::move(p));

CodePudding user response:

You can also swap the content directly

std::pair el_ids(0,1);
std::swap(el_ids.first,el_ids.second);

CodePudding user response:

You can also use uniform initialization:

int main() {
  std::pair el_ids(0,1);
  el_ids = {el_ids.second, el_ids.first};
}

Running example: https://godbolt.org/z/6vjf58co8

  •  Tags:  
  • Related