我需要使用我创建的包含x,y double值的类来初始化我的向量。 是否有更好的方法来启动它?
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);
这里是CentroidXY.cpp
#include "CentroidXY.h"
CentroidXY::CentroidXY(double X, double Y)
{
m_X = X;
m_Y = Y;
}
CentroidXY::CentroidXY(void)
{
}
CentroidXY::~CentroidXY(void)
{
}
这里是CentroidXY.h
#pragma once
class CentroidXY
{
public:
CentroidXY(double X, double Y);
CentroidXY(void);
~CentroidXY(void);
double m_X;
double m_Y;
};
答案 0 :(得分:3)
我会使用初始化列表,因此请更改:
CentroidXY::CentroidXY(double X, double Y)
{
m_X = X;
m_Y = Y;
}
到此:
CentroidXY::CentroidXY(double X, double Y) : m_X(X), m_Y(Y)
{ }
此外,您可以更改此内容(因为您不需要temp
):
CentroidXY temp = CentroidXY(1504.907526094 , 1345.27375938);
centroids.push_back(temp);
到此:
centroids.push_back(CentroidXY(1504.907526094 , 1345.27375938));
或(相当于调用push_back):
centroids.emplace_back(CentroidXY(1504.907526094 , 1345.27375938));
甚至更好:
centroids.emplace_back(1504.907526094 , 1345.27375938);
这样代码更清晰。
答案 1 :(得分:3)
可以使用:
auto centroids = std::vector<CentroidXY>() = {
{ 1504.907526094, 1345.27375938 },
{ 1852.11101474414, 1354.88360797918 }
};
或者如果您无法忍受几乎始终自动(AAA),请使用:
std::vector<CentroidXY> centroids = {
{ 1504.907526094, 1345.27375938 },
{ 1852.11101474414, 1354.88360797918 }
};
答案 2 :(得分:1)
这个怎么样:
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 ) );