2012-02-13 3 views
2

min_element의 값을 어떻게 저장할 수 있습니까? 그것은 앞으로 반복기라고하지만 나는 변수를 저장하는 방법을 알아낼 수 없습니다. 벡터에서 위치에 따라 액세스 할 수 있기를 원합니다. 찾을 수있는 것은 실제 요소를 사용하는 예입니다 (* min_element() 사용). 나는 min_element 결과의 위치를 ​​저장하는 방법은 무엇입니까?

iterator< forward_iterator_tag, vector<string> > min_word_iterator = min_element(first_words_in_subvecs.begin(), first_words_in_subvecs.end());

을 시도하지만, 작동하지 않았다. 나는 그 색인에있는 요소를 다른 요소로 대체 ​​할 것입니다.

답변

1

당신은을 찾기 위해 STL에서 제공하는 distance을 사용할 수 있습니다 위치. 당신은 당신이 임의 접근 반복자가있는 경우, 당신은 일반적으로을 찾기 위해 다른 하나를 뺄 수

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

int main() { 
    vector<int> myvec; 
    int i = 0; 
    for (i=8; i>0; i--) 
    { 
     myvec.push_back (i*10); 
    } 

    for (i=0; i<8; i++) 
    { 
     cout<<"At pos :"<<i<<"|val is:"<<myvec.at(i)<<endl; 
    } 

    int min_pos = distance(myvec.begin(),min_element(myvec.begin(),myvec.end())); 
    cout << "The distance is: " << min_pos << "|value is "<<*min_element(myvec.begin(),myvec.end())<<endl; 

    return 0; 
} 
+0

나는 어떻게 그것의 int 색인을 얻는가? – Marty

+0

답안에 실린 예제를 참조하십시오. – Raghuram

+0

또한 'min_element (myvec.begin(), myvec.end()) - myvec.begin()'은 괜찮을 것입니다. '거리 (myvec.begin(), min_element (myvec.begin(), myvec.end()))'에서? – altroware

3

사용이 :

std::vector<T>::iterator minIt = std::min_element(v.begin(),v.end()); 
//where T is the type of elements in vector v. 

T minElement = *minIt; //or T & minElement = *minIt; to avoid copy! 

와의

C++ 11 (컴파일러가 auto 키워드를 지원하는 경우), 다음이 :

auto minIt = std::min_element(v.begin(), v.end()); 
//type of minIt will be inferred by the compiler itself 

T minElement = *minIt; //or auto minElement = *minIt; 
         //or auto & minElement = *minIt; to avoid copy 
+0

또는 C++ 11에서'auto minIt = ...'. – GManNickG

+0

@GMan : 예. 나는 이미 이것을 추가했다! – Nawaz

+0

"C++ 11에서 ..."또는 왜 C++ 03 방법으로 시작해야하는지에 대해 이해하지 못합니다. C++ 03이 지나갔고, 라틴어가 죽었고, 우리 시스템에 단지 8 개의 행성 만 있습니다. – wilhelmtell

0

이 예제 코드를 참조 위치

를 얻기 위해 그것을 min_element에 의해 반환 된 반복자를 통과해야 그들 사이의 거리. 따라서 반복자 it을 얻은 후에는 it - my_vector.begin()으로 참조되는 요소의 색인을 찾을 수 있습니다.

관련 문제