Vector Index Access in Class

How do I access the vector index in the class function 'GetIndex' below?

Please don't get wrapped up around the example I'm using. This is just to illustrate the problem better. I just want to be able to access a vector index from inside the first class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class anObject{
public:
  int GetIndex()
  { /* Return the number 3 that's in the statement "obj.data[3].GetIndex();" */ }
};


class BIGGER_OBJECT{
public:
  std::vector<anObject> obj;
  void Create()
  {
    anObject tmp;
    for (int i=0; i<10; ++i)
      data.push_back(tmp);
  }
};

int main()
{
  BIGGER_OBJECT obj;
  obj.Create();
  int x = obj.data[3].GetIndex(); //should return 3
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class anObject{
   const std::vector<anObject> *container;
   int GetIndex(){
      return container->data() - this;
   }
};

class anObject{
   int index;
   int GetIndex(){
      return index;
   }
};

nolyc wrote:
You're trying to do X, and you thought of solution Y. So you're asking about solution Y, without even mentioning X. The problem is, there might be a better solution, but we can't know that unless you describe what X is.

Ok, here is what I'm trying to do. In order to calculate the Point() of a given cell, I need to be able to access the Cell Index where Index = the vector element position.

See below...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class CELL{
friend class grid;
public:
	int Height();
	int Width();
	rectangle Rectangle();
	point Point();
	point PointCenter();
	point PointBottomRight();	
	int Neighbor(Direction dir);
	int Row();
	int Column();
	int MoveCost;
private:
	int z_cellHeight;
	int z_cellWidth;
	int z_gridRows;
	int z_gridColumns;
};
point CELL::Point()
{
	//int x = Cell->data()-this; doesn't work :(
}


class grid{
friend class CELL;
public:
	std::vector<CELL> *Cell;
	void Create(int Rows, int Columns, int CellHeight, int CellWidth);
private:
	int z_cellHeight;
	int z_cellWidth;
	int z_gridRows;
	int z_gridColumns;
};

int main()
{
	grid g;
	g.Create(5,5,32,32);
	point x = g.Cell[2].Point();
}
Topic archived. No new replies allowed.