【发布时间】:2011-10-06 18:21:35
【问题描述】:
在我正在编写的程序中,我有类似这里的代码:
#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)。但是,这段代码给了我错误的结果,我认为这可能是由结构和浅拷贝问题引起的。这在一定程度上得到了证明,因为如果我使用完整的 people 数组来存储输入,那么答案是正确的。但我对此感到困惑:
- struct 只是指向编译器的指针,还是为什么存在这种浅拷贝问题?
- 我在内循环中声明
people youngling,希望能解决这个问题,但没有用。有什么简单的方法可以更正上面的sn-p代码吗? - 当我使用 GCC 4.4 对小型案例进行测试时,答案似乎是正确的。但是,当我使用 gnu C++0X 测试它时,答案是错误的。这是编译器特有的问题吗?
注意:我无法提供错误的测试用例,因为我正在使用裁判系统在线测试它。
【问题讨论】:
-
您需要在提交代码之前找到一种方法来测试您的代码。
-
@Alan:我在小案例上进行了测试,但结果和存储的信息都没有错误。这就是我感到困惑的地方:(
-
“gnu C++0X”是什么意思?
-
C++ 中没有“浅”与“深”副本的真正概念。忘记你曾经听过这两个术语。在 C++ 中,您只有正确与不正确的副本。每个对象通过实现一个复制构造函数来定义它是如何被复制的。
-
@Konrad:诚实的回答:我不知道。我正在使用一个名为 Codeforces 的网站,这就是他们所说的编译器。
标签: c++ vector struct shallow-copy