简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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