[英]Extract strings that don't contain 0 from vector<pair<string, int>>
I'm trying to find out strings that don't have zero. 我试图找出不为零的字符串。
The incoming data: (strings are in order but values or not) 传入数据:(字符串按顺序排列,但不包含值)
std::vector<std::pair<std::string, int>> data =
{
{"A", 3},
{"A", 0},
{"A", 1},
{"B", 2},
{"B", 0},
{"C", 2},
{"D", 0},
{"D", 1},
{"E", 3},
{"E", 4}
};
The result I want to get: (strings that don't contain zero) 我想得到的结果:(不包含零的字符串)
C, E
C,E
Here's my so far code that doesn't work: 这是到目前为止我无法使用的代码:
#include <iostream>
#include <string>
#include <vector>
#include <utility>
int main()
{
std::vector<std::pair<std::string, int>> data =
{
{"A", 3},
{"A", 0},
{"A", 1},
{"B", 2},
{"B", 0},
{"C", 2},
{"D", 0},
{"D", 1},
{"E", 3},
{"E", 4}
};
std::string previousStr = "";
bool hasZero = false;
std::vector<std::string> nonZeroStrs;
for (size_t i = 0; i < data.size(); ++i)
{
std::string currentStr = data[i].first;
if (currentStr != previousStr)
{
if (previousStr != "")
{
if (!hasZero)
nonZeroStrs.push_back(previousStr);
}
}
if (data[i].second == 0)
{
hasZero = true;
}
previousStr = currentStr;
}
for (size_t i = 0; i < nonZeroStrs.size(); ++i)
{
std::cout << nonZeroStrs[i] << '\n';
}
return 0;
}
You can use a map to remember if a certain key should not be included based on its second pair member. 您可以使用地图来记住是否应基于其第二对成员不包括某个特定钥匙。
std::unordered_map<std::string, bool> invalid;
for (auto const& p : data) {
if (p.second == 0) {
invalid[p.first] = true;
}
}
for (auto const& p : data) {
if (!invalid[p.first]) {
std::cout << p.first << '\n';
invalid[p.first] = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.