std :: map为什么不在我的代码中添加键值

Pro*_*mer 1 c++ c++11

我正在尝试将键和值数据添加到我的类地图成员变量中 - 但它没有添加相同的 - 我尝试过的map - insert,[]和emplace方法,但它们不是在我的循环代码中添加数据来映射 - 只有我在课程构建期间插入的值是可用的 - 我需要做的是解决问题 - 我期待show方法也会打印7,8,9,9 -

#include <iostream>
#include <map> 
#include <vector>

  class A {
    public:
      A(std::initializer_list <uint32_t> d): data(d) {}
    std::vector <uint32_t> data;
    bool operator < (const A & rhs) const {
      size_t rhsSize = rhs.data.size();
      for (size_t i = 0; i < data.size(); i++) {
        if (i < rhsSize)
          return false;
        return true;
      }
    }
  };

class B {
  public:
    B(const std::map <A, uint32_t> & t): table(t) {}
  void Show() {
    for (std::map <A, uint32_t> ::iterator it = table.begin(); it != table.end(); ++it) {
      for (const auto & i: it->first.data)
        std::cout << i << "\n";
      std::cout << it->second << "\n";
    }
  }

  std::map <A, uint32_t> table;
};

int main() {
  std::map <A, uint32_t> tb = {
    {
      A {70, 8, 9,10}, 1234}
  };
  B b(tb);
  for (int i = 0; i < 2; i++) {
    b.Show();
    b.table.emplace(A {7, 8,9, 9}, 1234);
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译并运行代码:

$ c++ -std=c++11 try78.cpp


$ ./a.exe
70
8
9
10
1234
70
8
9
10
1234
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 6

operator <违反了要求std::map密钥的严格弱订购要求.这要求if如果comp(a,b)为true comp(b,a)则为false.你用

bool operator < (const A & rhs) const {
  size_t rhsSize = rhs.data.size();
  for (size_t i = 0; i < data.size(); i++) {
    if (i < rhsSize)
      return false;
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

比较的元素,如果我们比较{70, 8, 9,10}反对{7, 8,9, 9}则返回true,如果我们打开它周围也返回true.这使得地图认为元素相等,并且不会添加第二个项目.

如果你只是为了确保这一独特载体存储在地图上,那么你可以使用std::vectoroperator <Aoperator <喜欢

bool operator < (const A & rhs) const {
    return data < rhs.data;
}
Run Code Online (Sandbox Code Playgroud)

并且代码将正常运行.

  • @Programmer是的.因为如果`cmp(a,b)== cmp(b,a)`,键必须在映射中是唯一的,那么元素"必须是相同的",因为这是具有该值的完全有序集合中的唯一值行为. (2认同)