首页 > 解决方案 > 具有无效输入的映射返回映射的第一个插入值

问题描述

我创建了一个结构来保存表的行/列索引

struct itemIndex {
    int row;
    int col;

    bool operator< (const itemIndex &i) const { if (this->col == i.col) return this->row < i.row; else return false; }
    bool operator== (const itemIndex &i) const { return (this->row == i.row && this->col == i.col); }
};

现在,我创建了一个将索引作为键的映射,但只有第 1 列中的索引创建了键。但是,当调用索引为 col = 0 的值时,它似乎返回了第一个插入的索引(行 = 0,col = 0),我不知道为什么。下面是代码的实现:

    itemIndex index;
    index.row = pLVDispInfo->item.iItem;
    index.col = pLVDispInfo->item.iSubItem;
    //example index.row = 5, index.col = 0
    bool found = false; 
    found = m_mSettingMap.find(index) != m_mSettingMap.end(); // returns true
    int val = m_mSettingMap[index];

标签: c++dictionary

解决方案


bool operator< (const itemIndex &i) const { if (this->col == i.col) return this->row < i.row; else return false; }

因此,如果 col 值匹配,您将根据行进行子排序。够正常的。
但是如果 col 不匹配,你总是返回 false?我希望col在这种情况下订购。

尝试:

bool operator< (const itemIndex &i) const 
{
   if (col == i.col) return row < i.row; 
   return col < i.col;
}

推荐阅读