首页 > 解决方案 > 这段代码中的“result.second == false”是什么意思?

问题描述

我遇到了这个用于计算向量中频率的 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++;
}

来自https://thispointer.com/c-how-to-find-duplicates-in-a-vector/。我想问是什么

result.second == false意思是?

标签: c++vector

解决方案


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


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

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

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


推荐阅读