将vector <bool>转换为int

mag*_*gu_ 3 c++ memcpy

我有一个vectorbool,我想在复制int较大尺寸的容器.有没有快速的方法来做到这一点?

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找像memcpy我可以在subbyte级别上使用的东西.

toh*_*ava 9

这是使用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;
}
Run Code Online (Sandbox Code Playgroud)

使用gcc内部的另一种解决方案vector<bool>更有效:

#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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,不建议使用vector<bool>它,因为它是一个有问题的专业化,vector<T>并且具有稍微不同的API.我建议使用vector<char>,或者Bool使用隐式强制转换来创建自己的包装类bool.

  • 请注意,该解决方案是特定于实现的,并且可能无法跨编译器移植.例如,`clang`将*不*编译该代码 (2认同)