I have a vector<string> vectorStrings with values: ta, bc, ac, st, cer, cda. I want to find the first occurrence of any of the strings in the vector in an input string.
e.g.
InputStr = "this certainly helps";
Of the given strings in the vector, I would want a way to say "cer" was the first occurrence at position 5.
int min = 9999999;
string first;
for(int i = 0; i < vectorStrings.size(); i++)
{
int pos = InputStr.find(vectorStrings[i]);
if(pos == string::npos)
continue;
if(pos < min)
{
min = pos;
first = vectorStrings[i];
}
}
// values of min and first gives which string occurred first
// and at the position of it in the input string
This implementation works, but I would want to know if there exists a more elegant way to do this with boost libraries or std library.
I am working on Windows and using Visual Studio 2010.
This is a MapReduce problem.
First, you want to go from
vector<string>tovector<int>, of their positions, which is a map, and then you want to reduce the values to one value by their minimum, which is a reduction. First, the map. This isstd::transform.Now we simply use
std::min_elementto get the smallest element, the reduce.To find the string that was found there, it’s a simple bit of iterator arithmetic: