这是一件非常简单的事情,但我一直在绞尽脑汁试图理解。我正在尝试比较 vector<complex <double> >
的元素vec 与 complex <double>
num 来检查 num 是否已经存在于 vec 上。如果是,则不添加。我尝试使用 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&)’
最佳答案
std::equal
算法用于比较 2 个迭代器范围。例如,您可以使用它来比较 2 个 vector ,看看这两个 vector 是否包含相同的元素。
在你的例子中,你只需要检查一个元素是否在 vector 中,你可以只使用 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
,这样您就可以获得查找的对数复杂度,并自动保证您没有任何重复元素。
关于c++ - 在 vector<complex <double>> 上使用 equal(),find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3791022/