🌍 C++ Study/C++ 기초
C++ std::distance 이터레이터의 거리 구하기
맨텀
2024. 11. 20. 11:38
std::distance
cppreference : std::distance
https://en.cppreference.com/w/cpp/iterator/distance
두 개의 이터레이터의 차이를 구하는 함수.
<algorithm> 헤더에 포함되어있으며,
인자로는 두개의 iterator를 받는다.
첫번째 이터레이터로부터 두번째 이터레이터 까지의 거리 차이를 계산하며,
std::distance(begin, end) → (end - begin)로 동작.
vector같은 랜덤 엑세스 반복자 일 경우, 인자 순서를 바꾸면 음수가 나온다.
순서를 바꾼다면 그냥 직접 뺄셈하는게 나을 수도 있다. it - numbers.begin();
template< class InputIt >
typename std::iterator_traits<InputIt>::difference_type
distance( InputIt first, InputIt last );
사용 예시
다음은 주어진 벡터에서 조건(n < 0)을 만족하는 첫번 째 원소의 인덱스를 반환하는 예시.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> num_list) {
auto it = std::find_if(num_list.begin(), num_list.end(),
[](int num)
{
return num < 0;
});
if (it == num_list.end())
return -1;
return std::distance(num_list.begin(), it);
}