如何在C ++中比较std :: array?

问题描述 投票:-2回答:1

对于下面的代码,为什么输出为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);
}
c++ c++11 c++-standard-library comparison-operators stdarray
1个回答
2
投票

他们使用标准算法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;
}
© www.soinside.com 2019 - 2024. All rights reserved.