我一直在尝试开始使用std::span<const T>
在我以前使用 const std::vector<T>&
的地方。我唯一的症结如下:
#include <iostream>
#include <vector>
#include <span>
#include <numeric>
double mean1(std::span<const double> vals) {
return std::accumulate(vals.begin(), vals.end(), 0.0) / vals.size();
}
double mean2(const std::vector<double>& vals) {
return std::accumulate(vals.begin(), vals.end(), 0.0) / vals.size();
}
int main() {
std::vector<double> foo = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
auto v = mean1(foo);
std::cout << v << "\n";
v = mean2( { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } );
std::cout << v << "\n";
v = mean1({ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } ); // << this is an error
std::cout << v << "\n";
}
我知道路过std:vector{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }
会起作用,但那是相当冗长的。 initializer_list
甚至更加冗长。只是想知道我是否在这里遗漏了一些明显的东西。
Visual Studio 的具体错误是
C2664 'double mean1(std::span<const double,18446744073709551615>)': cannot convert argument 1 from 'initializer list' to 'std::span<const double,18446744073709551615>'
我认为,基本上,std::span
没有采用初始值设定项列表的构造函数。
最佳答案
你可以使用
mean1( {{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }} );
调用原始数组构造函数。
如果你想指定类型,我建议
mean1( std::initializer_list{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } )
这可以防止潜在的另一个容器的构建。 (无论如何,它仍然构造一个 initializer_list
)
关于c++ - 将右值/临时集合传递给采用 std::span 的函数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73693061/