简体   繁体   中英

C++ Printing an array containing data structures

I'm currently a beginner with using C++ and I am having some trouble trying to figure out how to print an array of data structures. I have been searching around to try and find a solution for this however, I have been unsuccessful. Below is my code:

#include <iostream>
#include <string>
using namespace std;
int P = 5;
int N = 5;

//Create individual
typedef struct 
{
    int gene[5];    
    int fitness;
} individual;

//Population array contains all individuals
individual population[5];

//Initialize genes and fitness level of each individual in the the 
population
int initializeGenes()
{
    for (int i = 0; i < P; i++) {
        for (int j = 0; j < N; j++) {
            population[i].gene[j] = rand() % 2;
        }
        population[i].fitness = 0;
    }
    return 0;
}

int main()
{
    initializeGenes();

    for (int i = 0; i < P; i++)
    {
        cout << population[i];
    }
    system("pause");
}

What I am wanting to do is print the 'population' array and the error i'm getting says 'no operator "<<" matches these operands, operands types are std::ostream << individual" and I do not understand how to fix this.

Any help or a solution would be very much appreciated, thanks!

The problem is you are trying cout a struct and in C++ this action is only defined for primitive types (int, char, char*, ...), unless you overload the << operator yourself.

What you probably want is to output the primitive data types contained in the struct.

Example

for (int i = 0; i < 5; i++) {
    cout << population[i].gene[i] << endl;
}
cout << population[i].fitness << endl;

You have to overload the operator << and use a ostream alongside a struct individual as parameters so that you can call cout directly. Here's a snippet:

ostream& operator << (ostream& os, const individual& ind)
{
    os << "Gene = ";
    for (int i = 0; i < 5; i++)
    {
        os << ind.gene[i] << " ";
    }
    os << "Fitness = " << ind.fitness <<'\n';
    return os;
}

Here is a C++11 way to achieve your goal. As underline by @seccpur, the best way is to overload the << flux operator. I took some liberties and transform your code a little bit by using a class rather than a struct . It will also show you another use of the << flux operator when playing with classes.

#include <iostream>
#include <string>
#include <vector>
#include <random>

class Individual
{
public:
    Individual() : fitness(0)
    {
        gene.reserve(5);
        std::random_device random_dev;
        std::mt19937  generator(random_dev());
        std::uniform_int_distribution<int> distr(0, 100);
        for (std::size_t i = 0; i < 5; ++i)
            gene.push_back(distr(generator) % 2);
    }

    ~Individual() {};

private:
    std::vector<int> gene;    
    int fitness;

private:
    friend std::ostream& operator<<(std::ostream& stream, const Individual& individual); 
};

std::ostream& operator <<(std::ostream& stream, const Individual& individual)
{
    stream << "Gene = ";
    for (std::size_t i = 0; i < individual.gene.size(); ++i)
        stream << individual.gene[i] << " ";
    stream << "Fitness = " << individual.fitness <<'\n';
    return stream;
}

std::vector<Individual> population(5);

int main()
{
    for (int i = 0; i < population.size(); i++)
        std::cout << population[i];

    return 0;
}

In the above example, you must absolutely declare the following:

friend std::ostream& operator<<(std::ostream& stream, const Individual& individual);

The operator overload is declared friend of the Individual class in order to access its private members.

Also, take care with the rand() function. Use as is, it will always generate the same numbers. You should provide a seed to the number generator. One of its usage can be:

srand(time(NULL)); // Needed one time.
rand() % 2;        // Can be used multiple time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM