C++/C++ 기타

C++ 배열없이 데이터 집약적으로 출석 저장해보기

kimc 2021. 7. 12. 23:10


 

이번 글을 통해 배워갈 내용

  1.  출석을 저장하는 법

 

월단위 출석을 저장하는 경우

 

    int a[30];

배열로 저장을 하면 쉽습니다.

 

int가 16비트니까 총 16 * 30 비트의 데이터를 쓰겠군요

 

 

하지만 용량을 효율적으로 써야되는 경우

 

예를 들어 백만명의 출석을 저장 하는 경우 라면 어떨까요?

 


 

그럴때는 이러한 방법도 있을겁니다.

 

#include <iostream>
#include <math.h> 
#include <bitset>
using namespace std;

int main()
{
    uint schoolAttendance = 0u;
    
    schoolAttendance |= (int)pow(2, 0);
    cout<< (bitset<32>)(schoolAttendance) << endl;
    
    schoolAttendance |= (int)pow(2, 1);
    cout<< (bitset<32>)(schoolAttendance) << endl;
    
    schoolAttendance |= (int)pow(2, 15);
    cout<< (bitset<32>)(schoolAttendance) << endl;
    return 0;
}

 

결과

00000000000000000000000000000001

00000000000000000000000000000011

00000000000000001000000000000011

uint 라는 32비트 양수 정수형 자료형에 

자리수는 0이거나 1입니다.

 

따라서 

 

각 자료에 0 과 1을 넣어줌으로서 32비트 안에 한 사람의 출석을 저장 할 수 있습니다.

 

아까 방법보다 16배 이상 메모리를 집약적으로 쓸 수 있습니다.

 

출석한 날에는 그에 해당하는 이진법 자리수에 0에서 1로 바꿔주고

 

출석을 체크 하는 날에는 해당하는 자리수만 확인해 주면 됩니다.~

 

참쉽죠~

 

 

 

이상입니다.

 

오늘도 즐거운 코딩하시길 바랍니다 ~ :)

 

참조 및 인용

 

https://en.cppreference.com/w/cpp/utility/bitset

 

std::bitset - cppreference.com

The class template bitset represents a fixed-size sequence of N bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers. bitset meets the requirements of CopyConstructible and CopyAssignable. [edit] Templ

en.cppreference.com

 

C++ Primer

 

 


https://codemasterkimc.tistory.com/35

 

C++ 이론을 배울수 있는 곳 정리

개요  C++을 배우는 책, 강의, 블로그, 링크 등을 공유합니다. (링크 및 간략한 설명을 하였으나 만약 원작자가 링크를 거는것을 원치 않을 경우 연락주시기 바랍니다.) 서적 https://www.amazon.com/Prime

codemasterkimc.tistory.com


 

728x90