Bri*_*ian 3 c++ algorithm dictionary iterator undefined-behavior
似乎无法解决这个问题。简单例子如下:
#include <iostream>
#include <map>
int main() {
std::map<uint32_t, char> m;
m[1] = 'b';
m[3] = 'd';
m[5] = 'f';
std::map<uint32_t, char>::iterator i = m.lower_bound('d');
std::cout << "First: " << i->first << std::endl;
// Decrement the iterator
i--;
// Expect to get 1, but get 5?
std::cout << "Second: " << i->first << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
First: 3
Second: 5
Run Code Online (Sandbox Code Playgroud)
为什么我这里是5?我认为递减迭代器会导致它指向键 1
这个电话
std::map<uint32_t, char>::iterator i = m.lower_bound('d');
Run Code Online (Sandbox Code Playgroud)
返回迭代器m.end()
。所以取消引用迭代器
std::cout << "First: " << i->first << std::endl;
Run Code Online (Sandbox Code Playgroud)
导致未定义的行为。
成员函数lower_bound
需要一个指定键而不是值的参数。
考虑以下演示程序。
#include <iostream>
#include <iomanip>
#include <map>
#include <cstdint>
int main()
{
std::map<uint32_t, char> m;
m[1] = 'b';
m[3] = 'd';
m[5] = 'f';
std::map<uint32_t, char>::iterator i = m.lower_bound( 'd' );
std::cout << "i == m.end() is " << std::boolalpha << ( i == m.end() ) << '\n';
}
Run Code Online (Sandbox Code Playgroud)
程序输出是
i == m.end() is true
Run Code Online (Sandbox Code Playgroud)
相反,你可以写例如
std::map<uint32_t, char>::iterator i = m.lower_bound( 5 );
Run Code Online (Sandbox Code Playgroud)
在此调用后递减迭代器之后
std::map<uint32_t, char>::iterator i = m.lower_bound('d');
Run Code Online (Sandbox Code Playgroud)
它指向地图的最后一个元素。