Python的List和C++的Vector的对比
作者:糖果
简单的对比了一下Python的List和C的Vector操作,用Python代替C的
注释。
另外推荐一个在线的编译器,codepad.org。
1.定义数据
Python
candyList = ["Red Candy", "Green Candy", "Blue Candy", "Yello Candy"]
C++
vector<string> candyList;
2.增加元素
Python
candyList.append("Append Candy")
candyList.insert(1, "Insert Candy")
candyList.extend(["Extend Candy Front", "Extend Candy Background"])
candyList = candyList + ["Add Candy Front", "Add Candy Background"]
C++
candyList.push_back("Red Candy");
candyList.push_back("Green Candy");
candyList.push_back("Blue Candy");
candyList.push_back("Yellow Candy");
3.删除元素
Python
candyList.pop()
candyList.remove("Insert Candy")
C++
candyList.pop_back();
candyList.erase(candyList.begin(), candyList.begin()+1);
4.查找
Python
candy = candyList[3]
candy = candyList[-1]
candy = candyList[-3]
C++
candyList.at(0);
vector<string>::iterator it = candyList.begin() + 1;
字典
5.定义
candyMap = {"Red":"R", "Green":"G", "Blue":"B"}
map = ["%s=%s" % (k,v) for k,v in candyMap.items()]
color = candyMap["Red"]
candyMap.keys()
candyMap.values()
candyMap.items()
6.连接分割
str = ";".join(["%s=%s" % (k,v) for k,v in candyMap.items()])
candyList = str.split(";")
7.过滤器
count()是查找元素在list中的位置下标值。
[elem for elem in candyList if candyList.count(elem) == 1]
8.遍历
Python
len(candyList)
list = [elem for elem in candyList]
list = [elem for elem in candyList if len(elem) > 9]
candyList = ["red", "green", "blue"]
for elem in range(len(candyList)):
print candyList[elem]
C++
for (int i=0; i < candyList.size(); i++) {
cout << candyList.at(i) << endl;
}
for (vector<string>::iterator it = candyList.begin(); it != candyList.end(); ++it) {
cout << *it << endl;
}
#include<iostream>
#include<vector>
using namespace std;
int main(int argc, char** argv) {
vector<string> candyList;
candyList.push_back("Green Candy");
candyList.push_back("Blue Candy");
candyList.push_back("Yellow Candy");
for (int i=0; i < candyList.size(); i++) {
cout << candyList.at(i) << endl;
}
vector<string>::iterator it;
candyList.erase(candyList.begin(), candyList.begin()+1);
candyList.pop_back();
cout << "###SPLIT###" << endl;
for (vector<string>::iterator it = candyList.begin(); it != candyList.end(); ++it) {
cout << *it << endl;
}
}
[后记]
Python里的join和split很好用,一般的算法原型,完全可以先用python写出来,然后再改成C++,为什么这么干?
注释:个人劳动成果,转载使用请注明本文作者及出处链接,谢谢合作!