![](/img/trans.png)
[英]inserting in a vector of vector string from vector vector of vector pair<int,string>
[英]Extract strings that don't contain 0 from vector<pair<string, int>>
我試圖找出不為零的字符串。
傳入數據:(字符串按順序排列,但不包含值)
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}
};
我想得到的結果:(不包含零的字符串)
C,E
這是到目前為止我無法使用的代碼:
#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;
}
您可以使用地圖來記住是否應基於其第二對成員不包括某個特定鑰匙。
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.