STD :: MAP-减少迭代器给出奇怪的结果?
似乎无法解决这个问题。简单的示例如下:
#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;
}
输出是:
First: 3
Second: 5
为什么我在这里获得5?我认为减少迭代器会导致它指向键1
Can't seem to work this out. Simple example as follows:
#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;
}
The output is:
First: 3
Second: 5
Why do I get 5 here? I thought decrementing the iterator would result in it pointing at key 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此调用
返回迭代器
m.end()
。因此,将迭代剂删除会导致不确定的行为。
成员函数
lower_bound
期望一个参数指定密钥而不是值。考虑以下演示计划。
相反,程序输出是
后,您可以写入。
在此调用之后降低迭代器后
指向地图的最后一个元素
This call
returns the iterator
m.end()
. So dereferencing the iteratorresults in undefined behavior.
The member function
lower_bound
expects an argument that specifies a key not value.Consider the following demonstration program.
The program output is
Instead you could write for example
After decrementing the iterator after this call
it points to the last element of the map.
lower_bound
将作为输入密钥而不是值为输入。这将按照您的期望做到:使用
lower_bound
,您最终找到end()
并迭代一个。lower_bound
takes as input the key, not the value. This would do as you expect:With the
lower_bound
you are using, you end up findingend()
and iterating back one.