STL --最常见的容器使用要点
2013-08-08 00:30
405 查看
如果只是要找到STL某个容器的用法, 可以参考msdn和C++ Library Reference,msdn 上面的知识点应该是最新的,C++ Library Reference虽古老但是很多经典的容器使用有很多例子,二者可以相互参考,另外,本博客中提到的一些链接也是学习的好材料。
另有一篇文章总结很简洁,可以参考:烂笔头的专栏
一、vector
set中的元素默认是升序排列的,按照msdn中的描述来说是这样的:
Sorted, because its elements are ordered by key values within the container in accordance with a specified comparison function
Elements follow a strict weak ordering at all times.
四、list
另有一篇文章总结很简洁,可以参考:烂笔头的专栏
一、vector
dfsf
二、map dfdsf
三、set总览:
set中每个元素都是不同的。set中的元素默认是升序排列的,按照msdn中的描述来说是这样的:
Sorted, because its elements are ordered by key values within the container in accordance with a specified comparison function
Elements follow a strict weak ordering at all times.
应用注意:
set底层实现是红黑树,红黑树是理想平衡二叉查找树的一种统计学上的最优实现,具体原理参见wiki,需要知道的是树上所做的插入删除查找操作都是logN的复杂度,所以效率很高
如果要改变一个set中某个位置的值,不是直接改变,而是先删除再插入
常用函数说明:
迭代函数:begin() end() rbegin() rend()
查找函数:
删除函数:erase,它有好几种调用形式
count函数:因为set不允许重复元素,所以count为1表示存在,count为0表示不存在
使用示例:longest consecutive sequence—leetcode problem
set底层实现是红黑树,红黑树是理想平衡二叉查找树的一种统计学上的最优实现,具体原理参见wiki,需要知道的是树上所做的插入删除查找操作都是logN的复杂度,所以效率很高
如果要改变一个set中某个位置的值,不是直接改变,而是先删除再插入
常用函数说明:
迭代函数:begin() end() rbegin() rend()
查找函数:
iterator find( const Key& _Key );
返回的是迭代器,如果找不到,返回s.end()
删除函数:erase,它有好几种调用形式
iterator erase( iterator _Where ); iterator erase( iterator _First, iterator _Last ); size_type erase( const key_type& _Key );
count函数:因为set不允许重复元素,所以count为1表示存在,count为0表示不存在
使用示例:longest consecutive sequence—leetcode problem
[code]class Solution { public: int longestConsecutive(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if(num.size()==0){ return 0; } set<int> s; for(int i = 0; i<num.size(); i++){ s.insert(num[i]); } int len = 0; // If not erase, it is O(n^2). Smart. for(int i = 0; i<num.size(); i++){ int v = num[i]; if(s.find(v)!=s.end()){ s.erase(v); int count = 1; int u = v; while(s.find(--u)!=s.end()){ s.erase(u); count++; } u = v; while(s.find(++u)!=s.end()){ s.erase(u); count++; } if(count>len){ len = count; } } } return len; } }; [/code] |
四、list
相关文章推荐
- STL(6)-容器的共通能力,各个容器的使用时机,常见算法用法介绍
- 常见的STL容器及其使用场景
- C++ STL相关知识及容器使用要点
- 使用boost库serialize序列化map等STL容器的最常见错误——error C2039
- 几个常见stl容器的常用功能及使用方法
- STL中map容器使用自定义key类型报错详解
- CPP(二)再接再厉:STL容器类的使用
- C++STL容器使用经验总结
- STL - 各个容器的使用时机
- 使用stl标准容器,遍历容器时出现 iterators incompatible 错误的其中两种原因
- STL库中几种容器及迭代器的使用
- 使用STL中的list容器实现单链表的操作
- 使用STL的hash_map要点
- 关于stl中常见容器的复杂度分析
- STL--> list 双向循环链表容器 接口使用及介绍。 模拟实现 STL list容器
- C++STL容器使用经验总结
- 迭代器失效(1)-小心使用STL容器的erase()
- STL容器Maps和Multimaps使用
- 多年来,STL容器的使用总结!
- 使用STL的vector容器类