简体   繁体   English

如何在 C++ 中打印对象向量的内容

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

Please I have a vector of a person called nodes.请我有一个叫做节点的人的向量。 I read from a file into the nodes vector.我从文件中读取到节点向量。 When I try printing out the contents of the vector, my code compiles but does not print anything.当我尝试打印出向量的内容时,我的代码编译但不打印任何内容。 Below is my code.下面是我的代码。 Any help will be greatly appreciated.任何帮助将不胜感激。 I am still new to 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]);
}

This function:这个 function:

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

does nothing but print i , and i is just an int .除了打印i什么都不做,而i只是一个int

Before we can print a vector of person , we must be able to print one person .在我们可以打印一个person的向量之前,我们必须能够打印一个person You haven't shown us the definition of person , but the class seems to contain (at least) three member variables.您尚未向我们展示person的定义,但 class 似乎包含(至少)三个成员变量。 So we could have a function like this:所以我们可以有一个像这样的 function:

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

Then to print a vector of them:然后打印它们的向量:

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

or:或者:

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

Once you have that much working, many refinements are possible.一旦你有这么多的工作,许多改进是可能的。

You may overload operator<< as follows:您可以重载 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 <<":"; 
}
}

The problem is there.问题就在那里。 U're actually don't tell code to print anything.你实际上并没有告诉代码打印任何东西。 U could try something like:你可以尝试类似的东西:

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

The problem is you're not printing any information from the person class.问题是您没有从 class person那里打印任何信息。
But you have more problems in your code apart from printing.但是除了打印之外,您的代码中还有更多问题。 First of all, your insert function is inefficient and hard to read.首先,您的insert function 效率低下且难以阅读。 Actually, you don't even need an insert function at all in your case.实际上,在您的情况下,您甚至根本不需要insert function。 You can use the std::vector::emplace_back() function, for example:您可以使用std::vector::emplace_back() function,例如:

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

This will call the constructor for person and create the object in your vector of person s.这将调用person的构造函数并在您的person vector中创建 object。

To print the vector<person> , you can make a function which will print one person object instance:要打印vector<person> ,您可以制作一个 function ,它将打印一个person object 实例:

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

Which was already suggested and would definitely work, but there is a better option and that is to overload the operator<< for std::ostream , which is what std::cout derives from:这已经被建议并且肯定会起作用,但是有一个更好的选择,那就是重载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;
}

Then you just need to call this function for every object you want to print.然后,您只需为要打印的每个 object 调用此 function。


To wrap it up, this would be the whole main 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