小编Dhr*_*nna的帖子

矢量中的push_back是否插入到同一位置?

class Example
{
    public: int i;
    Example(const Example &e)
    {
        i = e.i;
    }
    Example(int i)
    {
        this->i = i;
    }
};

int main()
{
std::vector<Example*> vec;
std::vector<Example*> newVec;

Example* ex1 = new Example(1);
Example* ex2 = new Example(2);

vec.push_back(ex1);
vec.push_back(ex2);

//newVec = vec; --> This does shallow copy

for(int i=0; i<vec.size(); ++i) // --> Deep copy
{
    Example newE(*(vec[i]));
    newVec.push_back(&newE);
}

for(int i=0; i<newVec.size(); ++i)
{
    std::cout << "\nfoobar" << newVec[i]->i << "\n";
}
}
Run Code Online (Sandbox Code Playgroud)

上面的代码打印两次foobar2.它不应该打印foobar1和foobar2?另外,这是复制包含对象的矢量的最佳方法吗?我想深刻复制.

c++ pointers vector

0
推荐指数
1
解决办法
154
查看次数

标签 统计

c++ ×1

pointers ×1

vector ×1