转换vector< bool>诠释 [英] convert vector<bool> to int

查看:79
本文介绍了转换vector< bool>诠释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个boolvector,要复制到更大尺寸的int容器中.有没有一种快速的方法可以做到这一点?

I have a vector of bool which I want to copy in a int container of bigger size. Is there a fast way to do this?

需要澄清的是,有没有更聪明的方法来实现这一目标?

To clarify, is there a smarter way to achieve this?

#include <vector>
#include <cstdint>
#include <iostream>
#include <climits>
#include <cassert>


inline size_t bool2size_t(std::vector<bool> in) {
    assert(sizeof(size_t)*CHAR_BIT >= in.size());
    size_t out(0);

    for (size_t vecPos = 0; vecPos < in.size(); vecPos++) {
        if (in[vecPos]) {
            out += 1 << vecPos;
        }
    }

    return out;
} 

int main () {
    std::vector<bool> A(10,0);
    A[2] = A[4] = 1;

    size_t B = bool2size_t(A);

    std::cout << (1 << 2) + (1 << 4) << std::endl;
    std::cout << B << std::endl;
}

我正在寻找像memcpy这样的东西,可以在子字节级别使用.

I'm looking for something like a memcpy which I can use on a subbyte level.

推荐答案

以下是使用C ++ 11的示例

Here is an example using C++11

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    vector<bool> b(10,0);
    b[2] = b[4] = 1;
    int i;
    i = accumulate(b.rbegin(), b.rend(), 0, [](int x, int y) { return (x << 1) + y; });
    cout << i << endl;
}

将gcc内部结构用于vector<bool>且效率更高的另一种解决方案:

Another solution that uses gcc internals for vector<bool> and is more efficient:

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    vector<bool> b(10,0);
    b[2] = 1;
    b[4] = 1;
    auto p = b.begin()._M_p;
    cout << *p << endl;
}

请注意,尽管不建议使用vector<bool>,因为这是vector<T>的问题,并且API略有不同.我建议改用vector<char>,或者使用与bool之间的隐式转换来创建自己的Bool包装器类.

Note though that it is not recommended to use vector<bool> since it is a problematic specialization of vector<T> and has a slightly different API. I recommend using vector<char> instead, or creating your own Bool wrapper class with implicit cast to and from bool.

这篇关于转换vector&lt; bool&gt;诠释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆