找到向量中最长的单词c++

问题描述 投票:0回答:2

我有一个c++向量,其中包含大约106,000个单词,这些单词存储在

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
2个回答
7
投票

您可以使用标准算法

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

1
投票

我更喜欢简单地思考:只需根据每个索引检查元素的长度并据此更新信息。

std::vector<std::string> length;

// initialize the vector length

size_t max_length = 0; // the length of longest word(s)
std::vector<size_t> max_indice; // the indice of longest word(s)
for (size_t i = 0; i < length.size(); i++) {
    size_t this_len = length[i].length();
    if (this_len > max_length) {
        // new record
        max_length = this_len;
        max_indice.clear();
        max_indice.push_back(i);
    } else if (this_len == max_length) {
        // tie
        max_indice.push_back(i);
    }
}

for (size_t pos : max_indice) {
    cout << "Word      : " << words[pos] << '\n';
    cout << "Type      : " << definitions[pos] << '\n';
    cout << "Definition: " << types[pos] << '\n';
    cout << '\n';
}
© www.soinside.com 2019 - 2024. All rights reserved.