stl vector and c++: how to .resize without a default constructor?

妖精的绣舞 提交于 2019-11-28 07:16:11

Use the 2-argument overload: many_things.resize(20, something(5));

I can think of a solution, but iwarn you, it's rather ugly. I don't know why you do not want to add a default constructor, but if you just want to prevent users of the class to create unintialized instances, you can just make the default constructor private and declare the appropriate vector class a friend :

class Foo {
public:
   Foo( int x ) : num( x ) {}

   int GetX( ) { return num; }
private:
   friend class std::vector< Foo >;

   int num;
   Foo( ) : num( 10 ) {}
};

This is ugly for several reasons, mostly because it only works for one container type. There is no other way, because STL containers simply require their items to be default constructible.

You could use reserve() to increase the buffer size and manually add (push_back()) the necessary items in a loop.

With specialization alike this (sorry, I wrote this with only minimal checks)?

#include <vector>

class MyClass
{
    private:
        MyClass();
    public:
        MyClass(unsigned i) : _data(i) {};

    private:
        unsigned _data;
};

typedef std::vector<MyClass> MyVector;

void MyVector::resize(MyVector::size_type new_size)
{
    this->resize(new_size, MyClass(5));
}

int main()
{
    MyVector vector;
    vector.resize(5);

    return 0;
}

But think if you really need it. Why not to create default constructor instead?

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