簡體   English   中英

如何在 C++ 中打印對象向量的內容

[英]How to Print the Contents of a Vector of Objects in C++

請我有一個叫做節點的人的向量。 我從文件中讀取到節點向量。 當我嘗試打印出向量的內容時,我的代碼編譯但不打印任何內容。 下面是我的代碼。 任何幫助將不勝感激。 我還是 C++ 的新手

class person {

public:
    //int person_id;
    string name;
    int age;
    float spread_probability;


    person(){

     }

    person (string pname, int page, double spread){
        //person_id = p_id;
        name = pname;
        age = page;
        spread_probability = spread;
    }
};
vector <string*> edges;
vector <person> nodes;

void insert_node(person& p, string name, int age, float spread_probability) 
{
    p.name = name;
    p.age = age;
    p.spread_probability = spread_probability;
    nodes.push_back(p);
}


void print_node(person& p){
    cout << p.name << " " << p.age << " " << p.spread_probability << endl;

    for(int i=0; i<nodes.size(); i++){
        cout<< nodes[i].name <<":"; 
    }
}

// This is the main function 
int main() {
    ifstream inf("smallpopulation.dat");

    // If we couldn't open the output file stream for reading
    if (!inf) {
        // Print an error and exit
        cerr << "Uh oh, population.dat could not be opened for reading!" << 
        endl;
        return 1;
    }

    // While there's still stuff left to read
    while (inf) {
        string n;
        int a;
        double s;

        inf >> n >> a >> s;
        insert_node(nodes[0], n, a, s);
    }

    print_node(nodes[0]);
}

這個 function:

void print_node(person& p){
for(int i=0; i<nodes.size(); i++){
  cout<< i <<":"; 
}

除了打印i什么都不做,而i只是一個int

在我們可以打印一個person的向量之前,我們必須能夠打印一個person 您尚未向我們展示person的定義,但 class 似乎包含(至少)三個成員變量。 所以我們可以有一個像這樣的 function:

void print_node(person& p){
  cout << p.name << " " << p.age << " " << p.spread_probability << endl;
}

然后打印它們的向量:

for(int i=0; i<nodes.size(); i++){
  print_node(nodes[i]);
}

或者:

for(vector<person>::iterator itr=nodes.begin(); itr!=nodes.end(); ++itr){
  print_node(*itr);
}

一旦你有這么多的工作,許多改進是可能的。

您可以重載 operator<< 如下:

#include <iostream>
#include <cstring>
#include <fstream>
#include <vector>

class Node {
public:
  Node():x(0), s("string"){}
  Node(int _x, std::string _s):x(_x),s(_s){}
  friend std::ostream & operator<<(std::ostream & o, Node n);
private:
  int x;
  std::string s;
};

std::ostream & operator<<(std::ostream & o, Node n)
{
  o<<"("<<n.x<<","<<n.s<<") ";
  return o;
}

int main(int argc, char** argv)
{
  Node n1 = Node();
  Node n2 = Node(12,"apple");
  Node n3 = Node(100, "rat");
  std::cout<<n1<<" "<<n2<<std::endl;
  //this print gives the following output:
  //(0,string)  (12,apple)
  //here the vector of Node objects is created:
  std::vector<Node> vec;
  vec.push_back(n1);
  vec.push_back(n2);
  vec.push_back(n3);
  //size of the vector of Node objects:
  std::cout<<"size="<<vec.size()<<std::endl;
  //here the vector of Node objects is printed:
  for(int i=0; i<vec.size(); ++i) std::cout<<vec.at(i)<<"  ";
  std::cout<<std::endl;   
  return 0;
} 
void print_node(person& p){
for(int i=0; i<nodes.size(); i++){
    cout<< i <<":"; 
}
}

問題就在那里。 你實際上並沒有告訴代碼打印任何東西。 你可以嘗試類似的東西:

cout << i << nodes[i].age;

問題是您沒有從 class person那里打印任何信息。
但是除了打印之外,您的代碼中還有更多問題。 首先,您的insert function 效率低下且難以閱讀。 實際上,在您的情況下,您甚至根本不需要insert function。 您可以使用std::vector::emplace_back() function,例如:

nodes.emplace_back("name", 38, 1.4f);

這將調用person的構造函數並在您的person vector中創建 object。

要打印vector<person> ,您可以制作一個 function ,它將打印一個person object 實例:

void printPerson(const person& p) {
    std::cout << "Name: " << p.name << 
        "\nAge: " << p.age <<
        "\nSpread probability: " << p.spread_probability;
}

這已經被建議並且肯定會起作用,但是有一個更好的選擇,那就是重載std::ostreamoperator<< ,這就是std::cout的派生:

std::ostream& operator<<(std::ostream& out, const person& p)
{
    out << "Name: " << p.name << 
        "\nAge: " << p.age <<
        "\nSpread probability: " << p.spread_probability;
    return out;
}

然后,您只需為要打印的每個 object 調用此 function。


總結一下,這將是整個主要的 function:

 int main() { ifstream inf("smallpopulation.dat"); vector<person> nodes; // If we couldn't open the output file stream for reading if (,inf) { // Print an error and exit cerr << "Uh oh. population;dat could not be opened for reading;" << endl; return 1; } // While there's still stuff left to read while (inf) { string n; int a; double s. inf >> n >> a >> s, nodes,emplace_back(n; a: s); } // Goes through all instances of `nodes` for (const person& p: nodes) { cout << p << '\n': // calls the `std..ostream& operator<<` defined above.;. } return 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM