我需要将obejcts添加到列表中(现在它们只是main中的硬编码对象)
int main ()
{
// create objects of type Point, passing different x and y values to the contructor
Point point1 (7,5); // new point object point1 with value x=2.5, y=5.3
Point point2 (4,8); // second point obejct
Point point3 (8,9); // third point object
Point point4 (10,5);//fourth point object
Point point5 (6,8);//fifth point
Point point6 (4,7);//sixth point
}
使用push_back
逐个将它们添加到列表中list<Point>pointList ; // stl list that will contain my objects.
pointList.push_back(point1);//adds the obejcts to the list from the back each time {point1}
pointList.push_back(point2);//{point1, point2} < point2 pushed_back
pointList.push_back(point3);//{point, point}
pointList.push_back(point4);
pointList.push_back(point5);
pointList.push_back(point6);
现在我需要做的是一次将对象3传递给此方法&gt;
static void calculateF (Point p1, Point& p2, Point p3)// point2 needs to be a reference otherwise f is just changed locally.
double F ; //
double xPoint1 = p1.getX(); // x value of object p1
double yPoint1 = p1.getY(); // y value of object p1
double xPoint2 = p2.getX(); // x value of object p2
double yPoint2 = p2.getY(); // y coordinates of object p2
double xPoint3 = p3.getX(); // x coordinates of obejct p3
double yPoint3 = p3.getY(); // y coorinates of obejct p3
//equation for working out f from these six values
//temp variables to store the length of the triangles sides.
double p2p3 = sqrt (((xPoint2 - xPoint3)*(xPoint2 - xPoint3)) + ((yPoint2 - yPoint3)*(yPoint2 - yPoint3))); //length point2 to point1 (PR in assingment notes)
cout << "p1p2 is = " << p2p3 << endl; // print the value of p2p3 (PR)
double p1p2 = sqrt (((xPoint1 - xPoint2)*(xPoint1 - xPoint2)) + ((yPoint1 - yPoint2)*(yPoint1 - yPoint2))); //length point1 to point 2 (LP in assingment notes)
cout << "p1p2 is = " << p1p2 << endl;
double p1p3 = sqrt (((xPoint1 - xPoint3)*(xPoint1 - xPoint3)) + ((yPoint1 - yPoint3)*(yPoint1 - yPoint3)));//length of point1 to point 3 (LR in assigment notes)
cout << "hypotenuse p1p3 is = " << p1p3 << endl;
F = p1p2 + p2p3 - p1p3 ; //equation for f
//cout << "importance factor is " << F << endl ;
p2.setF(F); // setting F to f in class
}
现在我知道我可以一次传递一个像 calculatef(点1,点2,POINT3); calculatef(point2.point3,point4); 等..............
它根本没有使用列表来传递它们,这是我需要做的。在列表中添加点并使用列表将每个点传递给calculateF方法。
如果那是一个真正的问题,那就是问我的问题。我只是包含了所有内容,因此可以将其放入上下文中。
先谢谢有能力的程序员
答案 0 :(得分:0)
由于列表是作为双向链表实现的,因此您可能更适合使用向量(因为您可以使用向量非常轻松有效地访问单个元素...)。
您可以使用以下代码示例来执行您希望的内容
std::vector<Point> vec;
vec.push_back( Point(0,0));
// Push back all other points...
for( int i = 0; i < ( vec.size() - 2 ); i++ )
{
calculateF( vec[i], vec[i+1], vec[i+2] );
}
我希望这会有所帮助......
答案 1 :(得分:0)
您还可以使用矢量迭代器执行更通用的操作,例如;
void calculateF (std::vector<Point>::iterator from_a,
std::vector<Point>::iterator to_b )
{
for (std::vector<Point>::iterator i=from_a; i != to_b; ++i) {
// ... do something with i->x and i->y
}
}
main()
{
...
calculateF(vec.begin()+0, vec.begin()+3);
calculateF(vec.begin()+3, vec.begin()+6);
...
}