首页 > 解决方案 > 在向量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;
    }

标签: c++search

解决方案


您可以使用标准算法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

推荐阅读