How to limit the range of elements of an STL C ++ vector?
vector<int> l;
for(int i=0;i<10;i++){
l.push_back(i);
}
I want the vector to be able to store only numbers from a specified range (or set). How can this be done in general?
Specifically, I want to constrain the vector so that it can only store single digit numbers.
So, if I do a l[9]++
(in this case, l[9]
there is 9
) it should give me an error or warn me. (because it 10
is not a single digit number). Likewise, l[0]--
must warn me.
Is there a way to do this using the C ++ STL vector
?
a source to share
An alternative solution would be to create your own data type that provides these constraints. When I read your question, I think the constraints really do not belong to the container itself, but to the data type you want to store. An example (beginning) of such an implementation might be as follows: perhaps this data type 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; }
...
};
a source to share