給定兩個整數向量,如何確定第一個向量中是否存在某個元素?查找第二個向量中的向量元素
回答
我想這樣的事情應該工作:
std::vector<int> v1,v2;
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end())
std::cout << "found!\n";
這正是我要找的 – dimba 2009-12-10 18:20:02
雖然在O(v1.size()* v2.size())這個複雜度上看起來可能更糟糕,但它對於小集合並不重要,而且你也不需要必須事先修改(排序)你的載體。 – 2009-12-10 18:21:54
你可以採取兩個向量的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
工作,兩個向量必須先排序。
值得注意的是,v1和v2必須進行排序才能正常工作。 – 2009-12-10 18:11:33
值得注意的是,你應該更喜歡'v3.empty()'到'v3.size()== 0'。 – 2009-12-10 18:19:12
@Charles Bailey和@Matthie M .:我加了這兩個,謝謝。 – 2009-12-11 00:40:21
我覺得是這樣的:
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);
他們是排序,可他們的地方進行排序或做他們必須留在他們目前的訂購? – 2009-12-10 18:02:55
這是功課嗎?如果是,它應該被標記爲這樣。 – Andres 2009-12-10 18:04:32
你有複雜性約束嗎? – philsquared 2009-12-10 18:06:29