首页 > 解决方案 > 检查地图值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 循环。

标签: c++maps

解决方案


让我们试试这个:

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.

注意:此技术适用于少量容器。然而,循环仍然是首选技术。


推荐阅读