c++ - 如何查看 boost set<cpp_int> 中的下一个和上一个元素

标签 c++ boost

我正在尝试将 boost 整数 cpp_int 存储在一个有序 集合中,并使用以下代码检查下一个和上一个元素:

#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: None\n";
        }

        auto it2 = std::next(it);
        if (it2 != s.end()) { // there is a next element
            std::cout << "Next: " << *it2 << '\n';
        }
        else {
            std::cout << "Next: None\n";
        }
    }

}

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

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

关于c++ - 如何查看 boost set<cpp_int> 中的下一个和上一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575056/

相关文章:

c++ - 如何将 Boost 属性树的子树序列化为 XML

c++ - 获取运行文件名:argv[0] vs boost::filesystem::current_path()

c++ - BOOST & GCC,未定义的 boost 引用

c++ - 使用新的内存分配失败

c++ - 避免堆分配的宏?在这种情况下有那么糟糕吗?

返回函数的 C++ 函数,xmemory 和 xrefwrap 中的错误 C2440、C2100

c++ - 打印 boost::graph edge_descriptor

c++ - 在纹理中的 CPU 和 GPU 之间传递数据

c++ - 为什么这个转换不起作用?

xcode - Boost.Python - 即使链接了 lib 文件,也会出现 undefined symbol 错误