C++ 如何获取类的向量的输入?

C++ 如何获取类的向量的输入?,c++,vector,C++,Vector,我有一个类点,它由x和y坐标组成。我有一个这类的向量。如何从输入中获取坐标?我试过P.x.push_back(x),但显然不起作用。我想知道我怎样才能做到这一点? 我想买点像这样的东西 {1,3},{5,2},{7,2}作为向量 class POINT { public: int x, y; }; int main() { int n; cin >> n; vector<POINT> P(n); int x, y; for

我有一个类
,它由x和y坐标组成。我有一个这类的向量。如何从输入中获取坐标?我试过P.x.push_back(x),但显然不起作用。我想知道我怎样才能做到这一点? 我想买点像这样的东西 {1,3},{5,2},{7,2}作为向量

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;
}
类点{
公众:
int x,y;
};
int main(){
int n;
cin>>n;
向量P(n);
int x,y;
对于(int i=0;i>x>>y;
P.x.推回(x);
P.y.推回(y);
}
返回0;
}

如果您使用的是C++11或更高版本,则可以使用初始值设定项列表

for(int i=0;i>x>>y;
P.推回({x,y});
}
另一种方法是创建一个临时结构并推送(复制)。这种方法在C++03中也可用

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

另一种选择是在
类中重载
操作符>

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;
}
您的输入循环可能如下所示:

POINT p;
std::vector<POINT> coordinates;
while (cin >> p)
{
    coordinates.push_back(p);
}
p点;
向量坐标;
而(cin>>p)
{
坐标。推回(p);
}

点添加
操作符>
也将允许使用
std::istream_迭代器
,因此您可以避免手动循环通过
cin
,例如:
std::copy(std::istream_迭代器(std::cin),std::istream_迭代器(),std::back_插入器(坐标))
POINT p;
std::vector<POINT> coordinates;
while (cin >> p)
{
    coordinates.push_back(p);
}