从向量<string>中查找第一次出现的字符串

a n*_*a n 7 c++ boost std

我有一个vector<string> vectorStrings值:ta, bc, ac, st, cer, cda.我想在输入字符串中找到向量中第一个出现的任何字符串.

例如

InputStr = "this certainly helps";
Run Code Online (Sandbox Code Playgroud)

在向量中的给定字符串中,我想要一种方式来说明"cer"第一次出现在位置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
Run Code Online (Sandbox Code Playgroud)

这个实现有效,但我想知道是否有更优雅的方法来使用boost库或std库.

我正在使用Windows并使用Visual Studio 2010.

Pup*_*ppy 8

这是MapReduce问题.

首先,你想从去vector<string>vector<int>他们的位置,这是一个地图,然后要通过他们的最低,这是一个降低,可以降低值一个值.首先是地图.这是std::transform.

std::vector<std::string> stuff;
std::string input;
// fill stuff and input
std::vector<int> positions;
std::transform(
    stuff.begin(), 
    stuff.end(), 
    std::back_inserter(positions), 
    [&](std::string& stuff) {
        return input.find(stuff);
    }
);
Run Code Online (Sandbox Code Playgroud)

现在我们只是std::min_element用来获得最小的元素,即reduce.

auto iterator = std::min_element(positions.begin(), positions.end());
int index = *iterator;
Run Code Online (Sandbox Code Playgroud)

要找到那里找到的字符串,它是一个简单的迭代器算术:

string found = stuff[iterator - positions.begin()];
Run Code Online (Sandbox Code Playgroud)