gpt4 book ai didi

c++ - std::map - 递减迭代器给出奇怪的结果?

转载 作者:行者123 更新时间:2023-12-05 01:23:44 24 4
gpt4 key购买 nike

似乎无法解决这个问题。简单示例如下:

#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

最佳答案

这个电话

std::map<uint32_t, char>::iterator i = m.lower_bound('d');

返回迭代器m.end()。所以取消引用迭代器

std::cout << "First: " << i->first << std::endl;

导致未定义的行为。

成员函数 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';
}

程序输出为

i == m.end() is true

相反,你可以这样写

std::map<uint32_t, char>::iterator i = m.lower_bound( 5 );

在这次调用之后递减迭代器之后

std::map<uint32_t, char>::iterator i = m.lower_bound('d');

它指向 map 的最后一个元素。

关于c++ - std::map - 递减迭代器给出奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71930082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com