【问题标题】:How to build std::vector of objects from 2D array如何从二维数组构建对象的 std::vector
【发布时间】:2015-09-09 12:50:17
【问题描述】:

我有一个 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;
}

上面的代码仅用于说明目的,以显示基本要求——基本类型的二维数组存在,我需要从中构建对象向量。

我可以控制 point_3d 类,所以如果需要可以添加更多的构造函数。

【问题讨论】:

    标签: c++ arrays vector stl


    【解决方案1】:

    您可以从每个一维数组构造一个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,您无需担心会执行此向量的额外副本。

    Working demo

    【讨论】:

    • @NathanOliver 谢谢!
    • 到时候你还不如直接改成std::vector&lt;point_3d&gt; points(std::begin(coordinates), std::end(coordinates));
    • @ʎǝɹɟɟɟǝſ 更好的是,他们可以删除全局数组 coordinates 并保留函数,但让它接受一个数组作为参数。
    • @CoryKramer 或者甚至更好地让它使用一对迭代器到任何Container。 #头脑风暴
    • 哇!这 C++11 的东西真是太棒了。
    【解决方案2】:

    尽管已经提供了很好的答案,但您可以使用一些 stl 函数。从build_tetrahedron_vertices_nice 的示例中,您可以使用基本相同的语法,但使用std::copy 而不是std::for_each

    void build_tetrahedron_vertices_nice(std::vector<point_3d> & points)
    {
        std::copy(&coordinates[0], &coordinates[num_vertices], std::back_inserter(points));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2017-08-27
      • 2021-06-16
      • 1970-01-01
      • 2013-12-05
      相关资源
      最近更新 更多