简体   繁体   中英

How to restrict the range of elements of C++ STL vector?

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 ?

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; }
    ...
};

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 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM