gpt4 book ai didi

c++ - 从 vector> 中提取不包含 0 的字符串

转载 作者:行者123 更新时间:2023-11-28 01:19:56 25 4
gpt4 key购买 nike

我正在尝试找出不包含零的字符串。

传入的数据:(字符串是有序的,但值与否)

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;
}
}

关于c++ - 从 vector<pair<string, int>> 中提取不包含 0 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56910804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com