Rusydi Rusydii
Rusydi Rusydii

Reputation: 137

STL Vectors array

For example i have a class name Point.

class Point{
protected: 
int x, y;
public:
void setX(int);
void setY(int)
int getX();
int getY();
}

void Point::setX(int newX)
{
x = newX;
}

There is setX, getX, setY, getY inside.

How do I start a vector array with this? so that I can use setX, getX and all?

Upvotes: 1

Views: 261

Answers (2)

Zeta
Zeta

Reputation: 105965

Simply include vector and use the vector functions.

#include <iostream>
#include <vector>

/* .... */
size_t number_of_elements = 100;
std::vector<Point> myPointVector(number_of_elements);

for(unsigned i = 0; i < myPointVector.size(); ++i){
    myPointVector[i].setX(i);
    myPointVector[i].setY(number_of_elements - i);
}

for(unsigned i = 0; i < myPointVector.size(); ++i){
    std::cout << "Vector " << i << ": ";
    std::cout << myPointVector[i].getX() << ", ";
    std::cout << myPointVector[i].getY() << std::endl;
}

If the code above baffles you I recommend you to read a good introduction to C++ container/iterators/algorithms (or a good C++ book in general).

Upvotes: 1

alestanis
alestanis

Reputation: 21863

You just have to declare a

vector<Point> myPoints;

I recommend you add a constructor to your class that takes as an argument the point's coordinates:

class Point {
  public:
    Point(int xx, int yy) : x(xx), y(yy) {}
  // Other things
}

Then you can just add points to your vector using

myPoints.push_back(Point(10, 42));

and once your vector is filled, you can get the coordinates of the points inside using your functions. For example:

for (int i = 0; i < myPoints.size(); ++i) {
  cout << myPoints[i].getX() << ", " << myPoints[i].getY() << endl;
}

Upvotes: 3

Related Questions