c++ - 在向量c ++中找到最长的单词
问题描述
所以我有一个包含大约 106,000 个单词的 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;
}
解决方案
您可以使用标准算法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';
}
输出:
The longest word is ccc at (zero-based) pos 2
推荐阅读
- c# - 在特定游戏对象上启用/禁用另一个脚本?
- java - 如何在android studio中重新打开应用程序后打开最近的活动
- python - 在 yapfignore 中包含的文件上预提交 yapf 失败
- r - ENMeval 教程后的 sf_buffer 结果不正确
- amazon-web-services - 无法在 AWS 上编辑权限 JSON,尽管它告诉我我可以
- cartopy - 无法使用 cartopy 显示经纬度和海岸线
- django - 将主页和关于页面添加到 Django 动态 sitemap.xml
- python - 如果它在字符串中并导致错误,则返回错误消息 - Python 3
- php - 在 Laravel 8 中使用 $errors 变量包含额外的验证
- java - Maven - 从多模型项目中构建几个模块