std::valarray<T>::operator=

来自cppreference.com
< cpp‎ | numeric‎ | valarray
 
 
 
 
valarray<T>& operator=(const valarray<T>& other );
(1)
valarray<T>& operator=( valarray<T>&& other )noexcept;
(2) (C++11 起)
valarray<T>& operator=(const T& val );
(3)
valarray<T>& operator=(conststd::slice_array<T>& other );
(4)
valarray<T>& operator=(conststd::gslice_array<T>& other );
(5)
valarray<T>& operator=(conststd::mask_array<T>& other );
(6)
valarray<T>& operator=(conststd::indirect_array<T>& other );
(7)
valarray<T>& operator=(std::initializer_list<T> il );
(8) (C++11 起)

替换数值数组的内容。

1) 复制赋值运算符。如果 size()!= other.size(),那么首先如同通过 resize(other.size()) 重置 *this 的大小。*this 的每个元素被赋 other 的对应元素的值。
2) 移动赋值运算符。以 other 的内容替换 *this 的内容。此操作后 other 的内容未指定。如果 T 拥有非平凡的析构函数,那么此操作的复杂度可能是线性,其他情况下通常是常数。
3)val 的副本替换 *this 中的每个值。
4-7) 以广义的下标运算的结果替换 *this 的内容。如果 size()other 的长度不相等,或左侧的任何值依赖右侧的某个值(例如 v = v[v >2]),那么行为未定义。
8) 赋值初始化式列表 il 的内容。等价于 *this = valarray(il)

目录

[编辑]参数

other - 要赋值的另一数值数组(或掩码)
val - 用来初始化每个元素的值
il - 要赋值的初始化式列表

[编辑]返回值

*this

[编辑]异常

1,3-8) 可能会抛出由实现定义的异常。

[编辑]示例

#include <iomanip>#include <iostream>#include <valarray>   void print(constchar* rem, conststd::valarray<int>& v){std::cout<<std::left<<std::setw(36)<< rem <<std::right;for(int n : v)std::cout<<std::setw(3)<< n;std::cout<<'\n';}   int main(){std::valarray<int> v1(3); v1 =-1;// (3)从标量 print("从标量赋值:\t\t ", v1);   v1 ={1, 2, 3, 4, 5, 6};// (8)从不同大小的初始化式列表 print("从初始化式列表赋值:\t ", v1);   std::valarray<int> v2(3); v2 = v1[std::slice(0, 3, 2)];// (4)从切片数组 print("从位置 0 开始的每第 2 个元素: ", v2);   v2 = v1[v1 %2==0];// (6)从掩码数组 print("偶数值:\t\t\t ", v2);   std::valarray<std::size_t> idx ={0, 1, 2, 4};// 索引数组 v2.resize(4);// 从生成下标赋值时大小必须匹配 v2 = v1[idx];// (7)从间接数组 print("在位置 0、1、2、4 的值: ", v2);}

输出:

从标量赋值: -1 -1 -1 从初始化式列表赋值: 1 2 3 4 5 6 从位置 0 开始的每第 2 个元素: 1 3 5 偶数值: 2 4 6 在位置 0、1、2、4 的值: 1 2 3 5

[编辑]缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 624 C++98 other 的长度不是 size() 时,重载 (4-7) 的行为不明确 此时行为未定义
LWG 630 C++98 复制赋值运算符在 size()!= other.size() 时的行为未定义 此时先重置 *this 的大小
LWG 2071 C++98 移动赋值运算符在 size()!= other.size() 时会重置 *this 的大小 此时不需要重置大小
close