我已经将boundary_info
结构的 vector 定义为std::vector<boundary_info> nodes
,以便在我的代码中用于特定目的。当我尝试将特定元素中的新元素push_back
编码到此 vector 中时,如下所示:
void myFun()
{
std::vector<float_type> dists(9, -1.0);
std::array<float_type,9> f, g;
//do something - x and y are defined here
nodes.push_back(boundary_info{point<int>{x,y}, dists, f, g, {}});
}
我收到以下错误消息:
Error 1 : cannot convert ‘std::vector<float>’ to ‘float’ in initialization
Error 2 : cannot convert ‘std::array<float, 9ul>’ to ‘float’ in
initialization
Error 3 : cannot convert ‘std::array<float, 9ul>’ to ‘float’ in
initialization
错误1与
dists
相关,后者是一个 vector 。错误2和错误3与分别作为f, g
中的参数传递的push_back
相关联。代码如下所示。
#include <iostream>
#include <vector>
template <typename T>
struct point //specify a point structure
{
T x,y;
};
struct boundary_info
{
point<int> xy_bdary; //coordinates of a bdary point
std::array<float_type,9> dist; //distance from boundary
std::array<float_type,9> f_prev, g_prev; //populations
std::vector<int> miss_dirns; //missing directions
};
如果能指出该错误的解决方案,我将非常高兴。从半天开始,我一直在努力。
注意:我正在使用c++ 11进行编译。
编辑
您可以在以下位置找到此问题的最少代码,以再现同样的问题
https://repl.it/repls/GleefulTartMarkuplanguage
谢谢
最佳答案
在下面的行中,您尝试从std::array
(boundary_info::dist
)初始化std::vector
(dists
):
nodes.push_back(boundary_info{point<int>{x,y}, dists, f, g, {}});
std::array
没有接受std::vector
的构造函数。您只能按元素初始化std::array
(总体初始化),也可以将std::vector
显式复制到std::array
。汇总初始化
nodes.push_back(boundary_info{point<int>{x,y}, {dists[0], dists[1], dists[2], dists[3], dists[4], dists[5], dists[6], dists[7], dists[8]}, f, g, {}});
当然,这不是很优雅。
将
std::vector
复制到std::array
借助一些模板功能,我们可以做得更好。
template<typename T, std::size_t N, typename Range>
std::array<T,N> to_array( Range const& in )
{
std::array<T,N> result;
// To make the standard begin() and end() in addition to any user-defined
// overloads available for ADL.
using std::begin; using std::end;
std::copy( begin( in ), end( in ), result.begin() );
return result;
}
Live demo
to_array
接受具有begin()
和end()
成员函数或自由函数begin()
和end()
的重载的任何输入类型。现在,您可以像这样从 vector 初始化数组:
nodes.push_back(boundary_info{point<int>{x,y}, to_array<float_type,9>(dists), f, g, {}});
请注意,如果
dists
的元素多于数组,则可以轻松地将自己扔到脚上,因为to_array
不执行任何范围检查(std::copy
也不执行任何范围检查)。如果需要的话,我将其留给读者练习,以使该功能更安全。
关于c++ - 错误: cannot convert ‘std::vector<float>’ to ‘float’ in initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49836865/