【问题标题】:Pushing back an object to a list in c++将对象推回C++中的列表
【发布时间】:2020-04-29 14:33:16
【问题描述】:

我在将对象推回对象列表时遇到问题。

std::ostream& operator << (std::ostream& os, const Class1& sk) {
    os << sk.X << 'x' << sk.Y << 'x' << sk.H << ';' << sk.a << ';' << sk.b << '\n';
    return os;
}

std::istream& operator >> (std::istream& is, Class1& sk) {
    char ch;
    is >> sk.X >> ch >> sk.Y >> ch >> sk.H >> ch >> sk.a >> ch >> sk.b >> ch;
    return is;
}

void Class1::GetSK_list(std::list<Class1>& SK_list) {
    std::ifstream file("file.txt", std::ios::in);
    std::list<Class1>::iterator iter = SK_list.begin();
    while(file >> *iter) {
        "std::cout << *iter"; // checking
        SK_list.push_back(*iter);
        iter++;
    }
    file.close();
}

void Class1::SaveSK_list(std::list<Class1>& SK_list) {
    std::ofstream file("file.txt", std::ios::out);
    for(std::list<Class1>::iterator iter = SK_list.begin(); iter != SK_list.end(); iter++)
        file << *iter;
    file.close();
}

当我使用 SaveSK_list 函数时,它可以正常工作。

问题出在 GetSK_list 函数上。如果文件中有一行(例如 1x2x3;4;5)文件 >> *iter 不起作用。没有打印任何内容(我相信 std::cout

如果文件中有多行,则只打印第一行。 After that std::bad_alloc error appears.

顺便说一句。这些函数都在 Class1 中,以便使用运算符重载。

【问题讨论】:

  • 如果在调用GetSK_listSK_list 为空,那么file &gt;&gt; *iter 将是未定义的行为。即使它不是空的,你的循环也没有多大意义。
  • "std::cout &lt;&lt; *iter".... 尝试不使用"。如果那是代码,您将看不到 std::cout 的输出
  • 而不是while(file &gt;&gt; *iter)(这是问题),读入Class1(例如Class1 temp;)和file &gt;&gt; temp的实例,然后调用.push_back(temp);
  • "(我相信 std::cout 使用您的调试器,确定。

标签: c++ list oop object operator-overloading


【解决方案1】:

你可以使用an insert iterator,它会自动调用列表中的push_back()

void GetSK_list(std::list<Class1>& SK_list) {
    auto iter = std::back_inserter(SK_list);

    std::ifstream file("file.txt", std::ios::in);
    Class1 tmp;
    while(file >> tmp) {
        *iter++ = tmp;
    }
    file.close();
}

结合istream_iteratorcopy 算法,您可以做得更好:

void GetSK_list(std::list<Class1>& SK_list) {
    std::ifstream file("file.txt", std::ios::in);
    std::copy(std::istream_iterator<Class1>(file),
              std::istream_iterator<Class1>(),
              std::back_inserter(SK_list));
}

也无需拨打file.close();该文件在 ifstream 析构函数中关闭。

【讨论】:

  • .push_back() 是插入std::list的有效方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多