포스트

[C++] 이런저런 표준 라이브러리 함수

[C++] 이런저런 표준 라이브러리 함수

C++ 표준 라이브러리 유틸리티 함수 정리

따로 분류하기 애매하지만 유용한 함수들을 정리한 문서.


std::count

  • 헤더: <algorithm>
  • 특정 값이 컨테이너에 몇 번 등장하는지 세는 함수
1
2
std::vector<int> v = {1, 2, 2, 3, 4, 2};
int count2 = std::count(v.begin(), v.end(), 2); // 결과: 3

std::count_if

  • 헤더: <algorithm>
  • 주어진 조건(predicate)을 만족하는 요소 개수 세기
1
2
3
int evenCount = std::count_if(v.begin(), v.end(), [](int x) {
    return x % 2 == 0;
});

std::begin / std::end

  • 헤더: <iterator>
  • STL 컨테이너나 C 배열의 시작/끝 반복자를 얻을 수 있음
  • C++11부터 도입
1
2
3
int arr[] = {1, 2, 3};
auto it1 = std::begin(arr); // arr + 0
auto it2 = std::end(arr);   // arr + 3

std::random_shuffle

  • 헤더: <algorithm>
  • C++14까지 지원, C++17에서 제거됨
  • 주어진 범위의 요소들을 무작위로 섞음
1
std::random_shuffle(v.begin(), v.end());
  • C++11부터는 std::shuffle을 사용하는 것이 권장됨

std::shuffle (C++11~)

  • <algorithm> + <random> 필요
  • 난수 엔진을 이용해 안전하게 섞기
1
2
3
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);

std::iota

  • 헤더: <numeric>
  • 지정된 범위에 연속된 값을 자동으로 채움
1
2
std::vector<int> v(5);
std::iota(v.begin(), v.end(), 1);  // 1, 2, 3, 4, 5
  • C 배열에도 사용 가능:
1
2
int arr[5];
std::iota(std::begin(arr), std::end(arr), 10); // 10, 11, ...

요약

함수헤더기능
count<algorithm>특정 값의 개수 세기
count_if<algorithm>조건을 만족하는 개수 세기
begin / end<iterator>범용 이터레이터 추출
random_shuffle<algorithm>랜덤 셔플 (C++14까지)
shuffle<algorithm> + <random>안전한 셔플 (C++11~)
iota<numeric>연속된 숫자 채우기


C++ 실수 출력과 소숫점 반올림/올림/내림 함수 정리


실수 출력 시 소숫점 자릿수 지정

헤더: <iomanip>

1
2
3
4
5
6
7
#include <iostream>
#include <iomanip>

double num = 3.141592;

std::cout << std::fixed << std::setprecision(2) << num << std::endl;
// 출력: 3.14
조합의미
std::fixed소수점 이하 고정 표시
std::setprecision(n)소숫점 이하 n자리 출력

반올림/올림/내림 함수

헤더: <cmath>

1. std::round(x)

  • 가장 가까운 정수로 반올림
  • .5 이상은 올림, 미만은 내림
1
2
3
std::round(3.2);  // 3
std::round(3.8);  // 4
std::round(-2.5); // -2

2. std::floor(x)

  • 내림 (작은 쪽 정수로)
  • 소수점 버림
1
2
std::floor(3.7);  // 3
std::floor(-3.7); // -4

3. std::ceil(x)

  • 올림 (큰 쪽 정수로)
1
2
std::ceil(3.2);   // 4
std::ceil(-3.2);  // -3

소숫점 n자리에서 반올림 / 올림 / 내림 하기

공식: 함수(x * 10^n) / 10^n

예: 소숫점 2자리에서 반올림

1
2
double x = 3.141592;
double result = std::round(x * 100.0) / 100.0;  // 3.14

예: 소숫점 1자리에서 올림

1
double result = std::ceil(x * 10.0) / 10.0;     // 3.2

예: 소숫점 3자리에서 내림

1
double result = std::floor(x * 1000.0) / 1000.0; // 3.141

요약 표

함수설명예시 (x = 3.1415)
std::round(x)반올림3.0
std::ceil(x)올림4.0
std::floor(x)내림3.0
std::round(x * 100) / 100소숫점 2자리 반올림3.14
std::ceil(x * 10) / 10소숫점 1자리 올림3.2
std::floor(x * 1000) / 1000소숫점 3자리 내림3.141

참고

  • 모든 함수는 <cmath>에 포함
  • 출력 자릿수 제어는 <iomanip> 조합 사용

precision() vs setprecision()

항목precision()setprecision(n)
종류스트림의 멤버 함수조정자(manipulator)
헤더<ostream><iomanip>
사용 방식cout.precision(n);cout << setprecision(n);
반환 값이전 precision 값 반환없음
체이닝 사용불편함체이닝에 적합

예제 비교

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265;

    // setprecision: 체이닝에 적합
    std::cout << std::fixed << std::setprecision(3) << pi << std::endl;  // 3.142

    // precision(): 직접 설정
    std::cout.precision(4);
    std::cout << std::fixed << pi << std::endl;  // 3.1416
}
  • std::setprecision(n)은 일시적 조정자
  • .precision(n)은 스트림의 속성을 직접 바꿈

출력 체이닝

<< 연산자를 연속적으로 사용하여 여러 값을 한 줄로 출력하는 방식.

  • << 연산자는 내부적으로 std::ostream&를 반환합니다.

  • 즉, 다음 출력 대상도 같은 std::cout에 계속 이어붙일 수 있게 해줍니다.

1
std::ostream& operator<<(std::ostream& os, const T& val);

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.