Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 找不到std::map中插入的最新密钥_C++_Oop_Std_Stdmap - Fatal编程技术网

C++ 找不到std::map中插入的最新密钥

C++ 找不到std::map中插入的最新密钥,c++,oop,std,stdmap,C++,Oop,Std,Stdmap,我的问题是,无论我在std::map中插入的最后一个元素是什么,我都无法找到它 我有下面的映射,它将颜色作为键,并将其编码为某种对象类型(enum) 示例性输出: Not found in the map! Blue: 36 Green: 28 Red: 237 is not mapped! Not found in the map! Blue: 36 Green: 28 Red: 237 is not mapped! 但是,如果我取消对此的注释: // load(Color(0,

我的问题是,无论我在
std::map
中插入的最后一个元素是什么,我都无法找到它

我有下面的映射,它将颜色作为键,并将其编码为某种对象类型(enum)

示例性输出:

Not found in the map!   Blue: 36  Green: 28 Red: 237 is not mapped!
Not found in the map!   Blue: 36  Green: 28 Red: 237 is not mapped!
但是,如果我取消对此的注释:

// load(Color(0, 111, 222), Object::PleaseDont);
然后,它将正确检测上述以前未找到的颜色:
(36、28、237)

对我来说,这看起来像是被一个或是什么东西弄丢了,但老实说,我不知道潜在的错误在哪里


颜色的定义如下,对于重载的
运算符,
st::map
中的键的比较必须是严格的弱顺序,即必须遵守以下规则:

  • (a
    
  • (a
    意味着
    (a
  • (a
    意味着
    (b
  • (a
    意味着
    (a
  • 对于结构来说,实现这一点的最简单方法是利用
    std::tuple
    s比较:

    bool operator< (Color const& c0, Color const& c1) {
        return std::tie(c0.blue, c0.green, c0.red) < std::tie(c1.blue, c1.green, c1.red);
    }
    
    bool运算符<(颜色常数&c0,颜色常数&c1){
    返回标准::tie(c0.blue,c0.green,c0.red)

    此比较运算符实际上定义了一个更强的顺序:总顺序。

    您的比较运算符没有定义严格的弱顺序。因此,在
    std::map
    中使用类型会导致不确定的行为。@DietmarKühl:谢谢!
    // load(Color(0, 111, 222), Object::PleaseDont);
    
    struct Color {
        uint8_t blue;
        uint8_t green;
        uint8_t red;
    
        Color() = default;
    
        Color(uint8_t blue, uint8_t green, uint8_t red)
            :blue{blue},
             green{green},
             red{red}
        {
        }
    
        bool operator<(const Color& other) const {
            return blue != other.blue || green != other.green || red != other.red;
        }
    }
    
    bool operator< (Color const& c0, Color const& c1) {
        return std::tie(c0.blue, c0.green, c0.red) < std::tie(c1.blue, c1.green, c1.red);
    }