簡體   English   中英

std::map 用迭代器查找距離,程序不會終止

[英]std::map find distance with iterators, program does not terminate

當我編譯( g++ -std=c++14 map.cpp )並運行這個程序時,它似乎沒有終止。 任何人都可以解釋為什么? 然而,當我找到('a')而不是'c'時,它給出了一個零。

#include <iostream>
#include <string>
#include <vector>
#include <map> 
#include <algorithm>
using namespace std; 



int main()
{
    map<char, float> m;
    m['a'] = 3.4;
    m['b'] = 5.3;
    m['c'] = 33.3;
    m['d'] = 43.;

    auto it = m.find( 'c' );
    cout << "distance : " << std::distance( it , m.begin() ) << endl;

}

利用

std::distance( m.begin(), it  )

否則調用

std::distance( it , m.begin() )

具有未定義的行為,因為使用了無效范圍。 C++ 中的范圍被指定為[first, last ) ,其中 first 優先於或等於 last。 在第一個等於最后一個的最后一種情況下,范圍為空。

來自 C++ 標准(27.4.3 迭代器操作)

4 效果:如果 InputIterator 滿足隨機訪問迭代器的要求,則返回(last - first); 否則,返回從 first 到 last 所需的增量數

std::distance(first,last)first開始運行並推進迭代器直到到達last 在您的情況下,這永遠不會發生,因為it很可能m.begin()之后找到,所以它會永遠循環。 更改給std::distance的參數順序

標准::距離參考:

如果 last 不能通過(可能重復)首先遞增從 first 到達,則行為未定義。

暫無
暫無

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

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