C++/Modern C++(11, 14, 17, 20)

[C++11 - library features] std::begin/end

deulee 2023. 8. 28. 16:30

`std::begin``std::end`는 C++11에서 도입된 컨테이너의 일반적인 `begin``end` 반복자를 반환해주는 기능이다.

 

이들의 특징은 특정 클래스의 멤버 함수로써 존재하는 것이 아니라 "raw array"와 같이 `begin`과 `end` 멤버 함수가 없는 배열에도 유용하게 사용된다는 것이다.

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

template <typename T>
int CountTwos(const T& container)
{
	return std::count_if(std::begin(container), std::end(container), [](int item){
		return item == 2;
	});
}

int main(void)
{
	std::vector<int> vec = {2, 2, 43, 435, 4345345, 3434};
	int arr[8] = {2, 12, 13 ,15 , 1, 66, 3, 9};
	auto a = CountTwos(vec); // 2
	auto b = CountTwos(arr); // 1
	std::cout << a << ' ' << b << std::endl;
	return 0;
}