簡體   English   中英

使用迭代器在向量c ++中循環

[英]loop in vector c++ using iterator

我有以下代碼:

std::vector<A>::iterator it;
for(auto it = m_vA.begin(); it != m_vA.end(); it++)

我發現一個錯誤:

ISO C++ forbids declaration of 'it' with no type
cannot convert '__gnu_cxx::__normal_iterator<A* const*, std::vector<tp::Vehicule*, std::allocator<A*> > >' to 'int' in initialization

如果我刪除了自動

erreur: no match for 'operator=' in 'it = ((const B*)this)->B::m_vA.std::vector<_Tp, _Alloc>::begin [with _Tp = A*, _Alloc = std::allocator<A*>]()'

B是我的循環班

謝謝

對於auto您似乎沒有啟用c ++ 11,如果啟用它,則應刪除以下行:

std::vector<A>::iterator it;

如果您不能使用c ++ 11並在刪除auto后出現錯誤,則好像將此代碼放入const方法中,因此將迭代器替換為const_iterator:

std::vector<A>::const_iterator it;
for(it = m_vA.begin(); it != m_vA.end(); it++)

如果循環后不需要此迭代器,也可以將其設為一行:

for(std::vector<A>::const_iterator it = m_vA.begin(); it != m_vA.end(); it++)

據我所知,您處於const方法中,應使用const_iterator或刪除const

如果您之前聲明了變量,則不需要auto 它不會產生錯誤,只會發出警告,但是您必須選擇一種方式;)

要解決您的問題,請刪除 auto關鍵字。

您必須啟用C ++ 11才能使用auto 如果使用的是gcc編譯器,則可以通過-std=c++11-std=c++0x編譯器的開關啟用它。

當前,它使用的是較早的C編譯器繼承的auto關鍵字,將被忽略。 編譯器認為您要再次聲明it ,但是沒有類型。

如果確實啟用了C ++ 11,那么為什么要使用auto這樣呢? 只需使用基於范圍的for循環:

for (auto i : m_vA)
    // do stuff here with i

同樣,代碼的問題是您指定了it的類型,因此在for循環中使用auto毫無意義。 同樣,如果您使用的是C ++ 11,則應使用上面的循環,因為它更容易編寫和理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM