代码之家  ›  专栏  ›  技术社区  ›  wrongusername

如何交换地图元素

  •  3
  • wrongusername  · 技术社区  · 15 年前

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

    5 回复  |  直到 10 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    在地图中交换是什么意思?一张普通的瓦尼拉平面图没有任何特定的顺序,所以说到交换,对于顺序没有任何意义。

    如果您正在寻找保留顺序的C++映射实现,那么在这种情况下,排序变得有意义,那么 here

    但是,如果要将与一个键关联的值与与与第二个键关联的值交换,则只需执行以下操作

      map<char,string> mymap;
    
      mymap['a']="firstValue";
      mymap['b']="SecondValue";
      /*now let's swap*/
      string tmpString = mymap['a'];
      mymap['a']=mymap['b'];
      mymap['b']= tmpString
    
        2
  •  5
  •   icecrime    15 年前

    提供的答案是正确的,但正在使用 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毫无疑问地插入,最后可能交换两个默认构造的字符串)。

        3
  •  3
  •   Kylo    15 年前

    我想 std::swap() 是个不错的选择。

        4
  •  1
  •   Animiral    10 年前

    到目前为止,所提供的答案中没有一个涉及到不存在的密钥,并且保留了这些密钥的不存在。

    template<class Key, class Value>
    void swap_map_elements(std::map<Key, Value>& map, const Key& key1, const Key& key2)
    {
        auto it1 = map.find(key1);
        auto it2 = map.find(key2);
        auto end = map.end();
    
        if(it1 != end && it2 != end) {
            std::swap(it1->second, it2->second);
        }
        else if(it1 != end) {
            map.emplace(std::make_pair(key2, std::move(it1->second)));
            map.erase(key1);
        }
        else if(it2 != end) {
            map.emplace(std::make_pair(key1, std::move(it2->second)));
            map.erase(key2);
        }
    }
    

    例子:

    auto M = std::map<int, std::string>();
    M.emplace(std::make_pair(1, "one"));
    M.emplace(std::make_pair(2, "two"));
    
    swap_map_elements(M, 1, 2); // 1: "two", 2: "one"
    swap_map_elements(M, 1, 4); // 2: "one", 4: "two"
    swap_map_elements(M, 5, 2); // 4: "two", 5: "one"
    swap_map_elements(M, 8, 9); // 4: "two", 5: "one"
    
        5
  •  0
  •   Draco Ater    15 年前

    你是说这个吗?

    const T tmp = map["a"];
    map["a"] = map["b"];
    map["b"] = tmp;
    
    推荐文章