using vectors with constructors and functions

I've declared a vector of Lists as a private field in my header file. I create the vector in my constructor and make it size 10.

I want to call upon the vector created in the constructor in a different function in the same file. When I do so I get a segfault. When I check the size of the vector (which I want to be the same one I created in the constructor) that i'm calling in the function I get size 0, which tells me they're not the same vector. How do I access the vector I created in my constructor?
Last edited on
Please, show your code.
What you trying to do is not trivial so I would take care in designing you class unless you just want to put it all in a struct and make everything public. I am a firm believer in locking down data so this is how I would start to implement my class. I would then add public methods to add and remove from the vectors under certain conditions to avoid any run-time errors that can occur from trying to access or delete components that do not exist.

Good luck.

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
class Foo
{
public:
	Foo() { listOfLists.resize(10); }

	list<string>& operator [] (int i)
	{
		if (i < 0 || i > listOfLists.size() || i > listOfLists[i].size())
			cerr << "Index out of bounds!\n";
		else 
	 		return listOfLists[i]; 
	}
		
	list<string> operator [] (int i) const
	{
		if (i < 0 || i > listOfLists.size() || i > listOfLists[i].size())
			cerr << "Index out of bounds!\n";
		else 
	 		return listOfLists[i]; 
	}

	int OuterSize() { return listOfLists.size(); }

	int InnerSize (int i) 
	{ 
		if (i < 0 || i > listOfLists.size())
			cerr << "Index out of bounds!\n";
		else 
	 		return listOfLists[i].size(); 
	}

private:
	vector<list<string> > listOfLists;
};



This is really messy though. And I haven't tried using it but you should definitely try to control the out of bounds stuff inside your class to make things easier when you start to use them.

I would opt for a list of lists or a vector of vectors just to keep things consistent as well.
Last edited on
Topic archived. No new replies allowed.