Can someone explain what am I doing wrong?
I get "vector subscript out of range" error.

Here is the sample ...

#include <vector>
using std::vector;

struct CUBE
{
	int number;
	bool changed;
};

int _tmain(int argc, _TCHAR* argv[])
{
	vector<CUBE *> cube;

	for (int i = 0; i < 5; i++)
	{
		cube[i] = new CUBE;
		cube[i]->number = 0;
		cube[i]->changed = false;
	}

	return 0;
}

Recommended Answers

All 5 Replies

Either set the length of the vector before you start, or use push_back() to add each new cube as you go.

>>cube = new CUBE;
You can't use the new operator on a vector. All you have to do is use its push_back() method to add a new item.

CUBE* cb = new CUBE;
cb->number = 0;
cb->changed = false;
cube.push_back(cb);

But you can make your life a little easier by adding a constructure to initialize the structure's variables.

And -- do not make it a vector of CUBE pointers. You could use pointers, but life is a little easier without them, especially since CUBE is such a small structure/class.

struct CUBE
{
    int number;
    bool changed;
    CUBE() { number = 0; changed = false; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<CUBE> cube;
    cube.resize(5);
    return 0;
}

Damn ... I'm ashamed what I was trying to do:$
Tnx for the constructor tip.

Another question ...
If I have a class like this one, I have to manually delete created structs of CUBE right?

class Cube
{

private:
	struct CUBE
	{
		int number;
		bool changed;
		CUBE(): number(0), changed(false);
	};

	CUBE* cube[5];
public:

	Cube()
	{
		for (int i = 0; i < 5; i++)
			cube[i] = new CUBE;
	}
};

Another question ...
If I have a class like this one, I have to manually delete created structs of CUBE right?

Yes, but why bother with those pointers? You should be able to allocate 5 of those tiny structures on the stack with no problem. Using pointers in this situation does nothing more than makes the problem more complex then it needs to be.

I agree. Thanks for help and information :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.