简体   繁体   English

在类构造函数上初始化向量

[英]Initializing a vector on a class constructor

I'm doing this A class which has a vector of B's. 我正在做一个具有B的向量的A类。 I'm initializing the vector on the constructor of the A class (I'm not sure if this is the right way, but it compiles). 我正在A类的构造函数上初始化向量(我不确定这是否正确,但是可以编译)。 Besides this, I'm having a problem because I don't want that when initializing the vector that it initializes himself with the default construtor of B() because this makes me do a for loop to set the value that I want. 除此之外,我还有一个问题,因为在初始化使用B()的默认构造函数初始化的向量时,我不希望这样做,因为这使我执行了一个for循环来设置所需的值。 It would be fine if the vector position stood NULL or stood 0 to size; 如果向量位置为NULL或大小为0,那就很好了;

class B{
    int _t;
public:
    B(){ _t = 1; }
    B(int t) : _t(t){}
 };



class A{
    std::vector<B> _b;
public:
    A(int size): _b(size){
        for(int i = 0; i < size; i++){
        _b[i].setNumber(i);
    }
};  


int main() {
    int n = 3;
    A _a(n);
    return 0;
}

You can simply let the vector be default constructed (empty), then emplace_back into it: 您可以简单地将向量默认构造(空),然后将emplace_back插入其中:

A(int size) {
   _b.reserve(size);
   for(int i = 0; i < size; i++){
     _b.emplace_back(i);
   }
}

If you are stuck with a pre-C++11 compiler, you can push_back B objects into it: 如果您使用的是C ++ 11之前的编译器,则可以将B个对象推入其中:

A(int size) {
   _b.reserve(size);
   for(int i = 0; i < size; i++){
     _b.push_back(B(i));
   }
}

The calls to std::vector::reserve are to avoid re-allocations as the vector grows in size. 调用std::vector::reserve是避免随着向量大小的增加而重新分配。

It does not compile. 它不会编译。 class B does not have a setNumber function. B类没有setNumber函数。 Initializing the vector to a size does not require you to do anything. 将向量初始化为一个大小不需要执行任何操作。 It would just default construct number of objects equal to the specified size. 它只会默认构造等于指定大小的对象数。 Vector has a reserve member function that allows you to allocate enough memory for some number of elements without actually constructing objects. Vector具有保留成员功能,可让您为某些数量的元素分配足够的内存,而无需实际构造对象。 Perhaps that is what you were seeking. 也许这就是您想要的。 Obviously leaving it empty until you are ready to perform some form of insertion is another option. 显然,在准备执行某种形式的插入之前将其保留为空是另一种选择。 Hopefully one or more of the posted answers will help. 希望一个或多个发布的答案会有所帮助。

class A{
    std::vector<B> _b;
public:
    A(int size){
        _b.reserve(size);
    }
};

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

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