gpt4 book ai didi

c++ - 如何交换 map 元素

转载 作者:太空狗 更新时间:2023-10-29 19:54:53 26 4
gpt4 key购买 nike

在 C++ 中,如何交换 map 的两个元素?

最佳答案

提供的答案是正确的,但对相同的键使用了两次 operator[],这不是免费的,可以避免:

std::map<char, std::string> a;

解决方案 1:

std::string &item1 = a['a'];
std::string &item2 = a['b'];
std::swap(item1, item2);

解决方案 2:

const std::map<char, std::string>::iterator item1 = a.find('a');
const std::map<char, std::string>::iterator item2 = a.find('b');
if ((item1 != a.end()) && (item2 != a.end()))
std::swap(item1->second, item2->second);

当然,这两个解决方案并不等同(解决方案 2 仅交换映射中已有的值,解决方案 1 不加质疑地插入,最终可能会交换两个默认构造的字符串)。

关于c++ - 如何交换 map 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4231942/

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