gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:13:29 26 4
gpt4 key购买 nike

对于以下代码,为什么输出为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);
}

最佳答案

他们使用标准算法std::lexicographical_compare
根据C++标准中算法的描述

3 Remarks: If two sequences have the same number of elements and their corresponding elements (if any) are equivalent, then neither sequence is lexicographically less than the other. If one sequence is a prefix of the other, then the shorter sequence is lexicographically less than the longer sequence. Otherwise, the lexicographical comparison of the sequences yields the same result as the comparison of the first corresponding pair of elements that are not equivalent.



您的示例的输出是 bool(boolean) 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;
}

关于c++ - 如何在C++中比较std::array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com