gpt4 book ai didi

c++ - 翻转 std::pair 的顺序

转载 作者:行者123 更新时间:2023-12-05 01:54:09 27 4
gpt4 key购买 nike

如何翻转 std::pair 的顺序?是否有内置命令或我需要创建一个新的对。

目前我正在通过创建一对来做到这一点。

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

最佳答案

只要这对的两种类型相同,您就可以交换它们(就像@273k 在评论中指出的那样),例如:

godbolt example

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

如果类型不同,你必须为它编写一个小的实用函数,因为没有内置的方法可以做到这一点,例如:

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));

关于c++ - 翻转 std::pair 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70804783/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com