Lv 0. 가장 큰 수 찾기 iterator을 이용해서 배열의 인덱스를 찾으려면, distance() 함수를 사용해보자 *다시 풀어보기*

https://school.programmers.co.kr/learn/courses/30/lessons/120899

 

 

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> array) {
    vector<int> answer;
    int mx=-1;
    int idx=0;
    for(int i=0; i<array.size(); i++){
        if(mx<array[i]){
            mx=array[i];
            idx=i;
        }
    }
    answer.emplace_back(mx);
    answer.emplace_back(idx);
    return answer;
}

 

 

처음에 이 문제의 경우는, max_element()를 이용한 풀이를 떠올렸는데, 이때에 iterator를 반환하는데, 이 반환되는 iterator를 이용해서 해당 배열의 인덱스를 찾는 방법에 대해서 잘 생각이 나지 않아서 일단 위와 같은 풀이를 제출해서 통과하였다. 

이때에 해당 위치의 iterator를 it라고 하면, 인덱스를 찾을때, it-array.begin(); 형태를 이용했던 것으로 기억하는데, 

그것이 맞는지 시험해보기 위해서 아래와 같은 코드를 작성해서 cout의 결과를 보면, 

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

vector<int> solution(vector<int> array) {
    vector<int> answer;
    auto it=max_element(array.begin(),array.end());
    cout<<it-array.begin();
    return answer;
}
테스트 1
입력값 〉	[1, 8, 3]
기댓값 〉	[8, 1]
실행 결과 〉	실행한 결괏값 []이 기댓값 [8,1]과 다릅니다.
출력 〉	1
테스트 2
입력값 〉	[9, 10, 11, 8]
기댓값 〉	[11, 2]
실행 결과 〉	실행한 결괏값 []이 기댓값 [11,2]과 다릅니다.
출력 〉	2

출력의 결과가 문제에서 요구하는 index에 해당하는것을 볼 수 있다. 

결국 iterator를 통해서 컨테이너에서의 인덱스를 구할때는, max_element() 등을 통해서 반환받은 iterator의 값에서, 

해당 컨테이너의 begin() 이터레이터를 빼주면 원하는 위치의 인덱스를 구할 수 있게 된다는것을 알 수 있다. 

위의 사실을 이용해서 코드를 작성해보면, 

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

vector<int> solution(vector<int> array) {
    vector<int> answer;
    auto it=max_element(array.begin(),array.end());
    // cout<<it-array.begin();
    answer.emplace_back(*it);
    answer.emplace_back(it-array.begin());
    return answer;
}

이와 같이 작성할 수 있고, 이 코드를 제출하면 성공적으로 통과할 수 있다. 

 

다른 사람의 풀이를 보았을때 또 새롭게 알게된 함수가 있는데, 

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> array) {
    vector<int> answer;
    auto t = max_element(array.begin(), array.end());
    answer.push_back(*t);
    answer.push_back(distance(array.begin(),t));
    return answer;
}

이와 같은 풀이를 볼 수 있었으며, 이때에 이 코드에서는 인덱스를 구할때, distance() 라는 함수를 이용해서 iterator 사이의 거리를 구할 수 있고, 해당 거리를 0을 기준으로 하는 인덱스의 위치로 사용할 수 있었다. 

 

 

`distance()` 함수는 두 반복자 (iterators) 사이의 요소 개수, 즉 원소들의 거리를 계산하는 C++ 표준 
라이브러리 함수입니다. 이 함수는 템플릿 형태로 정의되어 있어, 다양한 컨테이너 및 반복자 타입에 대해 사용할 수 
있습니다.

`distance()` 함수는 보통 다음과 같이 사용됩니다:

```cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};
    
    auto first = numbers.begin();
    auto last = numbers.end();
    
    int dist = std::distance(first, last);
    
    std::cout << "Distance: " << dist << std::endl; // 출력: Distance: 5
    return 0;
}
```

위의 코드에서 `std::distance()` 함수는 `numbers.begin()`과 `numbers.end()` 반복자 사이의 거리,
즉 원소의 개수를 계산하고 5를 반환합니다.

`distance()` 함수는 컨테이너의 처음과 끝을 가리키는 반복자 두 개를 받아서 두 반복자 사이의 원소 개수를
계산합니다. 이 함수를 `std::max_element()`와 함께 사용하면 최댓값을 가진 원소의 값과 해당 원소의 인덱스를 
구할 수 있습니다.

 

위와 같이 distance() 함수에 대해서 알 수 있었는데, 물론 이 함수를 사용할 수 있겠으나, 이 함수를 알고있는것 뿐만 아니라, 

위에 언급한것처럼 it-array.begin() 형태를 통해서 해당 인덱스를 알아낼 수 있다는것을 알고 이것을 잘 활용하도록 하자. 

지금까지 코딩테스트 문제에서 iterator를 이용해서 index를 구할때는 이정도 선에서도 충분했다. 일단 이 형태를 잘 알아두고, 

그 후에 distance() 함수를 떠올려보자. 

 

  Comments,     Trackbacks