C++ 中有标准的循环整数类吗?
我有一个在我目前编写的代码中很常见的问题,即我想要一个只能存在于范围为 [start, end) 的特定范围内的整数。基本上我希望能够执行如下操作:
cyclic_int ci(4, 8);
ci = 4;
assert(ci == 4);
ci += 3;
assert(ci == 7);
ci += 2;
assert(ci == 5);
assert(ci == 13);
并且这一切都应该返回 true。基本上,该类自动为我应用模数 (%),并且该整数充当我初始化它的范围内的循环整数。我可以自己实现这个类并重载所有常见的运算符,使其能够与普通整数很好地配合,但它似乎是一个有用的类,可能有人以前做过。
所以我的问题是,是否有一个每个人都使用的公共类,或者我是否正在考虑以错误的方式进行操作,是否有更好的更简单的方法。 (我的目标是不必不断考虑应用 % 运算符或任何类似的函数)谢谢。
编辑:我决定也写自己的一个只是为了好玩: http://github.com/robertmassaioli/wrapping_number< /a>
I have a problem that is quite common in the code that I am writing at the moment whereby I want to have an integer that can only exist inside a certain range where the range is [start, end). Basically I want to be able to do something like the following:
cyclic_int ci(4, 8);
ci = 4;
assert(ci == 4);
ci += 3;
assert(ci == 7);
ci += 2;
assert(ci == 5);
assert(ci == 13);
And that should all return true. Basically the class automatically applies modulus (%) for me and the integer acts as a cyclic integer in the range that I init it with. I could implement this class myself and overload all of the common operators to make it work nicely with normal integers but it seems like a useful class that somebody may have made before.
So my question is this, is there a common class like this out there somewhere that everyone uses or am I thinking of doing it the wrong way and is there a better simpler way. (My aim is to not have to constantly think about applying the % operator or any similar function over it) Thanks.
Edit: I decided to write my own one as well just for fun: http://github.com/robertmassaioli/wrapping_number
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
normalize
函数不是更简单吗?Is not it easier to use the function
normalize
?我从未使用过它,而且它还不是官方的 Boost 库,但 Boost.ConstrainedValue 有一个
wrapping_int
看起来与您要查找的内容非常相似。虽然它还不是 Boost 的一部分,但最近经过了审查,并且 IIUC 有条件接受: http://lists.boost.org/boost-announce/2010/09/0265.php
该库位于 http://rk.dl.pl/f/constrained_value.zip
文档位于 http://rk.dl.pl/r/constrained_value
I never used it and it is not yet an official Boost library, but Boost.ConstrainedValue has a
wrapping_int
that looks very similar to what you're looking for.Although it is not yet a part of Boost, it was reviewed and, IIUC, conditionally accepted recently: http://lists.boost.org/boost-announce/2010/09/0265.php
The library is available at http://rk.dl.pl/f/constrained_value.zip
The documentation is at http://rk.dl.pl/r/constrained_value
这些可能并不完全是您想要的,但您可能对众多伽罗瓦域库之一感兴趣(http://www.google.co.uk/search?q=galois+field+c%2B%2B+library)。我从未使用过其中任何一个,所以我无法给出具体的推荐。
These may not be exactly what you want, but you may be interested in one of the many Galois-field libraries out there (http://www.google.co.uk/search?q=galois+field+c%2B%2B+library). I've never used any of them, so I can't give a specific recommendation.