0

这是一件非常简单的事情,但我一直在努力理解。我正在尝试将vector<complex <double> >vec 的元素与complex <double>num 进行比较,以检查 vec 上是否已存在 num。如果有,则不添加。我尝试使用 equal() 和算法,但没有成功。有谁知道一个快速的方法来做到这一点?

EDIT2:为了简化,我试图对复数执行此操作,因为我还需要对结构执行相同的操作:

struct thing{
 int i;
 int j;
 complex <double> pos;
}typedef t_thing;

complex <double> new_num(2.0,2.0);
t_thing will_insert;
will_insert.i = 1;
will_insert.j = 1;
will_insert.pos = new_num;
vector<t_thing> vec_thing;
if(! (find(vec_thing.begin(),vec_thing.end(),will_insert) == vec_thing.end())){
  vec_thing.push_back(will_insert);
}else { 
 cout<<"element already on vec_thing"<<endl;
}

编辑 3:我重载了运算符 ==,但 find 无法使用它:

: error: no matching function for call to ‘find(__gnu_cxx::__normal_iterator<thing*, std::vector<thing, std::allocator<thing> > >, __gnu_cxx::__normal_iterator<thing*, std::vector<thing, std::allocator<thing> > >, t_thing&)’
4

1 回答 1

4

std::equal算法用于比较 2 个迭代器范围。因此,您将使用它来比较例如 2 个向量,以查看两个向量是否包含相同的元素。

在您的情况下,您只需要检查单个元素是否在向量内,您可以使用std::find

if (std::find(vec.begin(), vec.end(), std::complex<double>(1,1)) == vec.end()) {
   /* did not find element */
}
else { /* found the element */ }

但是请注意,这std::vector并不是特别适合像这样的查找算法,因为每次查找都会给您 O(N) 复杂度。您可能想考虑使用std::set,因此您可以获得对数复杂性进行查找,并自动保证您没有任何重复的元素。

于 2010-09-24T21:14:55.753 回答