所以我有一个包含大约 106 千个单词的 c++ 向量,这些单词存储在vector<string>words
我需要找到这个向量中最长的单词,我还需要获取单词所在的位置,例如 (1,2,3) 在我的向量。我需要这个位置,因为我还有另外两个具有单词含义和类型的向量。vector<string>definition, vector<string>type
请帮忙
我当前的代码
此代码根本不起作用
copy_if(words.begin(), words.end(), back_inserter(length), [](const string& x) { return x.length() > 40; });// looks for words longer than 7 letters
for (const string& s : length)
{
cout << "found!!" << endl;
auto i = find(words.begin(), words.end(), s);//looks for the word in the words vector
if (i != words.end())
{
auto pos = i - words.begin();
//displays the word, type and the definition of the word that the user has entered
cout << "Word : " << words[pos] << '\n';
cout << "Type : " << definitions[pos] << '\n';
cout << "Definition: " << types[pos] << '\n';
cout << '\n';
}
else
cout << "word not found" << endl;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用标准算法std::max_element
搜索vector<string>
.
例子:
#include <algorithm> // max_element
#include <iostream>
#include <iterator> // distance
#include <string>
#include <vector>
int main() {
std::vector<std::string> words{"a", "bb", "ccc"};
auto it = std::max_element(words.begin(), words.end(),
[](const auto& a, const auto& b) {
return a.size() < b.size();
});
std::cout << "The longest word is " << *it << " at (zero-based) pos "
<< std::distance(words.begin(), it) << '\n';
}
Run Code Online (Sandbox Code Playgroud)
输出:
The longest word is ccc at (zero-based) pos 2
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
691 次 |
最近记录: |