如何查看提升集中<cpp_int>的下一个和上一个元素

How to peek next and prev elements in a boost set<cpp_int>

本文关键字:gt 下一个 元素 上一个 int cpp 何查看 集中 lt      更新时间:2023-10-16

我正试图将提升整数cpp_int存储在有序集合中,并使用以下代码检查next和prev元素:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/unordered_set.hpp>
#include <iostream>
namespace mp = boost::multiprecision;
using boost::unordered_set;
using namespace std;
int main() {
set<mp::cpp_int> st;
set<mp::cpp_int>::iterator it, it1, it2;
//pair<set<mp::cpp_int>::iterator,bool> res;
boost::tuples::tuple<set<mp::cpp_int>::iterator, bool> tp;
int i = 0, temp;
while(i<10){
cin>>temp;
tp = st.insert(temp);
it = get<0>(tp);
it1 = prev(it);
it2 = next(it);
cout<<*it1<<endl;
//cout<<*it2<<endl;
i++;
}
return 0; 
}

然而,上面的代码并没有像预期的那样工作,并且在两次输入后崩溃。一个这样的崩溃输入序列是:

0
1
2
3
4
0

使用boost时,使用集合和迭代器的正确方法是什么?

在取消引用it1it2之前,您需要检查是否存在上一个/下一个元素,例如:

std::set<mp::cpp_int> s;
for (size_t i = 0; i < 10; ++i){
std::cin >> temp;
auto p = s.insert(temp);
if (p.second) { // insertion succeed
auto it = p.first;
std::cout << "Inserted: " << *it << 'n';
if (it != s.begin()) { // not the first, there is a previous element
auto it1 = std::prev(it);
std::cout << "Previous: " << *it1 << 'n';
}
else {
std::cout << "Previous: Nonen";
}
auto it2 = std::next(it);
if (it2 != s.end()) { // there is a next element
std::cout << "Next: " << *it2 << 'n';
}
else {
std::cout << "Next: Nonen";
}
}
}

此外,如果要查找现有元素的上一个和下一个元素,则应使用std::set::find,而不是std::set::insert:

auto it = s.find(temp);
if (it != s.end()) {
// Same code as above.
}