c++ - 这段代码中的“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
意思是?
解决方案
由于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
到地图并增加其值。
推荐阅读
- windows - 在批处理文件中使用 zip 有时会在没有提示的情况下要求返回
- php - 无法理解布尔逻辑
- javascript - 16:9 宽高比应用程序和背景(考虑导航占用的空间)
- ios - UITraitCollection getter,iOS13 不支持
- scala - 如何将 Spark Dataframe 的时间戳列转换为字符串列
- javascript - 该代码不计算或显示任何结果
- maven - 如何正确设置快照 deeplearning4j
- c# - 双列表框选择要删除的项目
- c# - 使用 c# 控制台应用程序中的嵌套 for 循环从右上角到左下角绘制对角线
- html - Umbraco 8 宏某些 HTML 标签未在后台呈现