简体   繁体   English

std::map 用迭代器查找距离,程序不会终止

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

As I compile ( g++ -std=c++14 map.cpp ) and run this program, it doesn't seem to terminate.当我编译( g++ -std=c++14 map.cpp )并运行这个程序时,它似乎没有终止。 Can any one explain Why?任何人都可以解释为什么? However as I do find('a') instead of 'c' it gives a zero.然而,当我找到('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;

}

Use利用

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

Otherwise the call否则调用

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

has undefined behavior because there is used an invalid range.具有未定义的行为,因为使用了无效范围。 Ranges in C++ are specified like [first, last ) where first precedes or equal to last. C++ 中的范围被指定为[first, last ) ,其中 first 优先于或等于 last。 In the last case when first is equal to last the range is empty.在第一个等于最后一个的最后一种情况下,范围为空。

From the C++ Standard (27.4.3 Iterator operations)来自 C++ 标准(27.4.3 迭代器操作)

4 Effects: If InputIterator meets the requirements of random access iterator, returns (last - first); 4 效果:如果 InputIterator 满足随机访问迭代器的要求,则返回(last - first); otherwise, returns the number of increments needed to get from first to last .否则,返回从 first 到 last 所需的增量数

std::distance(first,last) starts running from first and advances the iterator until it reaches the last . std::distance(first,last)first开始运行并推进迭代器直到到达last In your case this will never happen because it is most likely found after m.begin() so it'll loop forever.在您的情况下,这永远不会发生,因为it很可能m.begin()之后找到,所以它会永远循环。 change the order of parameters given to std::distance更改给std::distance的参数顺序

std::distance reference: 标准::距离参考:

The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.如果 last 不能通过(可能重复)首先递增从 first 到达,则行为未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM