how to cout a vector of structs (that's a class member, using extraction operator)
- by Julz
hi, i'm trying to simply cout the elements of a vector using an overloaded extraction operator. the vector contians Point, which is just a struct containing two doubles.
the vector is a private member of a class called Polygon, so heres my Point.h
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <string>
#include <sstream>
struct Point
{
double x;
double y;
//constructor
Point()
{
x = 0.0;
y = 0.0;
}
friend std::istream& operator >>(std::istream& stream, Point &p)
{
stream >> std::ws;
stream >> p.x;
stream >> p.y;
return stream;
}
friend std::ostream& operator << (std::ostream& stream, Point &p)
{
stream << p.x << p.y;
return stream;
}
};
#endif
my Polygon.h
#ifndef POLYGON_H
#define POLYGON_H
#include "Segment.h"
#include <vector>
class Polygon
{
//insertion operator needs work
friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr);
// extraction operator
friend std::ostream & operator << (std::ostream &outStream, const Polygon &vertStr);
public:
//Constructor
Polygon(const std::vector<Point> &theVerts);
//Default Constructor
Polygon();
//Copy Constructor
Polygon(const Polygon &polyCopy);
//Accessor/Modifier methods
inline std::vector<Point> getVector() const {return vertices;}
//Return number of Vector elements
inline int sizeOfVect() const {return vertices.size();}
//add Point elements to vector
inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);}
private:
std::vector<Point> vertices;
};
and Polygon.cc
using namespace std;
#include "Polygon.h"
// Constructor
Polygon::Polygon(const vector<Point> &theVerts)
{
vertices = theVerts;
}
//Default Constructor
Polygon::Polygon(){}
istream & operator >> (istream &inStream, Polygon::Polygon &vertStr)
{
inStream >> ws;
inStream >> vertStr;
return inStream;
}
// extraction operator
ostream & operator << (ostream &outStream, const Polygon::Polygon &vertStr)
{
outStream << vertStr.vertices << endl;
return outStream;
}
i figure my Point insertion/extraction is right, i can insert and cout using it
and i figure i should be able to just......
cout << myPoly[i] << endl;
in my driver? (in a loop) or even...
cout << myPoly[0] << endl;
without a loop?
i've tried all sorts of
myPoly.at[i];
myPoly.vertices[i];
etc etc
also tried all veriations in my extraction function
outStream << vertStr.vertices[i] << endl;
within loops, etc etc.
when i just create a...
vector<Point> myVect;
in my driver i can just...
cout << myVect.at(i) << endl;
no problems.
tried to find an answer for days, really lost and not through lack of trying!!!
thanks in advance for any help.
please excuse my lack of comments and formatting
also there's bits and pieces missing but i really just need an answer to this problem
thanks again