c++ - 检查地图值c ++
问题描述
我需要遍历地图中的值并检查有多少> 0。我不知道如何在不循环的情况下执行此操作。
#include <map>
using std::map;
#include <string>
using std::string;
#include <iostream>
using std::cout; using std::endl;
int exists(const map<string, int> &m) {
int count = 0;
for (auto &p : m) {
if (p.second > 0) {
count++;
}
}
return count;
}
int main() {
const std::map<std::string, int> stuff = {
{"book", 0},
{"pencil", 7},
{"eraser", 0},
{"calculator", 1},
{"rivers", 1},
{"fish", 2},
{"people", 0},
};
int num = exists(stuff);
cout << num;
}
输出“4”,因为映射中只有 4 个键的值 >0。我基本上不需要 for 循环或 while 循环。
解决方案
让我们试试这个:
std::map<std::string, int>::const_iterator iter = stuff.begin();
unsigned int quantity = 0;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
if (iter->second == 0) ++quantity;
++iter;
我们称这种技术为“循环扁平化”。使用“循环展开”,会复制循环内容的一部分。在这里,整个循环是“扁平的”。
迭代器用于访问map
. 递增迭代器将指向map
.
注意:此技术适用于少量容器。然而,循环仍然是首选技术。
推荐阅读
- r - 在 open.connection(x, "rb") 中出现错误:HTTP 错误 504.while Web 抓取使用 rvest
- postgresql - 获取表中的列名列表(PostgreSQL)
- python-3.x - python函数中标题的自动化
- javascript - 反应库代码中的花括号是什么意思?
- android - Android Google Maps 可以在模拟器上运行,但不能在真实设备上运行
- oracle - 更改名称之间没有空格的所有表列
- powerquery - 我在这个用于电源查询的 M 代码功能中哪里出错了?
- java - 如何在tomcat上运行我的maven项目(angular+springboot)?
- makefile - 在 patsubst 中使用 % 两次
- javascript - 一种用于播放和暂停的可触摸不透明度