c++ - 如何从二维数组构建对象的 std::vector

标签 c++ arrays vector stl

我有 double 的 2D 数组(3D 坐标),我想从中创建一个 3D 点 vector 。直接的方法当然是简单的循环,但可能存在使用 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;
}

以上代码仅用于说明目的,只是为了说明基本要求——存在基本类型的二维数组,我需要从中构建对象 vector 。

我可以控制 point_3d 类,因此可以根据需要添加更多构造函数。

最佳答案

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

std::vector<point_3d> build_tetrahedron_vertices()
{
    return std::vector<point_3d>{std::begin(coordinates), std::end(coordinates)}; 
}

然后你可以简单地称它为

std::vector<point_3d> points = build_tetrahedron_vertices();

并且由于 return value optimization ,您无需担心会执行此 vector 的额外拷贝。

Working demo

关于c++ - 如何从二维数组构建对象的 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480022/

相关文章:

c++ - 替换类似 STL 的 map 中的值

java - int binarySearch 数组列表

c - C语言中分数升序排列

c++ - 如何在 C++ 中做矩阵和 vector 之间的点积

r - 为回归方程选择合适的滞后以及如何解释 VARselect 的结果

c++ - 替代 C、C++?

c++ - 重载运算符*以获取对另一个类实例的引用

java - 如何将多个变量值存储到单个数组或列表中?

c++ - std::chrono::milliseconds 的 vector

c++ - C++ ABI 是否指定 vTable 和 RTTI 信息应该如何存在?