오보에블로그

[STL] STL 알고리즘 정리 본문

C++ & C#/Modern C++

[STL] STL 알고리즘 정리

(OBO) 2022. 1. 31. 16:26
728x90

count , count_if

template< class InputIt, class T >
typename iterator_traits<InputIt>::difference_type
    count( InputIt first, InputIt last, const T& value );
  • 해당 값 또는 해당 조건식을 만족하는 데이터 개수 반환
vector<int> v = { 1,2,3,4,5,4,3,2,1 };

cout << count(v.begin(), v.end(), 3) << endl; // 2
cout << count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) << endl; // 4

find, find_if, find_if_not

  • 구현부
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
  • 첫번째로 지정 값이나 조건식을 만족하는 원소의 이터레이터 리턴
  • 예시
vector<int> v = { 1,2,3,4,5,4,3,2,1 };

bool r1 = find(v.begin(), v.end(), 5) != v.end();
cout << r1 << endl; // 1

bool r2 = find_if(v.begin(), v.end(), [](int x) { return x <= 5; }) != v.end();
cout << r2 << endl; // 1

bool r3 = find_if_not(v.begin(), v.end(), [](int x) { return x <= 5; }) != v.end();
cout << r3 << endl; // 0

fill

  • 구현부
template< class ForwardIt, class T >
void fill( ForwardIt first, ForwardIt last, const T& value );
  • 지정된 범위의 요소를 지정한 값으로 할당
fill(v.begin(), v.end(), 3);

generate

  • 지정된 범위의 요소를 지정 함수식의 리턴 값으로 할당
vector<int> v(3);
int x = 1;
generate(v.begin(), v.end(), [&x]() {x *= 2; return x; }); // 2 4 8

for_each

  • 구현부
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
  • first 이터레이터부터 last 이터레이터 까지 각 원소마다 f 적용한다.
  • 예시
vector<int> v1 = { 1,2,3,4,5 };
for_each(v1.begin(), v1.end(), [](int x) { x++; });

copy, copy_if

  • 해당 범위만큼의 아이템을 다른 컨테이너의 지정 위치부터 복사
  • count_if는 해당 조건식을 만족하는 아이템만 복사한다.
vector<int> v1 = { 1,2,3 };
vector<int> v2(3); // 복사하는 용량보다 복사 시작지점부터의 용량이 작으면 오류 발생

copy(v1.begin(), v1.end(), v2.begin());
vector<int> v1 = { 1,2,3 };
vector<int> v2(3);

copy_if(v1.begin(), v1.end(), v2.begin(), [](int x) {return x % 2 == 1; }); // 1 3 0

replace, replace_if

  • 지정 범위에서 특정 값이면 지정 값으로 변경
vector<int> v1 = { -1,-2,-1,4,-1,6};
replace(v1.begin(), v1.end(), -1, INT_MAX); // INT_MAX -2 INT_MAX 4 INT_MAX 6

vector<int> v2 = { -1,-2,-1,4,-1,6 };
replace_if(v2.begin(), v2.end(), [](int x) {return x < 0; }, INT_MAX); // INT_MAX INT_MAX INT_MAX 4 INT_MAX 6

all_of

  • 구현부
template< class InputIt, class UnaryPredicate >
constexpr bool all_of( InputIt first, InputIt last, UnaryPredicate p );
  • 해당 조건식을 모두 만족시키는지
  • 예시
bool a1 = all_of(v1.begin(), v1.end(), [](int x) {return x < 10; }); // true;

any_of

  • 구현부
template< class InputIt, class UnaryPredicate >
bool any_of( InputIt first, InputIt last, UnaryPredicate p );
  • 해당 조건식에 한 원소라도 만족시키는 원소가 있는지
  • 예시
bool a2 = any_of(v1.begin(), v1.end(), [](int x) {return x < 10; }); // false;
728x90

'C++ & C# > Modern C++' 카테고리의 다른 글

[C++20] Range  (0) 2022.01.31
[C++20] Concepts library  (0) 2022.01.31
[C++20] Concept  (0) 2022.01.30