开发者

Accessing an object's attributes correctly out of a vector and clearing it out

I'm unfamiliar with OO in C++.

I've been pushing instances of the MyPoint class into

vector <MyPoint> trianglePoints;

like this:

trianglePoints.push_back(MyPoint(x,y));

This is my definition of MyPoint:

class MyPoint {

public:
    float x; 
    float y;

    MyPoint(float x, float y) //constructor
    {
        this->x=x;
        this->y=y;

    }开发者_开发问答

}; //end

After pushing three points into the vector I call a function to render the triangle and then do:

trianglePoints.clear();

Questions:

a) How do I get my three x,y coordinates from the vector? I want to store each into its own int xi,yi to render them.

b) Is it okay to call clear() on the vector even though I haven't defined a destructor for the MyPoint class?


a)

trianglePoints[0].x
trianglePoints[0].y
trianglePoints[1].x
trianglePoints[1].y
trianglePoints[2].x
trianglePoints[2].y

b)

Yes, the class uses the default destructor.


(a) You can get elements from the vector using array syntax:

for (int i = 0; i < 3; i++)
{
    do_something(trianglePoints[i]);
}

or iterator syntax:

for (std::vector<MyPoint>::iterator it = trianglePoints.begin();
     it != trianglePoints.end(); ++it)
{
    do_something(*it);
}

or using algorithm syntax:

std::for_each(trianglePoints.begin(), trianglePoints.end(); do_something);

For more details on what you can do with std::vector, see e.g. http://cplusplus.com/reference/stl/vector/.

(b) It's ok to call clear; explicit destructors are only necessary if you have resources to clear up (like memory, file handles, etc.), or if your class is a base class (in which case you may need a virtual destructor).


How do I get my three x,y coordinates from the vector?

vector overloads the subscript operator ([]), so elements can be accessed as if they are in an array. Alternatively (and preferably), you can use iterators.

Is it okay to call clear() on the vector even though I haven't defined a destructor for the MyPoint class?

Yes; the compiler provides a default destructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜