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

标签 c++ iterator range distance stdmap

当我编译(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 ),其中第一个优先于或等于最后一个。在最后一种情况下,当第一个等于最后一个时,范围为空。

来自 C++ 标准(27.4.3 迭代器操作)

4 Effects: If InputIterator meets the requirements of random access iterator, returns (last - first); otherwise, returns the number of increments needed to get from first to last.

关于c++ - std::map 使用迭代器查找距离,程序不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58711776/

相关文章:

c++ - boost::asio::write() VS socket->write_some()

c++ - 有谁知道在 Linux 的终端窗口中显示图形的技术名称是什么?

c++ - "Undefined reference"尝试引用静态字段

c++ - 为什么有些 libstdc++ 迭代器有 operator++ 但没有 operator+?

javascript - 使用 Shift 键时如何限制选择元素中的选定选项

python glob匹配更广泛的范围

c++ - 是否必须定义所有静态类方法,即使未使用?

C++ vector 迭代器 + 偏移量超出范围

java - Java中迭代链表,同时直接在next()方法中过滤?

javascript - 浏览器中范围和选择的区别