vector :: push_back()是一个浅层副本以及如何解决这个问题

zw3*_*324 4 c++ struct vector 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:;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

注意:由于我使用判断系统在线测试,因此无法提供错误的测试用例.

Xio*_*ion 14

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

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