Gilad
Gilad

Reputation: 6595

initializing a c++ vector with values

I need to init my vector with a class I have created holding x,y double values. is there a better way to init it?

std::vector<CentroidXY> centroids;
CentroidXY temp = CentroidXY(1504.907526094 , 1345.27375938);
centroids.push_back(temp);
temp = CentroidXY(1843.890860395045,1694.073652494);
centroids.push_back(temp);
temp = CentroidXY(1852.11101474414,1354.88360797918);
centroids.push_back(temp);

here is CentroidXY.cpp

#include "CentroidXY.h"

CentroidXY::CentroidXY(double X, double Y)
{
    m_X = X;
    m_Y = Y;
}
CentroidXY::CentroidXY(void)
{
}

CentroidXY::~CentroidXY(void)
{
}

here is CentroidXY.h

#pragma once
class CentroidXY
{
public:
    CentroidXY(double X, double Y);
    CentroidXY(void);
    ~CentroidXY(void);

    double m_X;
    double m_Y;
};

Upvotes: 2

Views: 269

Answers (3)

Robinson
Robinson

Reputation: 10132

Could use:

auto centroids = std::vector<CentroidXY>() = {
    { 1504.907526094, 1345.27375938 },
    { 1852.11101474414, 1354.88360797918 }
};

or if you can't stand Almost Always Auto (AAA), use:

std::vector<CentroidXY> centroids = {
    { 1504.907526094, 1345.27375938 },
    { 1852.11101474414, 1354.88360797918 }
};

Upvotes: 3

CinCout
CinCout

Reputation: 9619

How about this:

std::vector<CentroidXY> centroids;
centroids.push_back( CentroidXY( 1504.907526094 , 1345.27375938 ) );
centroids.push_back( CentroidXY( 1843.890860395045, 1694.073652494 ) );
centroids.push_back( CentroidXY( 1852.11101474414, 1354.88360797918 ) );

Upvotes: 1

gsamaras
gsamaras

Reputation: 73444

I would use an initialization list, so change this:

CentroidXY::CentroidXY(double X, double Y)
{
    m_X = X;
    m_Y = Y;
}

to this:

CentroidXY::CentroidXY(double X, double Y) : m_X(X), m_Y(Y)
{ }

Source

Moreover, you could change this (since you don't need temp):

CentroidXY temp = CentroidXY(1504.907526094 , 1345.27375938);
centroids.push_back(temp);

to this:

centroids.push_back(CentroidXY(1504.907526094 , 1345.27375938));

or (which is equivalent to calling push_back):

centroids.emplace_back(CentroidXY(1504.907526094 , 1345.27375938));

or even better:

centroids.emplace_back(1504.907526094 , 1345.27375938);

That way the code is cleaner.

Interesting link: push_back vs emplace_back

Upvotes: 3

Related Questions