std::distance는 두 반복자 사이의 요소 개수를 반환하는 함수로, 시간 복잡도는 반복자의 종류에 따라 다르다.
임의 접근 반복자(random access iterator): std::vector, std::array 같은 컨테이너에 사용되며, 시간 복잡도는 O(1)이다.
순차 반복자(input, forward, bidirectional iterator): std::list, std::forward_list 같은 컨테이너에 사용되며, 시간 복잡도는 O(n)이다.
std::distance(시작_반복자, 끝_반복자);
#include <iostream>
#include <vector>
#include <iterator> // std::distance
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
// 두 반복자 사이의 거리 계산
int dist = std::distance(vec.begin(), vec.end());
std::cout << "Distance: " << dist << "\n"; // 출력: Distance: 5
return 0;
}
#include <iostream>
#include <iterator> // std::distance
int main() {
int arr[] = {1, 2, 3, 4, 5};
// 배열의 시작과 끝 반복자 사이의 거리 계산
int dist = std::distance(std::begin(arr), std::end(arr));
std::cout << "Distance: " << dist << "\n"; // 출력: Distance: 5
return 0;
}
#include <iostream>
#include <list>
#include <algorithm>
#include <iterator> // std::distance
int main() {
std::list<int> lst = {1, 3, 5, 7, 9};
// 리스트에서 값 3과 값 9 사이의 거리 계산
auto it1 = std::find(lst.begin(), lst.end(), 3);
auto it2 = std::find(lst.begin(), lst.end(), 9);
if (it1 != lst.end() && it2 != lst.end()) {
int dist = std::distance(it1, it2);
std::cout << "Distance between 3 and 9: " << dist << "\n"; // 출력: Distance between 3 and 9: 3
} else {
std::cout << "One of the elements not found\n";
}
return 0;
}
#include <iostream>
#include <string>
#include <iterator> // std::distance
int main() {
std::string str = "Hello, World!";
// 문자열의 시작과 끝 사이의 거리 계산
int dist = std::distance(str.begin(), str.end());
std::cout << "Distance: " << dist << "\n"; // 출력: Distance: 13
return 0;
}