这段代码中的“result.second == false”是什么意思?

har*_*uhi -1 c++ vector

我遇到了这个用于计算向量中频率的 C++ 代码。

std::map<std::string, int> countMap;

// Iterate over the vector and store the frequency of each element in map
for (auto & elem : vecOfStrings)
{
   auto result = countMap.insert(std::pair<std::string, int>(elem, 1));
   if (result.second == false)
      result.first->second++;
}
Run Code Online (Sandbox Code Playgroud)

来自https://thispointer.com/c-how-to-find-duplicates-in-a-vector/。我想问一下有什么作用

result.second == false 意思?

Nat*_*ica 7

由于std::map和其他非多关联容器仅存储唯一项目,因此当您将某些内容插入其中时,它可能实际上不会插入,因为它可能已经存在。 insert因此std::pair<iterator, bool>,如果插入成功,则返回布尔值为真,否则为假。


我想指出你可以摆脱循环中的 if 语句。由于operator[]地图的工作方式,循环可以替换为

for (const auto & elem : vecOfStrings) // also added const here since we don't need to modify elem
{
   ++countMap[elem];
}
Run Code Online (Sandbox Code Playgroud)

现在,如果elem存在,则增加该值,如果不存在,则将其添加elem到地图并增加其值。

  • 遗憾的是 `std::map::operator[]` 正是为这种情况而设计的,甚至在 https://en.cppreference.com/w/cpp/container/map/operator_at 的示例中列出了字数统计但人们懒得去查看文档 (2认同)