Home > OS >  How can I create a vector from struct in main?
How can I create a vector from struct in main?

Time:05-26

What am I doing wrong here? I'm trying to make a vector from struct in main but it keep showing error.

#include <iostream>
#include <vector>

using namespace std;

struct A{
    int y;
};

int main()
{
    int x;
    cin >> x;
    vector<A> vertex;
    for(int i = 0; i < x; i  ){
        vertex.push_back(x)
        cout << vertex[i]<<endl;
    }

    return 0;
}

CodePudding user response:

x is an int not an A

you need

int main()
{
    int x;
    cin >> x;
    vector<A> vertex;
    for (int i = 0; i < x; i  ) {
        A a;
        a.y = x;
        vertex.push_back(a);
        cout << vertex[i].y << endl;
    }

}

you can make your original code work by providing an implicit conversion from int to A

also you would need to provide a << operator for A

CodePudding user response:

You are trying to push_back() an int into a vector that holds A objects. You have not defined any conversion from int to A, hence the error.

You can add a constructor to A that takes in an int and assigns it to y:

struct A{
    int y;
    A(int value) : y(value) {}
};

Or, you can omit the constructor and instead create an A object and pass it to push_back():

A a;
a.y = x;
vertex.push_back(a);

Or, using Aggregate Initialization:

vertex.push_back(A{x});

Or, you can alternatively use emplace_back() instead, which will construct the A object inside the vector for you, using the specified parameter(s) for the construction:

vertex.emplace_back(x);

Either way, that will fix the error you are seeing.

Then, you will run into a new error, because you have not defined an operator<< for printing A objects, so you will have to add that, too:

struct A{
    int y;
    ...
};

std::ostream& operator<<(std::ostream &os, const A &a) {
    return os << a.y;
}

Now, your code will run.

  •  Tags:  
  • c
  • Related