簡體   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