c++ - Add of std::valarray got different sizes with different operand orders
问题描述
Add of std::valarray
got different sizes with different operand orders.
Code is as the following:
#include <iostream>
#include <valarray>
using namespace std;
int main() {
std::valarray<float> v0{3.f, 0.f};
std::valarray<float> v1{0.f};
std::valarray<float> v2 = v0 + v1;
std::valarray<float> v3 = v1 + v0;
cout << v2.size() << endl; // 2
cout << v3.size() << endl; // 1
}
Compilers:
g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
clang version 9.0.0-2~ubuntu18.04.2 (tags/RELEASE_900/final)
解决方案
operator+()
does not perfom concatenation of two std::valarray<float>
objects,
std::valarray<float> v2 = v0 + v1;
Here, since v1
is of size 1, it will add the only value in v1
to both the elements in v0
, hence size stays 2.
std::valarray<float> v2 = v1 + v0;
But here, v1
is of size 1, it will add the first element 3.f to the only element in v1
and second value of v0
is ignored.
This is what usually happens, but nevertheless the behaviour of binary operations on two valarray
s are undefined.
推荐阅读
- csh - 如何从两个字符串/列表中删除相同的目录/名称?
- azure - 如果在 azure 数据工厂中使用动态内容的逻辑函数,如何使用 else
- javascript - fullcalendar 为什么事件没有在 iPhone 上显示
- sql - Postgres左嵌套连接具有计数条件项
- c# - 如何在 C# 中使用 webview2 时忽略系统默认代理
- python - 将字符串转换为日期时间 [hh:mm:ss]
- php - laravel 从最近的 20 行中随机选择 5 行(加载后没有映射 & 只做一个查询)
- excel - 对象“_Global”的“范围”在“直到”中失败
- reactjs - 在 React Leaflet 的 MapContainer 的兄弟中使用 useMapEvents
- python-3.x - 从银行对账单中查找详细信息的正则表达式错误