2010-06-16 63 views
1

如果我有一個矢量對象矢量,我該如何檢查A * myA是否在該矢量內?如何迭代矢量列表

+1

也許一些代碼會有所幫助。 – GManNickG 2010-06-16 23:46:13

+1

一些澄清(可能與代碼)會很好。你的意思是你有一個指向某些struct A的向量向量? A類型是否相關,或者您的問題是否適用於void *? – Karmastan 2010-06-16 23:59:37

回答

5

嘗試......

#include <algorithm> 

bool in_vector(const std::vector<A*>& vec, const A* myA) 
{ 
    std::vector<A*>::const_iterator end = vec.end(); 
    return std::find(vec.begin(), end, myA) != end; 
} 
+2

'end'將需要是'const_iterator'。 – 2010-06-17 00:35:56

+0

@Mike很好找:) – 2010-06-17 00:36:33

0

這可能會或可能無法正常工作:

vector<int> v; 
. . . 
for (int i=0; i<v.size(); i++) { 
    //---do a compare of v[i] with your object? 
    cout << v[i] << endl; 
} 
0

也許是這樣的:

std::vector<A*> v; 

for (std::vector<A*>::iterator it = v.begin(); it != v.end(); ++it) { 
     // Do comparison with *it to your myA... 
}
0

這是wowus'答案的擴張因爲我認爲它更接近你想要做的事情:

#include <algorithm> 

// let's call it simply TVectorVectorA and TVectorA 
typedef std::vector<std::vector<A*> > TVectorVectorA; 
typedef TVectorVectorA::value_type TVectorA; 

bool in_vector(const std::vector<std::vector<A*> >& vec, const A* myA) 
{ 
    TVectorVectorA::const_iterator vend = vec.end(); 

    // iterate through all 'top-level' vectors 
    for (TVectorVectorA::const_iterator it = vec.begin(); vend != it; ++it) 
    { 
      // check if the current TVector element contains myA 
      if (std::find((*it).begin(), (*it).end(), myA) != end) 
      { 
       return true; 
      } 
    } 

    return false; 
} 

給出一個相關的代碼示例總是很好的。當您提出這些問題時,您正在使用的數據類型的聲明)。這樣,其他人更容易理解你想要做什麼。