我正在将文件中的某些数据读入vector<struct>
。代码是这样的:
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ifstream fin("gift1.in", ios::in);
ofstream fout("gift1.out", ios::out);
unsigned short NP;
struct person
{
string name;
unsigned int gave;
unsigned int received;
};
vector<person> accounts;
string tmp_name;
fin >> NP;
accounts.resize(NP);
for (auto i : accounts)
{
fin >> tmp_name;
fout << "Just read this name: " << tmp_name << "\n";
i.name = tmp_name;
i.gave = 0;
i.received = 0;
fout << "We have just created this person: " << i.name << ";" << i.gave << ";" << i.received << "\n";
//(1)
// OK, this part works
}
fout << "Freshly created ledger:\n";
for (auto l : accounts)
fout << "Person: " << l.name << "; Gave: " << l.gave << ";Received " << l.received << "\n";
//irrelevant stuff further
}
问题是名称在(1)
循环中打印出来,但它们不在循环范围内。
为什么会这样?
示例输出为:
Just_read_this_name:_mitnik We_have_just_created_this_person:_mitnik; 0; 0 Just_read_this_name:_Poulsen We_have_just_created_this_person:_Poulsen; 0; 0 Just_read_this_name:_Tanner We_have_just_created_this_person:_Tanner; 0; 0 Just_read_this_name:_Stallman We_have_just_created_this_person:_Stallman; 0; 0 Just_read_this_name:_Ritchie We_have_just_created_this_person:_Ritchie; 0; 0 Just_read_this_name:_Baran We_have_just_created_this_person:_Baran; 0; 0 Just_read_this_name:_Spafford We_have_just_created_this_person:_Spafford; 0; 0 Just_read_this_name:_Farmer We_have_just_created_this_person:_Farmer; 0; 0 Just_read_this_name:_Venema We_have_just_created_this_person:_Venema; 0; 0 Just_read_this_name:_Linus We_have_just_created_this_person:_Linus; 0; 0 Freshly_created_ledger: 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 联系人:_; _都给:_0; Received_0 人:_; _都给:_0; Received_0
答案 0 :(得分:7)
for (auto i : accounts)
您获得的每个i
都是accounts
中元素的副本。执行i.name = tmp_name
时,您只需修改此副本。您需要使用引用,以便您可以自己修改元素:
for (auto& i : accounts)