Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip order of std::pair

Tags:

c++

std

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);
like image 561
PetrasVestartasEPFL Avatar asked Oct 18 '25 11:10

PetrasVestartasEPFL


1 Answers

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));
like image 124
Turtlefight Avatar answered Oct 20 '25 02:10

Turtlefight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!