2009-12-10 68 views
0

給定兩個整數向量,如何確定第一個向量中是否存在某個元素?查找第二個向量中的向量元素

+0

他們是排序,可他們的地方進行排序或做他們必須留在他們目前的訂購? – 2009-12-10 18:02:55

+0

這是功課嗎?如果是,它應該被標記爲這樣。 – Andres 2009-12-10 18:04:32

+0

你有複雜性約束嗎? – philsquared 2009-12-10 18:06:29

回答

9

我想這樣的事情應該工作:

std::vector<int> v1,v2; 
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end()) 
    std::cout << "found!\n"; 
+0

這正是我要找的 – dimba 2009-12-10 18:20:02

+1

雖然在O(v1.size()* v2.size())這個複雜度上看起來可能更糟糕,但它對於小集合並不重要,而且你也不需要必須事先修改(排序)你的載體。 – 2009-12-10 18:21:54

4

你可以採取兩個向量的set_intersection,然後檢查是否產生交集爲空:

std::sort(v1.begin(), v1.end()); 
std::sort(v2.begin(), v2.end()); 
std::set_intersection(v1.begin() 
    , v1.end() 
    , v2.begin() 
    , v2.end() 
    , std::back_inserter(v3)); 
bool containsElements = !v3.empty(); 

set_intersection可以#include <algorithm>

中找到set_intersection工作,兩個向量必須先排序。

+3

值得注意的是,v1和v2必須進行排序才能正常工作。 – 2009-12-10 18:11:33

+2

值得注意的是,你應該更喜歡'v3.empty()'到'v3.size()== 0'。 – 2009-12-10 18:19:12

+0

@Charles Bailey和@Matthie M .:我加了這兩個,謝謝。 – 2009-12-11 00:40:21

0

我覺得是這樣的:

bool contains(const std::vector<int>& vec, int val){ 
    for(std::vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it){ 
     if(*it==val){ 
      return true; 
     } 
    } 
    return false; 
} 

bool contains(const std::vector<int>& from, const std::vector<int>& in){ 
    for(std::vector<int>::const_iterator it=from.begin(); it!=from.end(); ++it){ 
     if(contains(in, *it)){ 
      return true; 
     } 
    } 
    return false; 
} 

// Example 
std::vector<int> a; 
std::vector<int> b; 

a.push_back(2); 
a.push_back(1); 
b.push_back(0); 
b.push_back(1); 

bool contains = contains(a, b); 
+0

這相當於手寫的。我正在尋找一種STL方式解決方案 – dimba 2009-12-10 18:11:03

+0

我在閱讀完您的意見後發表了意見:P – VDVLeon 2009-12-10 18:23:27