C++:'unique vector'数据结构

C++: 'unique vector' data structure

本文关键字:数据结构 vector unique C++      更新时间:2023-10-16

我需要像 std::vector 或 std::list 这样的数据结构,其元素是唯一的。在大多数时候,我会打电话给push_back,有时可能会擦除。当我插入一个已经存在的元素时,我需要通过一些布尔值或异常来通知我。

它应该具有的最重要的属性:插入顺序。每次我迭代它时,它都应该按照插入的顺序返回元素。

我们可以用另一种方式思考:一个保证元素唯一性的队列。但我不想弹出元素,而是想像我们对向量或列表所做的那样迭代它们。

满足我需求的最佳数据结构是什么?

您可以使用

std::set

它将在调用 insert 方法时返回一对pair<iterator,bool>。当元素已存在于集合中时,对中的布尔值为 false(在这种情况下不会添加元素(。

使用具有常规 std::vector 和 std::set 的结构。

推送时,检查该集合是否存在元素。当您需要迭代时,请迭代向量。如果需要从矢量中擦除,也请从集合中擦除。

基本上,使用集合作为旁白,仅用于快速"元素是否存在"检查。

// either make your class a template or use a fixed type of element
class unique_vector
{
    public:
        // implement the various operator you need like operator[]
        // alternatively, consider inheriting from std::vector
    private:
        std::set<T> m_set; // fast lookup for existence of elements
        std::vector<T> m_vector; // vector of elements
};
<</div> div class="answers">我更喜欢使用 std::

unordered_set 将现有元素存储在 std::vector 中,它的查找时间更快,为 O(1(,而 std::set 的查找时间为 O(logn(。

你可以使用 Boost.MultiIndex 来实现这一点:

住在科里鲁

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
using namespace boost::multi_index;
template<typename T>
using unique_list=multi_index_container<
 T,
 indexed_by<
   sequenced<>,
   hashed_unique<identity<T>>
 >
>;
#include <iostream>
int main()
{
  unique_list<int> l;
  auto print=[&](){
    const char* comma="";
    for(const auto& x:l){
      std::cout<<comma<<x;
      comma=",";
    }
    std::cout<<"n";
  };
  l.push_back(0);
  l.push_back(1);
  l.push_back(2);
  l.push_back(0);
  l.push_back(2);
  l.push_back(4);
  print();
}

输出

0,1,2,4