简体   繁体   English

用C ++初始化一个向量pf点

[英]initialize a vector pf points in C++

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)

This does not seem to work. 这似乎不起作用。 How do I initialize points vector to the values above? 如何将点矢量初始化为上述值? Or is there an easier way to do this? 或者有更简单的方法吗?

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

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

Try the following code (not tested): 尝试以下代码(未测试):

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);

There is no need to define objects of type Point that to define the vector. 无需定义Point类型的对象来定义向量。 You could write 你可以写

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

provided that your compiler supports the brace initialization. 前提是您的编译器支持大括号初始化。 Or you could define an array of Point and use it to initialize the vector. 或者您可以定义Point数组并使用它来初始化向量。 For example 例如

#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 ) ) ;

This code will be compiled by MS VC++ 2010. 此代码将由MS VC ++ 2010编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM