【问题标题】:How are std::array's compared in C++?如何在 C++ 中比较 std::array ?
【发布时间】:2020-02-11 18:47:39
【问题描述】:

对于下面的代码,为什么输出为 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 stl comparison-operators stdarray


【解决方案1】:

他们使用标准算法std::lexicographical_compare

来自C++标准中算法的描述

3 备注:如果两个序列有相同数量的元素和它们的 对应的元素(如果有的话)是等价的,那么这两个序列都不是 在字典上小于另一个。如果一个序列是前缀 另一个,那么较短的序列在字典上小于 较长的序列。否则, 序列产生与第一个比较相同的结果 不等价的对应元素对。

您的示例的输出是布尔值true,即“...与不等价的第一对对应元素的比较结果相同。”

对于您的示例,比较结果(a &lt; b) 是比较结果( a[0] &lt; 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;
}

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多