我师得见燃灯佛,多劫曾为忍辱仙。
--永嘉禅师《证道歌》
(注:由于本文有很多表格,而表格中有代码,手机观看可能排版不佳,建议电脑观看。)
本文整理一些常见的数据结构以及其常用的一些操作,这些操作是在刷题的时候经常使用的操作。
整体结构如下,对常见的数据结构的基本操作做了整理,语言基于C++
,Python
和Java
。
数组字符串链表栈队列mapset总结
下面是这些数据结构在各个语言中经常用什么工具来实现的整理。
C++ | Java | Python | |
---|---|---|---|
数组 | vector | ArrayList (来自List ) | List |
字符串 | string 类 | String 类 | string |
链表 | list (双向链表) | LinkedList (来自List ,双向链表) | 无官方实现 |
栈 | stack 容器适配器 | Stack 类(Vector 的一个子类) | deque (来自collections 库)也可以用 List 模拟 |
队列 | queue 容器适配器 | 无官方实现(可用ArrayList 模拟) | deque (来自collections 库)也可以用 List 模拟 |
map | map 容器 | Map (集合框架) | 字典 |
set | set 容器 | Set (集合框架) | set (集合) |
下面逐一整理。
数组
数组基本操作 | ||
---|---|---|
初始化 | Python | l1 = []; l2 = [1,2] l3=5*[0] |
C++ | vector a; //声明vector a(3); //声明数组并且长度为3,默认为0vector a(3,1); //声明数组长度为3,默认为1vector a = {1,2}; //以初始化列表进行初始化 | |
Java | List l1 = new ArrayList(); //声明初始长度为10List l2 = new ArrayList<>(Arrays.asList("a","b","c")); //初始化List l3 = new ArrayList(Collections.nCopies(5, new Integer(0))); // 长度为5,初值为0 | |
追加值 | Python | l1.append(1) # 尾部追加l1.append([7,8,9]) # 尾部追加一个listl1+[1,2,3] # 用加号拼接 |
C++ | a.push_back(3); //尾部追加v1.insert(v1.end(), v2.begin(), v2.end()); // 把v2加到v1末尾 | |
Java | l1.add("Hello"); l1.addAll(l2); // 尾部追加一个List | |
长度 | Python | len(l2) |
C++ | a.size() | |
Java | l1.size() | |
访问值 | Python | l1[0] |
C++ | a[0] | |
Java | l1.get(0) | |
更改元素值 | Python | l2[1] = 2 |
C++ | a[1] = 2 | |
Java | l3.set(0,100); // 第0个元素设置修改为100 | |
删除首部和尾部的元素值 | Python | l1.pop(0) l1.pop() # 弹出并可以返回 |
C++ | a.erase (a.begin()) ;a.pop_back(); | |
Java | l3.remove(0); l3.remove(l3.size()-1); //可返回 | |
排序 | Python | l1.sort() |
C++ | sort(a.begin(),a.end()); | |
Java | import static java.util.Collections.sort; sort(l3); | |
深拷贝 | Python | import copy l_c = copy.deepcopy(l1) |
C++ | vector l1 = {1,2,3}; vector l1_c2(l1.size()); //注意要提前申请内存vector l1_c3; vector l1_c1(l1); // 调用拷贝构造copy(l1.begin(),l1.end(),l1_c2.begin()); //使用copy函数l1_c3.assign(l1.begin(), l1.end()); // 使用assign成员函数 | |
Java | ArrayList l0= new ArrayList<>(Arrays.asList(4,5,6)); List mycopy1=new ArrayList(); mycopy1=(ArrayList) l0.clone(); // 使用cloneArrayList mycopy2=new ArrayList(Arrays.asList(new Integer[l0.size()])); Collections.copy(mycopy2, l0); // 使用copy | |
查找 | Python | l1.index(10) |
C++ | find(a.begin(),a.end(),10); //在a中的从a.begin()(包括它)到a.end()(不包括它)的元素中查找10,若存在返回其在向量中的位置 | |
Java | l3.indexOf(10) | |
求最值 | Python | max(l1) min(l1) |
C++ | *max_element(a.begin(),a.end()); *min_element(v.begin(),v.end()); | |
Java | Collections.max(l1) Collections.min(l1) | |
遍历 | Python | for i in range(len(l1)) for item in l1 |
C++ | for(std::vector::iterator it = v.begin(); it != v.end(); ++it) { /* std::cout << *it; ... */ } for(std::vector::size_type i = 0; i != v.size(); i++) { /* std::cout << v[i]; ... */ } for(auto const& value: a) { /* std::cout << value; ... */} // C++ 11 | |
Java | List l2 = new ArrayList<>(Arrays.asList("ac","b","css")); Iterator iterator = l2.iterator(); while(iterator.hasNext()) { String next = iterator.next(); System.out.println("迭代器====>"+next); } | |
新建 rows*cols的 二维数组 | Python | list_2d = [[0 for col in range(cols)] for row in range(rows)] |
C++ | int rows = 5; int cols = 3; vector> array(rows); for (int i = 0; i < array.size(); i++) {array[i].resize(cols);} | |
Java | ArrayList > list=new ArrayList >(); int rows = 5; int cols = 3; for(int i =0;i | |
关于数组操作较多,这里主要参考了下面的资料:
https://blog.csdn.net/fanyun_01/article/details/56842637?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://www.jianshu.com/p/63b01b6379fb
https://techlog.cn/article/list/10182995
https://www.runoob.com/python3/python3-list.html
https://blog.csdn.net/hust_bochu_xuchao/article/details/72850862?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://blog.csdn.net/zhouzhenhe2008/article/details/74936765?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
http://www.cplusplus.com/reference/algorithm/copy/?kw=copy
https://blog.csdn.net/liyuming0000/article/details/49488607/
https://blog.csdn.net/weixin_40883446/article/details/80812882?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://blog.csdn.net/a819825294/article/details/52088732?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://blog.csdn.net/MARS116048/article/details/104207861?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
字符串
再整理一下关于字符串的相关操作。
字符串基本操作 | ||
---|---|---|
初始化和访问 | Python | s1 = 'Hello World!' s1[0] |
C++ | string s1 = "abc"; string s2(s1); s1[2] | |
Java | String s1 = "adf"; String s2 = new String("dc"); s1.charAt(2); | |
拼接 | Python | s1 + 'Runoob!' |
C++ | s1.append("123") s1 += s2; | |
Java | s1+s2; s1.concat(s2); | |
长度 | Python | len(s1) |
C++ | s1.length(); | |
Java | s1.length(); | |
字符串与数组转化 | Python | list=[] list=[i for i in s1] l = ["dsf","sd","cds"] "".join(l1) |
C++ | vector v_s; string::const_iterator sit = s1.begin(); while(sit != s1.end()) {v_s.push_back(*sit); sit++;} vector::iterator it = v_s.begin(); string s; while(it != v_s.end()) { s += (*it); it++; } | |
Java | String s5 = "dvdv" ;List l_str = new ArrayList<>(); for (int i = 0; i < s5.length(); i++){ char item = s5.charAt(i); l_str.add(item);} String s6 = ""; for(int i =0;i{ | |
分割 | Python | url = "http://www.baidu.com/python/image/123456.jpg" url.split(".") |
C++ | 见下面的补充 | |
Java | String str = "小学,初中,高中,大专,本科,研究生,博士"; String[] buff = str.split(","); | |
查找 | Python | s1.find('a') # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0 |
C++ | s1.find("day") //若查找 find() 函数和其他函数没有搜索到期望的字符(或子串),则返回 npos;若搜索成功,则返回搜索到的第 1 个字符或子串的位置。其中,npos 是一个无符号整数值,初始值为 -1。当搜索失败时, npos 表示“没有找到(not found)”或“所有剩佘字符”。 | |
Java | String strOrig = "Google Runoob Taobao"; int intIndex = strOrig.indexOf("Runoob"); //如果存在返回字符串出现的位置(第一位为0),如果不存在返回 -1: | |
比较 | Python | "dfd">"dfsgvds" |
C++ | string A ("aBcdef"); string B ("AbcdEf"); int m=A.compare (B); //完整的A和B的比较A < "Li" | |
Java | String str1 = "Strings"; String str2 = "Strings"; int result = str1.compareTo( str2 ); | |
切片 | Python | s1[1:3] |
C++ | s1.substr(5,7) //从索引5开始7个字节 | |
Java | Str.substring(4, 10) // 左闭右开 | |
深复制 | Python | s_c = copy.deepcopy(s1) |
C++ | string s1 = "abc"; string s2(s1); // 拷贝构造 | |
Java | String str3 = str1; | |
判断是否包含 | Python | "a" in s1 |
C++ | s1.find("d") | |
Java | s1.contains("g") | |
替换 | Python | s1.replace("is", "was") |
C++ | s1.replace(0,3,"hello") //即将索引0开始的3个字符替换成"hello" | |
Java | s1.replace('o', 'T') | |
获取索引 | Python | for s in s1: |
C++ | string::iterator its = s.begin(); while(its != s.end()){ cout << *its< | |
Java | for (int i = 0; i < s1.length(); i++) { char item = s1.charAt(i);} | |
主要参考了:
https://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html
https://www.cnblogs.com/X-Do-Better/p/8628492.html
补充C++中的字符串的split
方法,目前没有标准函数,可参考下面的:
https://www.zhihu.com/question/36642771
https://www.cnblogs.com/dfcao/p/cpp-FAQ-split.html
1// 字符串分割
2#include
3#include
4#include
5#include
6#include
7
8using namespace std;
9int main(){
10 string s3 = "a#bbvdf#cd##";
11 char *token = strtok(const_cast<char *>(s3.data()) , "#");
12 // 注意 strtok的第一个参数是char *,而不是const char *, 所以要用const_cast把const去掉
13 while (token != NULL) {
14 cout <" ";
15 token = strtok(NULL, "#");
16 }
17
18 cout <endl;
19 }
关于const_cast
,看https://blog.csdn.net/geeeeeeee/article/details/3427920。
链表
由于Python
中没有链表的标准库,这里只整理C++
和Java
的。
链表的基本操作 | ||
---|---|---|
初始化 | C++ | list words; list values(50, 3.14); // 生成了一个具有 50 个 double 型值的列表,并且每一个值都等于 3.14 |
Java | List linkedList = new LinkedList(); | |
添加元素 | C++ | words.push_front("Ian"); words.push_back("Kitty"); |
Java | linkedList.add("my"); linkedList.add("name"); | |
遍历 | C++ | auto lt = l.begin(); while (lt != l.end()) { cout << *lt < |
Java | //迭代器迭代Iterator iterator = linkedList.iterator(); while(iterator.hasNext()){ String next = iterator.next(); System.out.println(next); } //for循环迭代集合 for(String str:linkedList){ System.out.println(str);} | |
链表长度 | C++ | l.size(); |
Java | int size = linkedList.size(); | |
其他的一些操作,如链表反转,链表排序,合并链表等,常作为面试题,不宜用库函数,暂不整理。
栈
栈的基本操作 | ||
---|---|---|
创建和初始化 | Python | stack = [] |
C++ | std::stack<:string> st; | |
Java | Stack st = new Stack(); | |
入栈 | Python | stack.append(1) |
C++ | st.push(item); //将item压入栈 | |
Java | st.push(new Integer(1)); | |
出栈 | Python | stack.pop() # 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
C++ | st.pop();// 删除栈顶的元素,但不会返回s.top(); //返回栈顶的元素,但不会删除 | |
Java | st.pop() //移除堆栈顶部的对象,并作为此函数的值返回该对象。st.peek() //查看堆栈顶部的对象,但不从堆栈中移除它。 | |
判断栈空 | Python | not stack |
C++ | s.empty(); //检查栈是否为空,如果为空返回true,否则返回false | |
Java | st.empty() | |
队列
队列基本操作 | ||
---|---|---|
创建和初始化 | Python | queue = [] |
C++ | std::queue<:string> q; | |
Java | List list = new ArrayList(); | |
入队 | Python | queue.append(1) |
C++ | q.push("dsa") | |
Java | list.add("Hello"); list.add("world"); | |
出队 | Python | queue.pop(0) |
C++ | q.pop() //删除 queue 中的第一个元素q.front() //返回 queue 中第一个元素的引用 | |
Java | list.remove(0); String element = list.get(0); | |
判断队列是否为空 | Python | not queue |
C++ | q.empty() | |
Java | boolean isEmpty = list.isEmpty(); | |
map
map基本操作 | ||
---|---|---|
创建和初始化 | Python | d = {key1 : value1, key2 : value2 } dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} |
C++ | map ID_Name = {{ 2015, "Jim" }, { 2016, "Tom" }, { 2017, "Bob" } }; // C++ 11 | |
Java | Map m1 = new HashMap(); | |
插入键值对 | Python | dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # 更新Age dict['School'] = "菜鸟教程" # 添加信息 |
C++ | // 如果已经存在键值2015,则会作赋值修改操作,如果没有则插入ID_Name[2015] = "Tom"; ID_Name.insert(std::pair(100, "ds")); // 插入单个键值对ID_Name.insert({ { 2015, "Jim" }, { 2016, "Tom" } }) // 插入多个键值对 | |
Java | m1.put("Zara", "8"); m1.put("Mahnaz", "31"); | |
取值 | Python | dict["Name"] |
C++ | ID_Name[2015] | |
Java | m1.get("Zara") | |
判断某个key 是否在当前的map的keys中 | Python | 'Age' in dict |
C++ | auto mit = ID_Name.find(2015); if (mit != mymap.end()){cout << "map中存在该key"<//关键字查询,找到则返回指向该关键字的迭代器,否则返回指向end的迭代器 | |
Java | m1.containsKey("Zara") | |
遍历 | Python | for key,value in dict.items(): |
C++ | auto idt = ID_Name.begin(); while(idt != ID_Name.end()){ cout << "key为:" << idt->first <second< | |
Java | Map map = new HashMap(); for(String key : map.keySet()) {String value = map.get(key); System.out.println(key+":"+value); } | |
map大小 | Python | len(dict) |
C++ | ID_Name.size() | |
Java | map.size() | |
map是否为空 | Python | not dict |
C++ | ID_Name.empty() | |
Java | map.isEmpty() | |
这里主要参考了下面的资料:
https://blog.csdn.net/shuzfan/article/details/53115922?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
http://c.biancheng.net/view/488.html
https://www.runoob.com/java/java-map-interface.html
https://www.runoob.com/python3/python3-dictionary.html
https://www.cnblogs.com/damoblog/p/9124937.html
set
set基本操作 | ||
---|---|---|
创建和初始化 | Python | basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana’} //打印出来会发现会被去重a = set('abracadabra') // 会被去重thisset = set(("Google", "Runoob", "Taobao")) |
C++ | set s; | |
Java | Set hashSet = new HashSet(); | |
添加值 | Python | thisset.add("Facebook") |
C++ | s.insert(1); s.insert(2); | |
Java | hashSet.add("my"); hashSet.add("name"); | |
判断元素 是否在 集合中存在 | Python | "Runoob" in thisset |
C++ | std::set words {"one", "two","three", "four","five"}; auto iter = words.find ("one") //会返回一个和参数匹配的元素的迭代器。如果对象不在 set 中,会返回一个结束迭代器。 | |
Java | hashSet.contains("my"); | |
遍历集合 | Python | for ss in thisset |
C++ | auto seit = s.begin(); while (seit != s.end()) { cout < | |
Java | for(String str:hashSet){} | |
集合大小 | Python | len(thisset) |
C++ | s.size() | |
Java | hashSet.size() | |
判断集合是否为空 | Python | not thisset |
C++ | s.empty() | |
Java | boolean isEmpty = hashSet.isEmpty(); | |
这里主要参考了下面的资料:
https://blog.csdn.net/sunshinewave/article/details/8068326?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://www.jianshu.com/p/d6cff3517688
https://www.runoob.com/python3/python3-set.html
总结
这里对各个数据结构的使用做了最基本的整理,涵盖了一些常用的操作,其中数组,字符串和字典的使用比较多,相关操作也更多一些。
如果需要深入使用,还需要另外再看。
如有问题,欢迎拍砖。
北交大统计学硕士
会点Python/R,cpp在路上
机器学习工程师/数据分析师修炼中
主攻广告和推荐方向
也爱看点文学、心理和宗教的东西
无可无不可,天下皆通途
长按扫码关注