dsi*_*h99 1 c++ stl comparison-operators c++11 stdarray
对于下面的代码,为什么输出为 1?
#include<iostream>
#include<array>
int main() {
std::array<int, 5> a { 10, 11, 12, 15, 14 };
std::array<int, 5> b { 11, 12, 13, 14, 15 };
std::cout << (a < b);
}
Run Code Online (Sandbox Code Playgroud)
他们使用标准算法 std::lexicographical_compare
来自C++标准中算法的描述
3 备注:如果两个序列具有相同数量的元素并且它们对应的元素(如果有)是等价的,则两个序列在字典序上都不小于另一个。如果一个序列是另一个序列的前缀,则较短的序列在字典上小于较长的序列。否则,序列的字典序比较产生与不等价的第一对对应元素的比较相同的结果。
您的示例的输出是布尔值true,即“...与第一对不等价的对应元素的比较结果相同。”
对于您的示例,比较(a < b)的结果是比较的结果( a[0] < b[0] )
下面是一个演示程序。例如,您可以为类模板 std::vector 编写这样的运算符。
#include <iostream>
#include <iomanip>
#include <array>
#include <vector>
#include <iterator>
#include <algorithm>
template <typename T>
bool operator <( const std::vector<T> &a, const std::vector<T> &b )
{
return std::lexicographical_compare( std::begin( a ), std::end( a ),
std::begin( b ), std::end( b ) );
}
int main()
{
std::array<int, 5> a { 10, 11, 12, 15, 14 };
std::array<int, 5> b { 11, 12, 13, 14, 15 };
std::cout << std::boolalpha
<< std::lexicographical_compare( a.begin(), a.end(),
b.begin(), b.end() )
<< '\n';
std::vector<int> a1 { 10, 11, 12, 15, 14 };
std::vector<int> b1 { 11, 12, 13, 14, 15 };
std::cout << std::boolalpha << ( a1 < b1 ) << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)