我有一个 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/