如何检查vector是否具有以特定字符串开头的元素

问题描述 投票:3回答:2

我想知道如何检查vector是否具有以特定字符串开头的元素。

我用C#中的代码完成了这个。但是我怎么能用C ++做到这一点。

if (Array.Exists(words, word => word.StartsWith("abc")))
{
    Console.WriteLine("Exists");
}

[编辑]我尝试使用下面的代码,但我认为当矢量很大时这是一个很难的解决方案。 (我的矢量元素超过400000)有更好的解决方案吗?

vector<string> words;
bool hasValue = false;

words.push_back("abcdef");
words.push_back("bcdef");
words.push_back("fffewdd");

for (string& word : words)
{
    if (word.find("abc") == 0)
    {
        hasValue = true;

        break;
    }
}

cout << hasValue << endl;
c++
2个回答
2
投票

使用qazxsw poi可以获得更优雅的解决方案。

<algorithm>

更新:

你可以使用std::string strToBeSearched = "abc"; bool found = std::any_of(words.begin(), words.end(), [&strToBeSearched](const std::string &s) { return s.substr(0, strToBeSearched.size()) == strToBeSearched; }); also。像这样的东西:

find()

更新2:

正如std::string strToBeSearched = "abc"; bool found = std::any_of(words.begin(), words.end(), [&strToBeSearched](const std::string &s) { return s.find(strToBeSearched) == 0; }); 正确建议的那样,你也可以使用@SidS来获得更好的性能。

rfind()

1
投票

你的解决方案非常好。

使用std::string strToBeSearched = "abc"; bool found = std::any_of(words.begin(), words.end(), [&strToBeSearched](const std::string &s) { return s.rfind(strToBeSearched, 0) == 0; }); 可能更有效率,因为string::rfind()可以搜索整个字符串:

string::find()
© www.soinside.com 2019 - 2024. All rights reserved.