NewUser
NewUser

Reputation: 29

How to get input to vector of class?

I have a class POINT which consists of x and y coordinates. And I have a vector of this class. How can I get the coordinates from input? I tried P.x.push_back(x) but obviously it doesn't work. I am wondering how I can achieve this? I want to get something like {{1, 3}, {5, 2}, {7, 2}} as a vector.

class POINT {
public:
    int x, y;
};

int main() {
    int n;
    cin >> n;
    vector<POINT> P(n);
    int x, y;
    for(int i = 0; i < n; i++) {
        cin >> x >> y;
        P.x.push_back(x);
        P.y.push_back(y);
    }
    return 0;
}

Upvotes: 0

Views: 100

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57698

Another alternative is to overload operator>> in your POINT class:

class POINT
{
  public:
    int x, y;
  friend std::istream& operator>>(std::istream& input, POINT& p);
};

std::istream& operator>>(std::istream& input, POINT& p)
{
  input >> p.x >> p.y;
  return input;
}

Your input loop could look like this:

POINT p;
std::vector<POINT> coordinates;
while (cin >> p)
{
    coordinates.push_back(p);
}

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

If you are using C++11 or later, you can use initializer list.

    for(int i = 0; i < n; i++) {
        cin >> x >> y;
        P.push_back({x, y});
    }

Alternative way is to create a temporary structure and push (copy of) that. This way is available also in C++03.

    for(int i = 0; i < n; i++) {
        cin >> x >> y;
        POINT point = {x, y};
        P.push_back(point);
    }

Upvotes: 5

Related Questions