如何限制C++的元素范围STL向量?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种解决方案是创建您自己的数据类型来提供此限制。当我读到你的问题时,我认为这些限制实际上并不属于容器本身,而是属于你想要存储的数据类型。这样的实现的示例(开始)可以如下,可能这样的数据类型已经在现有库中提供。
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.
用另一个类包装它:
Wrap it with another class: