[英]Copy constructor works faster on copying std::vector<int64_t> than std::copy
[英]int64_t to std::vector<bool> using only `std`
假設x
是一個int64_t
。 我怎樣才能有效地將它轉換為具有 64 個元素的std::vector<bool>
, x
的每一位一個,而不使用std
以外的其他庫?
編輯: std::bitset<64>
對我來說不是一個選項,例如因為我需要在其上調用push_back
和std::find
。
下面的makeVec
function 將允許您將 64 位值轉換為 boolean 向量:
#include <iostream>
#include <vector>
#include <cstdint>
std::vector<bool> makeVec(int64_t x) {
std::vector<bool> retVal;
uint64_t mask = 1ULL << 63;
for (int i = 0; i < 64; ++i) {
retVal.push_back((static_cast<uint64_t>(x) & mask) == 0 ? false : true);
mask >>= 1;
}
return retVal;
}
int main() {
auto vec = makeVec (42);
for (int i = 0; i < 64; ++i) {
std::cout << (vec[i] ? '1' : '0');
}
std::cout << '\n';
}
但是,您可能會發現為此使用位bitset
更容易,因此您的代碼變得更簡單:
#include <iostream>
#include <bitset>
int main() {
auto vec = std::bitset<64>(42);
for (int i = 63; i >= 0; --i) {
std::cout << vec[i];
}
std::cout << '\n';
}
您會注意到的一個區別是位位置的反轉。 對於位集,position 零是最低有效位,因此您必須為此進行調整。
如果您想在矢量解決方案中進行類似的排序(零索引是最低有效位),那只需要更改幾行即可:
std::vector<bool> makeVec(int64_t x) {
std::vector<bool> retVal;
uint64_t mask = 1; // This one ...
for (int i = 0; i < 64; ++i) {
retVal.push_back((static_cast<uint64_t>(x) & mask) == 0 ? false : true);
mask <<= 1; // ... and this one.
}
return retVal;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.