Make Unreal REAL.
article thumbnail

 

숫자를 비트셋으로 표현한 후 벡터로 변환

 

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

using namespace std;

template <typename T>
void print(vector<T> result);

void main()
{
    // 17을 문자 비트 벡터로 변환
    string s = bitset<32>(17).to_string();
    vector<char> v1(s.begin(), s.end());
    
    cout << "v1: ";
    print(v1);
    
    // 문자 비트 벡터를 정수 비트 벡터로 변환
    vector<int> v2(v1.begin(), v1.end());
    
    auto func = [](char c) { return c - '0'; };
    transform(v2.begin(), v2.end(), v2.begin(), func);
    
    cout << "v2: ";
    print(v2);
    
    // 앞의 연속된 0을 trim
    auto MS1 = find(v2.begin(), v2.end(), 1);
    v2.erase(v2.begin(), MS1);
    
    cout << "v2: ";
    print(v2);
}

 

출력

v1: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1
v2: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1
v2: 1 0 0 0 1

 

 

How do I create a bitset from binary string?

I have a binary string in a file that looks like

stackoverflow.com

 

이진 문자열(Binary String)을 통해서도 비트셋을 만들 수 있다.

 

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

using namespace std;

void print(vector<char> result);

void main()
{
    string binary_string = "10101101";
    bitset<32> bset = bitset<32>(binary_string);
    
    string s = bset.to_string();
    vector<char> v(s.begin(), s.end());

    auto MS1 = find(v.begin(), v.end(), '1');
    v.erase(v.begin(), MS1);
    
    cout << bset.to_ullong() << ": ";
    print(v);
}

 

출력

173: 1 0 1 0 1 1 0 1

'자료구조 & 알고리즘 > 기타' 카테고리의 다른 글

vector::resize()  (0) 2023.04.29
unordered_set의 입력 순서 유지  (0) 2023.04.20
unordered_map은 역순회가 불가능하다.  (0) 2023.04.05
내적 계산  (0) 2023.04.02
증가하는 시퀀스로 값 채우기  (0) 2023.03.31
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그