Vectors, Classes and functions

I have 2 questions

1. how do i access a class's function if said class is part of an std::vector.

example:
1
2
3
4
5
6
class Obstacle
{
  void function();
};

std::vector<Obstacle> m_obstacles[2];


how would i call the function of the 2 obstacle classes.


2. I am trying to find the size of a vector, i have used the vector.size() function but i get the following error:
error: request for member 'size' in '((Map*)this)->Map::m_obstacles', which is of non-class type 
'std::vector<Obstacle> [200]'|


code for review:
for (int i = 0; i < m_obstacles.size(); i++)
Last edited on
1. how do i access a class's function if said class is part of an std::vector.
1
2
std::vector<Obstacle> m_obstacles(2); // using [2] would create an array of vectors. it doesnt look like you want this.
m_obstacles[0].function(); // etc 


2. I am trying to find the size of a vector, i have used the vector.size() function but i get the following error:

fix #1 and #2 should be fixed
tried changing it from [2] to (2) and i got the following errors

error: expected identifier before numeric constant
error: expected ',' or '...' before numeric constant


full code for review:

1
2
3
4
5
6
7
8
9
10
11
class Map
{
public:
    Map();
    void handleInput(sf::RenderWindow& window);
	void update(float delta, sf::RenderWindow& window);
	void render(sf::RenderWindow& window);

private:
	std::vector<Obstacle> m_obstacles(200);
};
Last edited on
Use uniform or copy initialization to give default values to class members or initialize them in constructor:
1
2
3
private:
    //One parameter constructor is explicit so we need to instantiate a temporary directly
    std::vector<Obstacle> m_obstacles = std::vector<Obstacle>(200); //Copy initialization 
1
2
private:
    std::vector<Obstacle> m_obstacles {200}; //Uniform initialization 
1
2
3
4
5
public:
    Map(): m_obstacles(200) {} //initialization in constructor
   //...
private:
    std::vector<Obstacle> m_obstacles;
Last edited on
Topic archived. No new replies allowed.