mku*_*use 2 c++ iterator distance stdmap range
当我编译(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;
}
Run Code Online (Sandbox Code Playgroud)
使用
std::distance( m.begin(), it )
Run Code Online (Sandbox Code Playgroud)
否则打电话
std::distance( it , m.begin() )
Run Code Online (Sandbox Code Playgroud)
具有未定义的行为,因为使用了无效的范围。在C ++中指定范围,例如[first, last )first之前或等于last的位置。在后一种情况下,当first等于last时,范围为空。
来自C ++标准(27.4.3迭代器操作)
4效果:如果InputIterator满足随机访问迭代器的要求,则返回(最后-优先);否则,返回从first到last所需的增量数。