Wednesday, November 19, 2008

Using Vector template


#if defined(__cplusplus)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#else
error "must be CPP-enabled compiler to compile this program"
#endif

using namespace std;


class CPoint {
public:
CPoint(double a, double b) { x = a; y = b; };
friend std::ostream& operator<< (std::ostream& os, const CPoint& val);
double getX() { return x; };
double getY() { return y; };
private:
double x;
double y;
};


std::ostream& operator<< (ostream& os, const CPoint& pt)
{
return os << "(" << pt.x << ", " << pt.y << ")" ;
}


int main()
{
vector<CPoint> points;
vector<CPoint>::iterator it;
int i;

it = points.begin();

for (i=0; i<10; i++) {
it = points.insert( it, CPoint(10.5+double(i)/11, 22.7 - double(i)/13) );
}


cout << "Vector Demo" << endl << "-------------" << endl;
cout << "Vector size = " << points.size() << endl;

for (it = points.begin(), i=0; it < points.end(); it++,i++)
{
// cout << "points[" <<>x;
cout << " " << *it;
cout << endl;
}

for (i=0; i< points.size(); i++)
{
cout << "points[" << i << "] = " << points[i] << endl;
}

return 0;
}

No comments:

Post a Comment