Busted
Busted

Reputation: 147

How to check if vector has element that starts with specific string

I want to know how to check if vector has element that starts with specific string.

I did that with code below in C#. But how can I do this in C++.

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

[Edit] I tried with code below but I think this is dirty solution when vector is huge. (My vector has elements over 400000) Is there a better solution for this?

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;

Upvotes: 3

Views: 585

Answers (2)

Kunal Puri
Kunal Puri

Reputation: 3427

A more elegent solution can be attained using <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;
});

Update:

You may use find()also. Something like this:

std::string strToBeSearched = "abc";

bool found = std::any_of(words.begin(), words.end(), [&strToBeSearched](const std::string &s) {
    return s.find(strToBeSearched) == 0;
});

Update 2:

As rightly suggested by @SidS, you may use rfind() also for better performance.

std::string strToBeSearched = "abc";

bool found = std::any_of(words.begin(), words.end(), [&strToBeSearched](const std::string &s) {
    return s.rfind(strToBeSearched, 0) == 0;
});

Upvotes: 2

Sid S
Sid S

Reputation: 6125

Your solution is pretty good.

Using string::rfind() is likely to be more efficient, since string::find() may search through the whole string :

    for (const auto &word : words)
    {
        if (!word.rfind("abc", 0))
        {
            hasValue = true;
            break;
        }
    }

Upvotes: 1

Related Questions