当我编译(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/