c++ - 在 vector<complex <double>> 上使用 equal(),find()

标签 c++ stl find complex-numbers

这是一件非常简单的事情,但我一直在绞尽脑汁试图理解。我正在尝试比较 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/

相关文章:

c++ - 否定一个数字的最快方法

c++ - std::vector 的问题

c++ - 为什么顺序容器同时具有 size_type 和 difference_type?

jquery - 使用 jQuery 获取链接文本(如果有)或图像的 id(如果是图像链接)

bash - 找到,xargs : execute chain of commands for each file

c++ - g++-带有-O选项的浮点行为不是严格的C++11标准保形?

c++ - 如何使用 boost::spirit 验证代数语句?

C++ 标准 :search behavior or restriction

c++ - 迭代器跳过循环

c++ - 如何在 C++ 的字符串中找到一个完整的单词(不是它的一部分)