【问题标题】:Storing values in a container将值存储在容器中
【发布时间】:2025-12-22 14:25:20
【问题描述】:

我正在尝试从一个文件中读取两个值并将它们存储在我的名为God 的类中。 God 有两个数据成员,namemythology。我希望将值存储在list<God>(神及其各自的神话)中,然后将它们打印出来。到目前为止,这是我的代码:

#include <iostream>
#include <fstream>
#include <list>
#include <string>

using namespace std;

class God {
    string name;
    string mythology;
public:
    God(string& a, string& b) {
        name=a;
        mythology =b;
    }
    friend ostream&  operator<<( ostream& os,const God&);
};

void read_gods(list<God>& s) {
    string gname, gmyth;

    //reading values from file
    ifstream inFile;
    inFile.open("gods.txt");

    while(!inFile.eof()) {
        inFile >> gname >> gmyth ;
        s.push_back(God(gname, gmyth));
    }
}

ostream& operator<<( ostream& os,const God& god) {
    return  os << god.name << god.mythology;
}

int main() {
    //container:
    list<God> Godmyth;
    read_gods(Godmyth);

    cout << Godmyth;

    return 0;
}

例如,如果我阅读宙斯,希腊语,那么我将如何访问它们?

我收到的错误是:

错误:cannot bind 'std::ostream {aka std::basic_ostream&lt;char&gt;}' lvalue to 'std::basic_ostream&lt;char&gt;&amp;&amp;'|

【问题讨论】:

  • 您可以创建一个std::map&lt;string, God&gt;,这样您就可以按名称访问对象。
  • 你需要定义获取成员函数来访问你的成员
  • 您遇到了什么问题?您的标题表明您想知道如何在容器中存储值。
  • 与你的问题无关,但你不应该做while (!inFile.eof()),这是因为eofbit标志直到之后你试图阅读超出结尾文件。这会导致循环重复一次到多次。相反,例如while (inFile &gt;&gt; ...).
  • 我知道如何将值存储到像list&lt;double&gt; 这样的容器中,但现在我想知道如何将上帝存储在容器中,然后分别访问名称和神话。感谢@Joachim Pileborg 的提示

标签: c++ list class containers


【解决方案1】:

您应该为类 God 编写 operator &lt;&lt; 或一些成员函数,以输出其数据成员。

例如

class God
{
public:
   std::ostream & out( std::ostream &os ) const
   {
      return os << name << ": " << mythology;
   }

   //...
};

或者

class God
{
public:
   friend std::ostream & operator <<( std::ostream &, const God & ); 

   //...
};


std::ostream & operator <<( std::ostream &os, const God &god )
{
    return os << god.name << ": " << god.mythology;
}     

在这种情况下,而不是无效的声明

cout << Godmyth << endl;

你可以写

for ( const God &god : Godmyth ) std::cout << god << std::endl;

或者,如果您只是想访问数据成员,那么您应该编写 getter。

例如

class God
{
public:
    std::string GetName() const { return name; }
    std::string GetMythology() const { return mythology; }
    //...

【讨论】:

    【解决方案2】:

    没有重载的operator&lt;&lt; 允许使用std::cout 打印std::list 的内容。

    你能做什么?

    1. 正如@Vlad 提到的,你可以写

      for ( const God &god : Godmyth )
          std::cout << god << '\n';
      
    2. 或者,您可以编写自己的operator&lt;&lt;

      template<typename T>
      std::ostream& operator<< (std::ostream &os, const std::list<T> &_list){
          os << "[\n";
          for ( const auto &item : _list )
              os << item << ";\n";
          return os << ']';
      }
      

    【讨论】:

      最近更新 更多