简体   繁体   English

从 std::variant 获取 substr <std::string, std::vector<std::string> &gt;&gt; 在 C++</std::string,>

[英]Getting a substr from a std::variant<std::string, std::vector<std::string>>> in C++

So I've got a map with a string key and either a string or vector value.所以我有一个带有字符串键和字符串或向量值的 map。 I want to cycle through all the string values (whether they're found in a vector or they can be directly checked) in the map and check if they match a given string (it's irrelevant what the string is).我想循环遍历 map 中的所有字符串值(无论它们是在向量中找到还是可以直接检查),并检查它们是否与给定字符串匹配(与字符串是什么无关)。 If that string matches completely or partly, I will put the map that the string was found in inside a vector.如果该字符串完全或部分匹配,我会将找到该字符串的 map 放入向量中。

The issue I'm having is that even though I'm separating strings from vectors using an if conditional the substr function thinks I'm dealing with a std::variant<std::string, std::vector<std::string>>> and therefore gives me an error.我遇到的问题是,即使我使用 if 条件将字符串与向量分开, substr function 认为我正在处理std::variant<std::string, std::vector<std::string>>>因此给了我一个错误。

The begin functions in the else functions also tell me that variant doesn't have a member called "begin" because of this reason. else 函数中的 begin 函数也告诉我,由于这个原因,variant 没有名为“begin”的成员。 I'm totally lost, any help would be great.我完全迷路了,任何帮助都会很棒。

for (std::unordered_map<std::string,
                        std::variant<std::string,
                        std::vector<std::string>>>::iterator h = MyMap.begin();
    h != MyMap.end();
    h++) {
    if (typeid(h->second) == typeid(std::string)) {
        std::string MapValueString = h->second.substr(0, TextCtrlValue.length());
        if (MapValueString == TextCtrlValue) {
            RightSearchResultsVector.insert(RightSearchResultsVector.end(), Maps.begin(), Maps.end());
        }
    }
    else {
        for (std::vector<std::string>::iterator f = h->second.begin(); f != h->second.end(); f++) {
            // Go through vector and find matching/semi matching strings
        }
    }
}

Here's how to tell what type a variant holds以下是如何判断变体持有什么类型

std::string* pstr = std::get_if<std::string>(&h->second);
if (pstr != nullptr)
{
    // do stuff with string
}
else
{
    std::vector<std::string>& vec = std::get<std::vector<std::string>>(h->second);
    // do stuff with vector
}

BTW you can simplify this monstrosity顺便说一句,你可以简化这个怪物

for (std::unordered_map<std::string,
                    std::variant<std::string,
                    std::vector<std::string>>>::iterator h = MyMap.begin();

by writing通过写作

for (auto h = MyMap.begin();

Judicious use of auto can greatly improve the readability of your code.明智地使用auto可以极大地提高代码的可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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