在C ++中初始化一个指针向量

时间:2014-03-03 23:33:18

标签: c++ vector initialization

Point P0(0,0), P1(3, 4), P2(-50,-3), P3(2,0); //Input  Points (fine)
std::vector<Point>  Points(P0,P1, P2 ,P3); (not fine)

这似乎不起作用。如何将点矢量初始化为上述值?或者有更简单的方法吗?

3 个答案:

答案 0 :(得分:5)

如果您使用的是c ++ 11,则可以使用大括号来内联声明向量。

std::vector<Point> Points {P0, P1, P2, P3};

答案 1 :(得分:4)

尝试以下代码(未经测试):

Point P0(0,0), P1(3, 4), P2(-50,-3), P3(2,0); //Input  Points (fine)
std::vector<Point> Points;

Points.push_back(P0);
Points.push_back(P1);
Points.push_back(P2);
Points.push_back(P3);

答案 2 :(得分:1)

无需定义Point类型的对象来定义向量。你可以写

std::vector<Point>  Points{ { 0, 0 }, { 3, 4 }, { -50,-3 }, { 2, 0 } };

前提是您的编译器支持大括号初始化。或者您可以定义Point数组并使用它来初始化向量。例如

#include <vector>
#include <iterator>
//,,,
Point a[] = { Point( 0, 0 ), Point( 3, 4 ), Point( -50,-3 ), Point( 2, 0 ) };
std::vector<Point>  Points( std::begin( a ), std::end( a ) ) ;

此代码将由MS VC ++ 2010编译。