C++ valarray 与向量
我非常喜欢矢量.它们既漂亮又快速.但我知道这个叫做 valarray 的东西是存在的.为什么我要使用 valarray 而不是向量?我知道 valarrays 有一些语法糖,但除此之外,它们什么时候有用?
I like vectors a lot. They're nifty and fast. But I know this thing called a valarray exists. Why would I use a valarray instead of a vector? I know valarrays have some syntactic sugar, but other than that, when are they useful?
推荐答案
Valarrays(值数组)旨在将 Fortran 的某些速度带到 C++.您不会创建一个 valarray 指针,因此编译器可以对代码做出假设并更好地优化它.(Fortran 这么快的主要原因是没有指针类型,所以不能有指针别名.)
Valarrays (value arrays) are intended to bring some of the speed of Fortran to C++. You wouldn't make a valarray of pointers so the compiler can make assumptions about the code and optimise it better. (The main reason that Fortran is so fast is that there is no pointer type so there can be no pointer aliasing.)
Valarrays 也有允许你以相当简单的方式将它们切片的类,尽管标准的那部分可能需要更多的工作.调整它们的大小是破坏性的,并且它们缺少迭代器 自 C++11 以来它们就有迭代器.
Valarrays also have classes which allow you to slice them up in a reasonably easy way although that part of the standard could use a bit more work. Resizing them is destructive and they lack iterators they have iterators since C++11.
因此,如果您使用的是数字并且使用方便并不是那么重要,请使用 valarrays.否则,向量就方便多了.
So, if it's numbers you are working with and convenience isn't all that important use valarrays. Otherwise, vectors are just a lot more convenient.
相关文章