C++ 实例化一个新的 stl 向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/970498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:10:32  来源:igfitidea点击:

instantiate a new stl vector

c++stl

提问by np-hard

I have a situation where i have a pointer to an stl vector

我有一个指向 stl 向量的指针的情况

so like

很喜欢

vector<MyType*>* myvector;

I have to set this pointer to NULL in the constructor and then lazy load when property is touched.

我必须在构造函数中将此指针设置为 NULL,然后在触摸属性时延迟加载。

how can i instantiate this to a new instance of a vector ?

如何将其实例化为向量的新实例?

回答by Martin York

Assuming you define vector correctly:

假设您正确定义了向量:

vector<int>*   myvector;  // Note vector must be parametrized with a type.
                          // There is no such thing as a a naked vector.

Initialize to NULL

初始化为 NULL

myclass::myclass()
   :myvector(NULL)       // You can use 0 here but I still like NULL because it
{}                       // gives me more information. Waiting for the new keyword.

Instantiate on first use:

首次使用时实例化:

myvectr = new vector<int>(100); // reserve some space as appropriate

But you should not have RAW pointer as a member to your class (unless there is a very good reason). You will need to write your own copy constructor and assignment operator.

但是您不应该将 RAW 指针作为类的成员(除非有很好的理由)。您将需要编写自己的复制构造函数和赋值运算符。

Or alternatively you can wrap 'myvector' with a smart pointer. Or even better make it a normal vector. There is no real need to make it a pointer.

或者,您可以使用智能指针包装“myvector”。或者甚至更好地使其成为法线向量。没有真正需要使它成为一个指针。

回答by Johannes Schaub - litb

I have to set this pointer to NULL in the constructor and then lazy load when property is touched.

How can i instantiate this to a new instance of a vector ?

我必须在构造函数中将此指针设置为 NULL,然后在触摸属性时延迟加载。

如何将其实例化为向量的新实例?

I'm not sure i understand you all the way. Why not simply leave the vector empty, and set a boolean that says whether the property was loaded or not? Alternatively, you can use boost::optional

我不确定我是否完全理解你。为什么不简单地将向量留空,并设置一个布尔值来说明该属性是否已加载?或者,您可以使用boost::optional

boost::optional< vector<MyType*> > 

Or

或者

boost::optional< vector< shared_ptr<MyType> > >

You can then simply receive the object by dereferencing the optional object, and assign a vector to it like usual.

然后,您可以通过取消引用可选对象来简单地接收该对象,并像往常一样为其分配一个向量。

I would not use a pointer for this. It complicates the matter, and you have to think about what happens when you copy the object containing the property, ...

我不会为此使用指针。它使问题复杂化,您必须考虑复制包含该属性的对象时会发生什么,...

If you really have to use a pointer, you can do it like this

如果你真的必须使用指针,你可以这样做

struct A {
    A():prop() { }
    ~A() { delete prop; }

    vector< MyType *>& get() { 
        if(!prop) prop = new vector< MyType* >();
        return prop;
    }

private:
    // disable copy and assignment. 
    A(A const&);
    A& operator=(A const&);
    vector< MyType* > *prop;

};

Or use shared_ptr, which would be the way to go in my program (but boost::optional would still be first option, after which would be the vector-and-boolean option, after which would be the following)

或者使用shared_ptr,这将是我程序中的方法(但 boost::optional 仍然是第一个选项,之后是 vector-and-boolean 选项,之后是以下选项)

struct A {
    typedef vector< shared_ptr<MyType> > vector_type;

    vector_type &get() { 
        if(!prop) { 
            prop.reset(new vector_type);
        }
        return *prop;
    }

private:
    // disable copy and assignment. 
    A(A const&);
    A& operator=(A const&);
    shared_ptr< vector_type > prop;         
};

Copy and assignment are disabled, as they would share the prop behind the scene (shallow copy), which should be either clearly documented or disabled by deep copying in these functions.

复制和分配被禁用,因为它们会在幕后共享道具(浅复制),应该清楚地记录或通过在这些函数中进行深复制来禁用。

回答by Nikolai Ruhe

myvector = new std::vector<yourtype>;

回答by Nikolai Ruhe

You cannot haved a pointer like this:

你不能有这样的指针:

vector* myvector;

because vector is a template class and must have a type. You could say:

因为 vector 是一个模板类,必须有一个类型。你可以说:

vector <int> * myvector = 0;

or:

或者:

vector <string> * myvector = 0;

and then dynamically create a vector:

然后动态创建一个向量:

myvector = new vector <string>;

回答by Skurmedel

Well to initialize it you will need to at least set it to NULL or an instance like below using that syntax. Also you should do it in the order the fields are declared otherwise weird stuff might happen.

好吧,要初始化它,您至少需要使用该语法将其设置为 NULL 或如下所示的实例。此外,您应该按照声明字段的顺序进行操作,否则可能会发生奇怪的事情。

// Field.
std::vector<int> *myvector;
// Constructor.
myclass() : myvector(new std::vector<int>) 
{ 
}