“操作员不匹配-"简单迭代器差异上的错误 [英] "No match for operator-" error on simple iterator difference

查看:104
本文介绍了“操作员不匹配-"简单迭代器差异上的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

#include <set>
#include <iostream>
using namespace std;

int main(){
    set<int> st;
    st.insert(1);
    int x = st.find(1) - st.begin();

    return 0;
}

我得到了error: no match for 'operator-' in 'st.std::set<_Key, _Compare, _Alloc>::find [with _Key = int, _Compare = std::less<int>, _Alloc = std::allocator<int>](((const int&)((const int*)(&1)))) - st.std::set<_Key, _Compare, _Alloc>::begin [with _Key = int, _Compare = std::less<int>, _Alloc = std::allocator<int>]()'.

我无法弄清楚迭代器差异是如何突然停止工作的!我在这里想念什么吗?

I am not able to figure out how did iterator difference stopped working all of a sudden! Am I missing something here?

推荐答案

由于无法在std::set上有效地实现此操作,因此未提供. std::set提供了(恒定)双向迭代器,它可以沿任一方向移动,但不能任意跳转距离,例如std::vector提供的随机访问迭代器.您可以在此处看到迭代器概念的层次结构.

Because this operation can't be implemented efficiently on a std::set, it is not provided. std::set provides (Constant) Bidirectional Iterators, that can be moved in either direction, but not jumped arbitrary distances, like the Random Access Iterators provided by std::vector. You can see the hierarchy of iterator concepts here.

相反,请使用 std::distance 函数,但是请注意,在这种情况下,这是O(n)操作,必须沿着两个迭代器之间的每一步走,因此请谨慎在大型std::setstd::list s等上使用此操作.

Instead, use the std::distance function, but be aware that for this case, this is an O(n) operation, having to walk along every step between the two iterators, so be cautious about using this on large std::sets, std::lists, etc.

这篇关于“操作员不匹配-"简单迭代器差异上的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆