C++ Reference: Standard C++ Library reference: Containers: array: array: operators

发布于:2022-11-15 ⋅ 阅读:(427) ⋅ 点赞:(0)

C++官网参考链接:https://cplusplus.com/reference/array/array/operators/

函数模板 
<array>
std::relational operators (array)
template <class T, size_T N>  bool operator== ( const array<T,N>& lhs, const array<T,N>& rhs );
template <class T, size_T N>  bool operator!= ( const array<T,N>& lhs, const array<T,N>& rhs );
template <class T, size_T N>  bool operator<  ( const array<T,N>& lhs, const array<T,N>& rhs );
template <class T, size_T N>  bool operator<= ( const array<T,N>& lhs, const array<T,N>& rhs );
template <class T, size_T N>  bool operator>  ( const array<T,N>& lhs, const array<T,N>& rhs );
template <class T, size_T N>  bool operator>= ( const array<T,N>& lhs, const array<T,N>& rhs );
array的关系操作符
array容器lhsrhs之间执行适当的比较操作。
相等比较(operator==)是通过使用operator==顺序比较元素来执行的,在第一个不匹配处停止(就像使用算法equal)。
小于比较(operator<)的行为类似于使用算法lexicographical_compare,它使用operator<以互反方式按顺序比较元素(即检查a<b和b<a)并在第一次出现时停止。
其他操作也在内部使用operator==和<来比较元素,就像执行了以下等价操作一样:

operation equivalent operation
a!=b !(a==b)
a>b b<a
a<=b !(b<a)
a>=b !(a<b)

这些操作符在头文件<array>中重载。 

形参 
lhs,rhs
array容器(分别位于操作符的左边和右边),具有相同的模板形参(T和N)。

用例
// array comparisons
#include <iostream>
#include <array>

int main ()
{
  std::array<int,5> a = {10, 20, 30, 40, 50};
  std::array<int,5> b = {10, 20, 30, 40, 50};
  std::array<int,5> c = {50, 40, 30, 20, 10};

  if (a==b) std::cout << "a and b are equal\n";
  if (b!=c) std::cout << "b and c are not equal\n";
  if (b<c) std::cout << "b is less than c\n";
  if (c>b) std::cout << "c is greater than b\n";
  if (a<=b) std::cout << "a is less than or equal to b\n";
  if (a>=b) std::cout << "a is greater than or equal to b\n";

  return 0;
}
输出:

返回值
如果条件成立,则为true,否则为false。 

复杂性 
size(N)中最高达到线性。

迭代器有效性
没有变化。

数据竞争
lhsrhs中包含的所有元素都可以被访问。

异常安全
如果元素的类型支持带有无抛出保证的适当操作,则该函数永远不会抛出异常(无抛出保证)。
在任何情况下,函数都不能修改它的实参。 


网站公告

今日签到

点亮在社区的每一天
去签到