c++struct

Accessing individual elements of C++ structure


Here is the problem I have, please don't beat me up if I don't explain it well or the code is of bad quality - I have only done about 2 weeks of C++ so far.

Explanation: I would like to build a structure (a structure might not be the best decision but I have to start somewhere) that will contain coordinates (x and y only) of a set of points (let's call the set an arc), set id (and possibly other fields). Each set (arc) can contain various numbers of points. I have implemented each point in the set (arc) as the class, then my arc structure contains various instanses of this class in a vector (along with other stuff).

Example of an arc structure:

Struc1:

Id (int) 1

xY (vector) (0;0) (1;1) (2;2)

Struc2:

Id (int) 2

xY (vector) (1;1) (4;4)

Problem: I can't figure out how to access elements within my arc structure: for example if I need to access the coordinates of the second point in the struc with Id 1, I would want Struc1.xY[1], however this doesn't work as my code (below) stands. I have found this post that explains how one could print values inside the struct, but I will need to access these elements to (later on) conditionally edit those coordinates. How can this be impemented?

My attempt: (EDITED)

#include <cmath>
#include <vector>
#include <cstdlib> 
#include <stdio.h>
#include <iostream>

using namespace std;

class Point
  {
  public:
      Point();
      ~Point(){ }

      void setX (int pointX) {x = pointX; }
      void setY (int pointY) {y = pointY; }
      int getX() { return x; }
      int getY() { return y; }

  private:
      int x;
      int y;
  }; 

Point::Point()
    {
        x = 0;
    y = 0;
    }

struct arc {
  int id;
  vector<Point> xY;
};

int main(){

  arc arcStruc;
  vector<Point> pointClassVector;
  int Id;
  int X;
  int Y;
  // other fields go here

  arc *a;

  int m = 2; // Just create two arcs for now
  int k = 3; // each with three points in it
  for (int n=0; n<m; n++){    
    a = new arc;
    Id = n+1;
    arcStruc.id = Id;
    Point pt;
    for (int j=0; j<k; j++){            
      X = n-1;
      Y = n+1;      
      pt.setX(X);
      pt.setY(Y);
      arcStruc.xY.push_back(pt);

    }
  }

for (vector<Point>::iterator it = arcStruc.xY.begin(); it != arcStruc.xY.end(); ++it)
  {
    cout << arcStruc.id.at(it);
    cout << arcStruc.xY.at(it);
  }

  delete a;  
  return 0;
}

Solution

  • A couple of suggestions:

    If you want to iterate through the vector, you should probably use iterators instead of attempting to index into the container. Either way, you can access arcStruc.xY to get its size and then access the elements individually using the [] operator or using iterators, like so:

     for (vector<Point>::iterator it = arcStruc.xY.begin(); it != arcStruc.xY.end(), ++it)
     {
        ... do something with it here, it can be derefernced to get at the Point structure ...
     }