使用 C++,尝试使用 for 循环和 std::max 在向量中找到最大的单词

Using C++, trying to find the largest word in a vector using a for-loop and std::max

我正在尝试使用 C++ 组合一个 for 循环,以查找字符串向量中的最大单词。我知道可以通过比较字长来做到这一点。所以这只是想知道一些细节并学习一些关于 C++ 的东西,我不明白为什么这行不通:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  std::string test = "this is a test string for sentence length ranks";
  std::vector<std::string> words = {"this", "is", "a", "test", "string", 
  "for", "sentence", "length", "ranks"};

  std::string temp = "";
  std::string largest = "";
  for (int i = 0; i != words.size(); ++i) {
    std::cout << "words[" << i << "]: " << words[i] << " "; 
    std:: cout << std::endl;
    temp = std::max(temp, words[i]);
    largest = std::max(temp, largest);
    std::cout << "the biggest word is " << largest << std::endl;
  }
return 0;
}

它returns这个:


更新:

这里的答案帮助我指明了正确的方向。事实证明,std::max 的另一个功能称为 'comp'。我几乎看不懂,但这似乎有效:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  std::string test = "this is a test string for sentence length ranks";
  std::vector<std::string> words = {"this", "is", "a", "test", "string", 
  "for", "sentence", "length", "ranks"};

  std::string tempword;
  std::string longword;
  int longwordint = 0;
  for (int i = 0; i != words.size(); ++i) {
    int wordlength = words[i].length();
    longwordint = std::max(longwordint, wordlength);

    tempword = words[i];
    longword = std::max(longword, tempword, 
              [](std::string longword, std::string tempword) 
              { return (longword.size() < tempword.size()); });

    std::cout << "the biggest word so far is " << longwordint;
    std::cout <<" letters long: " << longword;
    std::cout << " | the tempword is: " << tempword << std::endl;
  }
return 0;
}

您可以使用 std::max_element 来查找向量字符串中的最大单词。

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  std::string test = "this is a test string for sentence length ranks";
  std::vector<std::string> words = {"this", "is", "a", "test", "string", 
  "for", "sentence", "length", "ranks"};

    auto largest = std::max_element(words.begin(), words.end(), [](const auto& s1, const auto& s2){
      return s1.size() < s2.size();
    });
    std::cout << "the biggest word is " << *largest << std::endl;

return 0;
}

std::max 将事物与正常比较进行比较,对于字符串,比较它们的字典顺序,而不是它们的长度。所以你循环中的所有结果都符合预期。