为什么max_element没有显示向量C++中最大的字符串

Why is max_element not showing the largest string in vector C++?

本文关键字:C++ 字符串 向量 显示 max element 为什么      更新时间:2024-09-23

在下面的代码中,我尝试使用std::max_element打印std::vector中最大的std::string

我预计下面代码的输出是:

Harmlessness

我得到的实际输出是:

This

代码:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector <string> strlist;
strlist.push_back("This");
strlist.push_back("Harmless");
strlist.push_back("Harmlessness");
cout << *max_element(strlist.begin(), strlist.end());
return 0;
}

我的问题:
你能解释一下为什么代码产生了上面的实际输出,而不是我预期的输出吗?

std::string的默认比较器执行字典比较(请参阅:std::string comparators(。

字符串"这个">按此顺序晚于以"em>"开头的任何字符串;H〃。

您可以使用std::max_element的另一个重载,它接受显式比较器参数:

模板<class ForwardIt,class比较>常量表达式ForwardIt max_element(ForwardIt first,ForwardIt last,比较comp(;

如果您想按长度比较字符串,可以使用:

#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector <std::string> strlist;
strlist.push_back("This");
strlist.push_back("Harmless");
strlist.push_back("Harmlessness");

// Use an explicit comparator, in this case with a lambda:
std::cout << *max_element(strlist.begin(), strlist.end(), 
[](std::string const& a, std::string const& b) {return a.length() < b.length(); });
return 0;
}

输出:

Harmlessness

旁注:最好避免using namespace std-请参阅此处"为什么";使用命名空间std"被认为是不好的做法?。