包含最大100个数字且易于查找最小数字的数据结构

时间:2019-04-01 15:12:23

标签: c++

我需要在某些数据结构中保存(0,100)之间的ID,不会超过100个ID,并且我需要一种简便快捷的方法来在数据结构中查找最小值,并需要一种简便的方法来插入和删除一个数据结构中的特定数字,例如,如果是列表, 因此list.append(1)list.append(2)list.append(99)list.remove(2) a = list.min()。 我对c ++有点陌生,并且不确定哪种数据结构可以有效地支持它。

3 个答案:

答案 0 :(得分:3)

您可以使用std::set,通常将其实现为二进制搜索树。

它的insert()erase()find()方法的大小是对数的,但是如果给出提示,则可以做得更好。对数复杂度称为Java TreeSet。

我认为您应该对std::lower_bound(将迭代器返回下限)和std::upper_bound(对迭代器返回上限)感兴趣。

答案 1 :(得分:0)

对于此请求,存在一个特殊的数据结构:heap:)

std::vector<std::uint32_t> vInts = { 25,10,35,30,5,15 };

//converts to min heap
std::make_heap(vInts.begin(), vInts.end(), std::greater<std::uint32_t>());

//5
std::cout << *vInts.begin() << std::endl;

//pop 5
std::pop_heap(vInts.begin(), vInts.end(), std::greater<std::uint32_t>());
vInts.pop_back();
std::cout << *vInts.begin() << std::endl; //10

//pop 10
std::pop_heap(vInts.begin(), vInts.end(), std::greater<std::uint32_t>());
vInts.pop_back();

//push 20. min will be still 15
vInts.push_back(20);
std::push_heap(vInts.begin(), vInts.end(), std::greater<std::uint32_t>());
std::cout << *vInts.begin() << std::endl; //15

//pop 15
std::pop_heap(vInts.begin(), vInts.end(), std::greater<std::uint32_t>());
vInts.pop_back();

std::cout << *vInts.begin() << std::endl; //20

答案 2 :(得分:0)

简单:

std::vector<int> container;
container.reserve(100);
// ... put stuff in container ...
const auto min_elem =
    std::min_element(container.begin(), 
        container.end());