3
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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Programmer
  • 421
  • 1
  • 7
  • 21
  • You might want to check http://stackoverflow.com/questions/2236197/c03-easiest-way-to-initialize-an-stl-vector-with-hardcoded-elements?rq=1 – Tony Delroy Mar 04 '14 at 00:12

3 Answers3

5

If you are using c++11, you can use braces to declare vectors inline.

std::vector<Point> Points {P0, P1, P2, P3};
Red Alert
  • 3,786
  • 2
  • 17
  • 24
4

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);
Spomky-Labs
  • 15,473
  • 5
  • 40
  • 64
3

There is no need to define objects of type Point that to define the vector. 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. 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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Brace-enclosed initializer lists and `std::begin` and `std::end` are all features of C++11 which may not be fully supported in older compilers. – Edward Mar 04 '14 at 00:30
  • @Edward I wrote clear that MS VC++ 2010 supports the last example in my post. – Vlad from Moscow Mar 04 '14 at 00:31
  • indeed you did. I was adding to your answer by naming the specification which added these features to the language so that others with different compilers will be able to understand what they need to be able to make use of your answer. – Edward Mar 04 '14 at 00:38