std::map 检查地图是否被分配了非默认值?

std::map check if a map has been assigned a non-default value?

假设我有一个定义为

的复杂地图
std::map<int, std::pair< vector<int>, float> > complex_map;  

让我们假设我将这张地图初始化为

for (int k=0;k<5;k++)
{
    std::pair< vector<int>, float> complex_map_child;
    complex_map[k]=complex_map_child;
}

接下来,我填充这张地图的一些条目:

float test_1 = .7888;
vector<int> test_2;
test_2.push_back(1);
test_2.push_back(2);
complex_map[1].first = test_2;
complex_map[1].second = test_1;

所以对应complex_map的键值1,我有test_1和test_2对应的一对值。

现在如何检查我是否已明确向地图添加值?即在这个例子中我怎么说我没有明确填写说 complex_map[0]?

Now how do I check if I have explicitly added values to the map? i.e in this example how do I say that I havent explicitly filled up say complex_map[0]?

如果 "explicitly" 的意思是要查找在执行 complex_map[k]=complex_map_child; 的初始化循环之后写入的元素,则:

  • 您可以将地图中的值与 complex_map_child 进行比较,看看它们是否相等

  • 您可以检测映射条目是否使用相同的值写入,或者更改然后恢复(除非您将数据类型更改为自己跟踪,或者在 map 之外添加一些额外的簿记)

看起来你使用 std::map::operator[] 不当并尝试检查它 - 你得到这样的对象:

auto &complex_value = complex_map[0];

现在您尝试检查它是您之前插入的还是由 std::map::operator[] 隐式创建的。

只是不要使用 std::map::operator[] 来访问元素。仅在需要在地图中设置值时使用它。

所以正确的解决方案是使用不同的方法:

// I just want to check if key 0 is there
if( complex_map.count( 0 ) ) {
     ...
}

// I want to access element by key 0 if it is there
auto it = complex_map.find( 0 );
if( it != complex_map.end() ) {
    auto &complex_value = it->second;
    ...
}

等等。我知道写 complex_map[0] 更短,但你正在创造一个试图解决复杂方式的问题。