gpt4 book ai didi

C++ 无法填充数据

转载 作者:行者123 更新时间:2023-11-28 07:21:55 27 4
gpt4 key购买 nike

我正在尝试用 x 和 y 值填充我的 vector 。但它似乎没有添加,只是覆盖了第一的。

主要.cpp

#include <iostream> 
#include "Point.h"

using namespace std;
int x,y;
Point point;
string options;
void someMethods();
int main()
{
cout << "Please Enter x-Cordinate"<< endl;
cin >> x;
cout << "Please Enter y-Cordinate" << endl;
cin >> y;
cout << "Enter cords again? yes/no"<< endl;
cin >> options;
while (options == "yes") {

cout << "Please Enter x-Cordinate"<< endl;
cin >> x;
cout << "Please Enter y-Cordinate" << endl;
cin >> y;
cout << "Enter cords again? yes/no"<< endl;
cin >> options;
}


if(options == "no") {
Point Point(x,y);
Point.someMethods();
// break;
}
}

点.h

#ifndef Point_Point_h
#define Point_Point_h
#include <vector>

class Point {
private:
int x,y;

public :

Point() {
x = 0;
y = 0;
} //default consrructor


Point(int x,int y);
int getX();
int getY();
void setX(int x);
void setY(int y);
std::vector<Point> storeData;
void someMethods();

};

#endif

点.cpp

#include <iostream>
#include "Point.h"
using namespace std;


Point::Point(int x,int y) {
setX(x);
setY(y);

}

int Point::getX() {
return x;
}
int Point::getY() {
return y;
}

void Point::setX(int x) {
this->x = x;
}

void Point::setY(int y) {
this->y = y;
}


void Point::someMethods() {
x = getX();
y = getY();

Point Point(x,y);
storeData.push_back(Point);

for (int i=0; i<storeData.size(); i++) {
cout << "X "<< storeData[i].getX() <<"Y " << storeData[i].getY() << endl;
}
// do some methods here after getting the x and y cords;
}

我怎样才能做到这一点,例如(我输入 x 和 y 3 次,比方说 1,1 2,2 3,3 )

然后会输出

X: 1,Y: 1
X: 2,Y: 2
X: 3,Y: 3

最佳答案

int main()
{
// don't need global variables, just define local ones here
int x,y;
Point point;
string options;

// You shouldn't store the vector of Points in the Point class itself.
// It doesn't have anything to do with a Point. classes should generally
// only contain relevant information (ex. Point contains only x and y coords).
vector<Point> pointsVector;

// do-while will do the contents of the loop at least once
// it will stop when the while condition is no longer met
do
{
cout << "Please Enter x-Cordinate"<< endl;
cin >> x;
cout << "Please Enter y-Cordinate" << endl;
cin >> y;

pointsVector.push_back(Point(x, y));

cout << "Enter cords again? yes/no"<< endl;
cin >> options;
} while (options == "yes")

// don't really need to check if options is "no"
// if you have exited the do/while loop above, the assumption is that you don't
// want to enter more coordinates.
doSomethingWithTheVectorOfPoints(pointsVector);

return 0;
}

在函数doSomethingWithTheVectorOfPoints 中,您可以放置​​用于输出X 和Y 坐标的代码。 (您也可以直接在主函数中循环遍历 vector 。)

此外,您可以向 Point 类添加一个名为 ToString 或 Print 的成员函数来为您完成这项工作。

编辑:我实际上并没有编译它,它只是让您了解如何重写代码。

关于C++ 无法填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19323641/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com