vector :: push_back()是一个浅拷贝&怎么解决这个问题

时间:2011-07-16 13:53:38

标签: c++ vector struct shallow-copy

在我写的程序中,我有类似代码的内容:

#include<iostream>
#include<vector>
#include<cstring>

using namespace std;

struct people
{
    string name;
    int st;
    int sn[50];
};

int main()
{
    unsigned int n,ST[10]={25,18,15,12,10,8,6,4,2,1};
    vector<people> master;
    cin>>n;
    for (int i=0;i<n;i++)
    {
        unsigned int m;
        cin>>m;
        for (int j=0;j<m;j++)
        {
            people youngling; //I am declaring it here, but it doesn't solve the issue
            string s;
            cin>>s;
            for (int l=0;l<master.size();l++)
            {
                if (master[l].name.compare(s)==0)
                {
                    if (j<10) master[l].st+=ST[j];
                    master[l].sn[j]++;
                    goto loop;
                }
            }
            youngling.name=s;
            if (j<10) youngling.st=ST[j];
            for (int l=0;l<50;l++) youngling.sn[l]=0;
            youngling.sn[j]++;
            master.push_back(youngling);
            loop:;
        }
    }
}

如您所见,我正在将结构(people youngling)推回到向量(vector<people> master)中。但是,这段代码给了我错误的结果,我认为它可能是由struct和浅拷贝问题引起的。这有点被证明,因为如果我使用完整的people数组来存储输入,那么答案是正确的。但我对此感到困惑:

  1. struct只是一个指向编译器的指针,或者为什么存在这个浅拷贝问题?
  2. 我在内循环中声明people youngling,希望解决这个问题,但没有用。有没有简单的方法来纠正上面的代码片段?
  3. 当我使用GCC 4.4测试小病例时,答案似乎是正确的。但是,当我测试它使用gnu C ++ 0X时,答案是错误的。这是编译器特定的问题吗?
  4. 注意:由于我使用评判系统在线测试,因此无法提供错误的测试用例。

1 个答案:

答案 0 :(得分:14)

push_back正在使用其复制构造函数来插入对象的副本。如果没有自定义的(如果你的结构),默认只是复制所有字段,使用自己的复制构造函数等。

对于你的struct - 包含一个字符串和一个固定大小的基本类型数组 - 结果应该等同于深层复制。