簡體   English   中英

簡單迭代器差異導致“操作員不匹配”錯誤

[英]“No match for operator-” error on simple iterator difference

這是我的代碼:

#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>]()'

我無法弄清楚迭代器差異是如何突然停止工作的! 我在這里想念什么嗎?

由於無法在std::set上有效地實現此操作,因此未提供。 std::set提供(恆定)雙向迭代器 ,可以沿任一方向移動,但不能跳躍任意距離,例如std::vector提供的隨機訪問迭代器。 您可以在此處查看迭代器概念的層次結構。

相反,請使用std::distance函數,但要注意,在這種情況下,這是一個O(n)操作,必須沿着兩個迭代器之間的每個步驟進行操作,因此請謹慎使用大型std::set s, std::list s等。

std::set迭代器是BidirectionalIterators ,不是RandomAccessIterators。 前者未定義operator- 使用std::distance計算迭代器之間的差異。

#include <iterator>
// ...
auto x = std::distance(st.begin(), st.find(1));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM