如何限制C++的元素范围STL向量?

发布于 2024-08-28 21:29:03 字数 390 浏览 1 评论 0原文

vector<int> l; 
for(int i=0;i<10;i++){ 
   l.push_back(i); 
} 

我希望向量只能存储指定范围(或集合)中的数字。 一般来说,这是如何做到的?

特别是,我想限制向量只能存储个位数。

因此,如果我执行 l[9]++ (在本例中 l[9]9),它应该给我一个错误或警告我。 (因为 10 不是一位数字)。同样,l[0]-- 应该警告我。

有没有办法使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

会发光的星星闪亮亮i 2024-09-04 21:29:03

另一种解决方案是创建您自己的数据类型来提供此限制。当我读到你的问题时,我认为这些限制实际上并不属于容器本身,而是属于你想要存储的数据类型。这样的实现的示例(开始)可以如下,可能这样的数据类型已经在现有库中提供。

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

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; }
    ...
};
一片旧的回忆 2024-09-04 21:29:03

用另一个类包装它:

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

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 
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文