c++ - 从 vector<string> 中查找字符串的第一次出现

标签 c++ boost std

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

例如

InputStr = "this certainly helps";

对于 vector 中的给定字符串,我想要一种方式来表示 "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

此实现有效,但我想知道是否存在使用 boost 库或 std 库执行此操作的更优雅的方法。

我在 Windows 上工作并使用 Visual Studio 2010。

最佳答案

这是一个 MapReduce 问题。

首先,你想从vector<string>vector<int> ,它们的位置,这是一张 map ,然后你想将这些值减少到一个值的最小值,这是一个减少。首先是 map 。这是 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);
    }
);

现在我们简单地使用std::min_element得到最小的元素,reduce。

auto iterator = std::min_element(positions.begin(), positions.end());
int index = *iterator;

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

string found = stuff[iterator - positions.begin()];

关于c++ - 从 vector<string> 中查找字符串的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609821/

相关文章:

c++ - boost::locale::to_lower 抛出 bad_cast 异常

c++ - boost asio 读取动态大小消息

c++ - 是否可以在 [win-builder](http ://win-builder. r-project.org/) 上构建一个使用 Rcpp 和 Boost.Thread 的 R 包?

c++ - (bool) cast 的默认行为

c++ - 更简单的方法来写这个 if 函数 c++

c++ - C 和 C++ 的某些标准之间的差异

c++ - Boost 1.46.1,属性树 : How to iterate through ptree receiving sub ptrees?

c++ - C++ 中 std::cout 的奇怪行为

c++ - 指向特征数据 `std::list` 的指针

C++ 线程 : what does join do exactly?