c++ - 错误: cannot convert ‘std::vector<float>’ to ‘float’ in initialization

标签 c++ c++11 struct error-handling stdvector

我已经将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/

相关文章:

C++ 对类数据成员的引用

c++ - 使用 clang++ 3.2 初始化 'vector<string>' 没有匹配的构造函数

c++ - 为什么 std::stoi 和 std::array 不能用 g++ c++11 编译?

c++ - union 和 struct 的字节大小

C++ fstream 找不到相对路径

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - 序列化函数对象

C++ 使用结构图

c++ - 结构成员的模板函数

c++ - C++ 中的 jit 汇编程序,使用 C 函数