[英]How to use lower_bound/upper_bound to get index number from std::set?
[英]std::set, how do lower_bound and upper_bound work?
我有这么简单的代码:
#include <iostream>
#include <set>
using std::set;
int main(int argc, char argv) {
set<int> myset;
set<int>::iterator it_l, it_u;
myset.insert(10);
it_l = myset.lower_bound(11);
it_u = myset.upper_bound(9);
std::cout << *it_l << " " << *it_u << std::endl;
}
这将打印1作为11的下限,10作为9的上限。
我不明白为什么打印1。 我希望使用这两种方法来获得给定上限/下限的一系列值。
来自cppreference.com
的std :: set :: lower_bound :
返回值
迭代器指向第一个不小于键的元素。 如果找不到这样的元素,则返回一个past-the-end迭代器(参见end() )。
在您的情况下,由于您的集合中没有不小于(即大于或等于)11的元素,因此返回过去的迭代器并将其分配给it_l
。 然后在你的行:
std::cout << *it_l << " " << *it_u << std::endl;
您正在it_l
这个过去的结束迭代器it_l
:这是未定义的行为,并且可能导致任何内容(测试中的1,0或其他编译器的任何其他值,或者程序甚至可能崩溃)。
您的下限应小于或等于上限,并且不应取消引用循环外的迭代器或任何其他测试环境:
#include <iostream>
#include <set>
using std::set;
int main(int argc, char argv) {
set<int> myset;
set<int>::iterator it_l, it_u;
myset.insert(9);
myset.insert(10);
myset.insert(11);
it_l = myset.lower_bound(10);
it_u = myset.upper_bound(10);
while(it_l != it_u)
{
std::cout << *it_l << std::endl; // will only print 10
it_l++;
}
}
这是UB。 你的it_l = myset.lower_bound(11);
返回myset.end()
(因为它找不到集合中的任何内容),你没有检查,然后你基本上打印出past-the-end迭代器的值。
lower_bound()将迭代器返回给第一个不小于键的元素。 如果找不到这样的元素,则返回end()。
请注意,使用end()返回的迭代器指向集合中过去的结尾元素。 这是标准容器的正常行为,表明出现了问题。 根据经验,您应该始终检查并采取相应措施。
您的代码是上述情况的示例,因为集合中没有不少于11的元素。 打印的'1'只是来自end()迭代器的垃圾值。
请使用以下代码段自行查看:
#include <iostream>
#include <set>
using std::set;
int main(int argc, char argv) {
set<int> myset;
set<int>::iterator it_l, it_u;
myset.insert(10);
it_l = myset.lower_bound(11);
if (it_l == myset.end()) {
std::cout << "we are at the end" << std::endl;
}
it_u = myset.upper_bound(9);
std::cout << *it_l << " " << *it_u << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.