繁体   English   中英

从向量中提取不包含0的字符串 <pair<string, int> &gt;

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM