Cad*_*hon 2 c++ boost stdvector c++03 stdarray
编写一个接口,我必须将 的实例转换std::vector<double>为boost::array<double,N>. 每次,通过构造(没有错误),我确定向量具有正确的大小。
这是我目前正在做的一个例子(我有大约 100 个这样的函数要写在界面中):
double foo1(const std::vector<double>& x)
{
assert(x.size() == 4);
boost::array<double,4> x_;
for(std::size_t i = 0; i < 4; ++i)
x_[i] = x[i];
return foo1_(x_);
}
double foo2(const std::vector<double>& x)
{
assert(x.size() == 6);
boost::array<double,6> x_;
for(std::size_t i = 0; i < 6; ++i)
x_[i] = x[i];
return foo2_(x_);
}
Run Code Online (Sandbox Code Playgroud)
有没有更短的方法来做到这一点?
注 1:出于兼容性原因,我不使用 C++11。
注 2:我添加了标签,stdarray因为即使它是 C++11 标签,它也可能有所帮助。
像这样的事情:
#include <boost/array.hpp>
#include <vector>
#include <boost/range/algorithm.hpp>
#include <iostream>
#include <cassert>
template<size_t Size, class Container>
boost::array<typename Container::value_type, Size> as_array(const Container &cont)
{
assert(cont.size() == Size);
boost::array<typename Container::value_type, Size> result;
boost::range::copy(cont, result.begin());
return result;
}
int main()
{
// this is C++11 initialization, but the rest of code is C++03-complient
std::vector<int> v{1, 2, 3};
boost::array<int, 3> a = as_array<3>(v);
boost::range::copy(a, std::ostream_iterator<int>(std::cout,", "));
}
Run Code Online (Sandbox Code Playgroud)
但请记住,从运行时到编译时容器的这种“转换”可能非常危险,因为其正确性依赖于assert,而在发布模式中已消除。
| 归档时间: |
|
| 查看次数: |
1764 次 |
| 最近记录: |