You can write completely a c++ code.
If you want to find all the elements satisfying the condition, you can not avoid iterating through the entire vector.
But you could use better range-based for-loop
instead of index based loop to iterate through the vector, and check wether str.find(substring) == 0
(credits @PiotrSkotnicki).
Here is the example code:
(See online)
#include <iostream>
#include <string>
#include <vector>
int main()
{
const std::string substring{ "bla" };
std::vector<std::string> vecString{ {"bllll"}, {"bllll"}, {"blasomething"} };
// iterate through the vector by range based for-loop
// here `auto` deduded to `std::string` as you have vector of strings(i.e. `vecString`)
for (const auto& str : vecString)
{
if (str.find(substring) == 0) {
std::cout << str << " is a match\n";
// do something more with str
}
}
return 0;
}
Alternatively using std::for_each
, along with a lambda function you could write the following. Read more about the lambdas here: What is a lambda expression in C++11?
(See online)
#include <algorithm> // std::for_each
std::for_each(std::cbegin(vecString), std::cend(vecString), [&substring](const auto& str)
{
if (str.find(substring) == 0)
{
std::cout << str << " is a match\n";
// do something more with str
}
});
If you are interested only the first match in the vector of string s, making use of standard algorithm std::find_if
as follows
#include <algorithm> // std::find_if
const auto iter = std::find_if(std::cbegin(vecString), std::cend(vecString),
[&substring](const auto& str) {
return str.find(substring) == 0;
}
);
if (iter != std::cend(vecString))
{
// do something
}