2010-06-29 5 views
13

컴파일되지 않습니다 :'std :: vector <T> :: iterator it;' 나는이 기능을 가지고

template<typename T> 
    void Inventory::insertItem(std::vector<T>& v, const T& x) 
    { 
     std::vector<T>::iterator it; // doesn't compile 
     for(it=v.begin(); it<v.end(); ++it) 
     { 
      if(x <= *it) // if the insertee is alphabetically less than this index 
      { 
       v.insert(it, x); 
      } 
     } 
    } 

및 g 것은 ++ 이러한 오류 제공 :

src/Item.hpp: In member function ‘void 
yarl::item::Inventory::insertItem(std::vector<T, std::allocator<_CharT> >&, const T&)’: 
src/Item.hpp:186: error: expected ‘;’ before ‘it’ 
src/Item.hpp:187: error: ‘it’ was not declared in this scope 

뭔가 간단합니다,하지만 내가 할 수있는 그것을 쳐다보고 십 분 ' 잘못된 것을 찾지 마라. 누구든지 그것을 볼 수 있습니까?

+2

btw을 사용하면'it

답변

28

대신을 시도해보십시오

typename std::vector<T>::iterator it; 

여기 how to use typename을 설명하는 페이지이고 왜 여기 필요가있다.

+0

그랬어. 감사. – Max

+0

+1은 간결한 답변이고 자세한 설명은 링크입니다. – stinky472

8

당신이하는 일은 비효율적입니다.

#include <algorithm> 

template <typename T> 
void insertItem(std::vector<T>& v, const T& x) 
{ 
    v.insert(std::upper_bound(v.begin(), v.end(), x), x); 
} 
+2

+1 - 나를 때려 눕히십시오. 현재 코드가 삽입 후에 루프에서 빠져 나가지 않기 때문에 일반적으로 새로운 항목의 추가 사본을 삽입하지 않을 것이라고 언급 할 가치가 있습니다. –

+2

@ Jerry : 벡터의 크기가 용량과 같으면 삽입하기 전에 가져온 모든 반복자를 무효화하므로'++ it'은 정의되지 않은 동작 영역으로 바로 이어집니다. – fredoverflow

+1

+1 (그러나 내가 +10을 줄 수 있었 더라면 좋겠다). 두 번째 코드를 보면 빌드 오류는 코드의 런타임 동작과 비교할 때 사소한 문제 일뿐입니다. – stinky472

관련 문제