通过查找位返回一个数组?
我有以下用例, 整数数组
vector<int> containing elements 123 345 678 890 555 ...
pos 0 1 2 3 4
基于我收到的位表示,例如,
101 then return 123 678 (Elements of the array with its position bits set)
0011 then return 678 890
00001 then return 555
您能推荐我可以用来解决这个问题的任何库吗?
编辑:向量本身是动态的,位大小可以根据想要返回相应数组元素的 1 位而变化。
I have the following use case ,
array of integers
vector<int> containing elements 123 345 678 890 555 ...
pos 0 1 2 3 4
Based on the bits representation I receive for e.g
101 then return 123 678 (Elements of the array with its position bits set)
0011 then return 678 890
00001 then return 555
Can you recommend any libraries which I can use to solve this problem.
EDIT: The vector itself is dynamic and the bit size can vary, based on the 1 bits want to return corresponding array elements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您最终希望将位集映射到其位索引。 使用众所周知的位旋转技巧这非常容易:
其中
count_bits_set
可以使用编译器内在函数或手动实现(请参阅http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel)。 如果您愿意,您还可以查找single_bit_set
的 log2。You ultimately want to map bits set to their bit index. That's pretty easy using well-known bit twiddling hacks:
Where
count_bits_set
can be implemented with a compiler intrinsic or manually (see http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel). You could also use finding the log2 ofsingle_bit_set
if you wanted to.我假设位掩码存储在容器中(以支持系统上具有超过
sizeof(uintmax_t)
位的位掩码)。 在这种情况下,解决方案的本质是:其中
v
- 输入向量;out
- 存储结果的向量;pred
- 位掩码上的迭代器。如果您想避免
boost::lambda
那么它很容易模拟:它可以按如下方式使用(使用与上面示例中相同的符号):
或者使用谓词相同
:可以如下使用:
示例(使用
boost::lambda
,但很容易用上述两个其他选项替换它):输出:
I assume that a bit mask is stored in a container (to support bit masks with more than
sizeof(uintmax_t)
bits on your system). In this case the essence of solution is:Where
v
- an input vector;out
- a vector to store results;pred
- an iterator over a bit mask.If you'd like to avoid
boost::lambda
then it is easily simulated:It can be used as follows (using the same notation as in the above example):
Or the same using a predicate:
That can be used as follows:
Example (using
boost::lambda
, but it is easy to replace it by the above two other options):Output:
这是一个快速但肮脏的解决方案
This is a quick and dirty solution
好的,您可以使用过滤迭代器来稍微优雅地完成此操作。 正如我在你的问题中看到的,数组上的索引以与数字相反的顺序开始(数字位置“0”的索引对应于数组中的位置“3”)。 因此,您必须反向查看数组才能选择正确的元素。 另外,由于返回值可能包含 0、1、2、3 或 4 个元素,因此我建议您返回一个列表。 这是一个提示:
希望这有帮助,
OK, You can do this one slightly more elegant using filtering iterators. As I see on your question, the indices on the array start in reverse order than that of the number (index of position "0" of the number corresponds to position "3" in the array). So you have to go in reverse looking at the array to select the correct elements. Also, as the return value may contain 0, 1, 2, 3, or 4 elements, I suggest you to return a list. Here is a hint:
Hope this helps,