C++:'unique vector'数据结构
C++: 'unique vector' data structure
我需要像 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
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- 查找索引数据结构,例如`sTD :: vector`(非数组)
- C++:'unique vector'数据结构
- Python 数据结构:map<string、vector<int>>
- 向量的向量作为有效的数据结构;std::vector<std::vector>的替代品<someType>
- std::vector或其他数据结构中不同类型的对象
- 修改 std::vector 的底层数据结构不会改变其大小
- 如何使用std::vector等动态数据结构并防止分页