【问题标题】:Can't read names from a vector of structs with string members无法从具有字符串成员的结构向量中读取名称
【发布时间】:2014-10-29 12:32:14
【问题描述】:

我正在将文件中的某些数据读入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) 循环中打印出来,但它们不在范围for 循环中。 为什么会这样?

示例输出如下:

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;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0 人:_;_给:_0;收到_0

【问题讨论】:

    标签: c++ vector struct fstream


    【解决方案1】:
    for (auto i : accounts)
    

    您获得的每个i 都是accounts 中一个元素的副本。当您执行i.name = tmp_name 时,您只是在修改此副本。您需要取而代之的是参考,以便您可以修改元素本身:

    for (auto& i : accounts)
    

    【讨论】:

    • 这对我来说应该很明显。不过还是谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多