For my constructor, I input a integer vector, and within the constructor, I set another vector of type bool called theSet. From the input vector, I check every element to see if its between 0 and 20, if true then element of theSet is true.
However I'm having problems with my implementation of dereferencing theSet vector.
class Set
{
public:
Set(vector<int> &);
bool IsMember(int);
private:
vector<bool> theSet;
}
bool Set::IsMember(int x)
{
if ((x >= 0) && (x <= 20))
return true;
else
return false;
}
Set::Set(vector<int> &v)
{
int length = v.size();
theSet.reserve(length);
bool check;
int p = 0;
for (int i = 0; i < length; i++)
{
theSet[i] = IsMember(v[i]);
}
}
Use theSet.resize()
instead of theSet.reserve()
and it'll probably work. Please try. With reserve()
you are just pre-allocating memory for inserts, but the memory itself is unitialized, resp. there are no real elements yet. When you try to modify the values within your loop you'll request a reference to the value at position i
, but there's no element that could be modified, hence the error.