Reputation: 10861
vector<int> l;
for(int i=0;i<10;i++){
l.push_back(i);
}
I want the vector to only be able to store numbers from a specified range (or set). How can that be done, in general?
In particular, I want to restrict the vector to beonly be able to store single digits.
So, if I do a l[9]++
(in this case l[9]
is 9
), it should give me an error or warn me. (because 10
is not a single digit number). Similarly, l[0]--
should warn me.
Is there a way to do this using C++ STL vector
?
Upvotes: 2
Views: 674
Reputation: 54232
Wrap it with another class:
class RestrictedVector{
private:
std::vector<int> things;
public:
// Other things
bool push_back(int data){
if(data >= 0 && data < 10){
things.push_back(data);
return true;
}
return false
}
}
Upvotes: 2
Reputation: 17176
An alternative solution would be to create your own datatype that provides this restrictions. As i read your question I think the restrictions do not really belong to the container itself but to the datatype you want to store. An example (start of) such an implementation can be as follows, possibly such a datatype is already provided in an existing library.
class Digit
{
private:
unsigned int d;
public:
Digit() : d(0) {}
Digit(unsigned int d)
{
if(d > 10) throw std::overflow_error();
else this->d=d;
}
Digit& operator++() { if(d<9) d++; return *this; }
...
};
Upvotes: 10