如何从2D数组构建std :: vector对象

one*_*ree 1 c++ arrays stl vector

我有二维2D阵列(3D坐标),我想从中创建一个3D点矢量.当然,直接的方法是简单的循环,但是使用stl算法可能会更优雅的解决方案存在吗?这是我得到的:

#include <algorithm>
#include <iterator>
#include <vector>

struct point_3d
{
  /**
   * Default constructor -- set everything to 0
  */
  point_3d() :
    x(0.0), y(0.0), z(0.0)
  {}

  /**
   * To define 3D point from array of doubles
  */
  point_3d(const double crd[]) :
    x(crd[0]),
    y(crd[1]),
    z(crd[2])
  {}

  /**
   * To define 3D point from 3 coordinates
  */
  point_3d(const double &_x, const double &_y, const double &_z) :
    x(_x), y(_y), z(_z)
  {}
  double x, y, z;
}; //struct point_3d

//Right-angle tetrahedron
const int num_vertices = 4;

const double coordinates[num_vertices][3] = 
{{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};

/**
 * Simple, but unelegant function.
*/
void build_tetrahedron_vertices(std::vector<point_3d>& points)
{
  points.clear();
  for(int i = 0; i < num_vertices; ++i)
    points.push_back(point_3d(coordinates[i]));
}//build_vector_of_points


/**
 * Something more elegant?
*/
void build_tetrahedron_vertices_nice(std::vector<point_3d>& points)
{
  points.clear();
  //this does not compile, but may be something else will work?
  std::for_each(&(coordinates[0]), &(coordinates[num_vertices]),
                std::back_inserter(points));
}//build_vector_of_points_nice

int main()
{
  std::vector<point_3d> points;
  build_tetrahedron_vertices(points);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

以上代码仅用于说明基本要求 - 存在基本类型的2D数组,我需要从中构建对象向量.

我可以控制point_3d类,因此如果需要可以添加更多构造函数.

Cor*_*mer 6

你可以point_3d从每个1d数组构造一个,所以我只使用带有std::vector两个迭代器的构造函数,并让每个1d数组用于隐含地构造一个point_3d

std::vector<point_3d> build_tetrahedron_vertices()
{
    return std::vector<point_3d>{std::begin(coordinates), std::end(coordinates)}; 
}
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地称之为

std::vector<point_3d> points = build_tetrahedron_vertices();
Run Code Online (Sandbox Code Playgroud)

由于返回值优化,您无需担心正在执行此向量的额外副本.

工作演示