Is using assign() a good way to initialise my C++ vector of structs?

旧巷老猫 提交于 2019-12-24 17:03:10

问题


The struct

struct Vanish
{
  int iCount;
  int iRow;
};

I defined a std::vector of Vanish as a member of my class, and want to initialise it in the constructor like this:

class BigClass
{
  public:
    BigClass();
  private:
    std::vector<Vanish> tovanish;
};

void BigClass::BigClass()
{
  Vanish empty = {0,0};
  tovanish.assign(MAX_VANISH, empty);
}

Is there a better way, or is this considered OK?


回答1:


It is better to do that in the constructor's initializer list:

BigClass::BigClass()
: tovanish(MAX_VANISH)
{

}

That way, you'll avoid possible vector reallocations. Note that you vector's constructor will value-initialize its elements. Value-initialization of the int members in Vanish just zeroes them.

Note that in C++11, using uniform-initialization you could specify other values easily:

BigClass::BigClass()
: tovanish(MAX_VANISH, {42, 24})
{

}



回答2:


Is there a better way?

Yes, sure,

BigClass::BigClass() : tovanish(MAX_VANISH) {}

This gives you a vector with MAX_VANISH value-initialized Vanish elements.



来源:https://stackoverflow.com/questions/17003126/is-using-assign-a-good-way-to-initialise-my-c-vector-of-structs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!