상세 컨텐츠

본문 제목

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

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

by 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;
}

'C++ > Modern C++(11, 14, 17, 20)' 카테고리의 다른 글

[C++11] Move Semantics  (0) 2023.08.28
[C++11] Rvalue references  (0) 2023.08.28
[C++11] Forwarding References(Universal References)  (0) 2023.08.28
[C++11] Variadic templates  (0) 2023.08.28
[C++11] Initializer lists  (0) 2023.08.28

관련글 더보기