如何查看提升集中<cpp_int>的下一个和上一个元素
How to peek next and prev elements in a boost set<cpp_int>
我正试图将提升整数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时,使用集合和迭代器的正确方法是什么?
在取消引用it1
和it2
之前,您需要检查是否存在上一个/下一个元素,例如:
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.
}
相关文章:
- 重新定位图像时如何前进到下一个内存块
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- CIN 仅在输入非数字值时跳过下一个 CIN
- 查找最小的下一个更大的元素
- 转到基于范围的 for 循环中的下一个迭代器
- 如何检查流中文件的下一个单词是否为 alpha?
- 如何打印下一个字母直到 Z 并继续到 A?
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 有没有一种标准方法可以在C++中获取第 n 个"下一个"浮点值
- 下一个云桌面客户端构建过程
- C++自定义流操纵器,用于更改流上的下一个字符串
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 下一个排列定义
- 查找下一个具有真值C++的数组索引
- 如何比较文件中包含的下一个字符
- 检查IP是否在其他IP网络范围内,并查找下一个可用IP
- 当我使用c++生成器时,如何在输入完成后自动跳转到下一个"TEdit"
- 如何在没有运算符>>的情况下从字符串流返回下一个令牌?