比较C++和Python数据结构和函数的区别
- 自动类型
- python
a = [1, 2, 3] type(a) # <class 'list'> type([4,5,6]) # <class 'list'>
- C++
auto a = {1, 2, 3}; //what's a's type? vector<int> b = a; //ok //a = b; //error //{1, 2, 3} 其实是 std::initializer_list<int> 类型 //thus list<int> a = {1, 2, 3}; deque<int> a = {1, 2, 3}; set<int> a = {1, 2, 3}; //其实: T a = {1, 2, 3}; <==> T a = T({1, 2, 3}); auto f = vector<int>{1, 2, 3};//没必要 vector<int> g{1, 2, 3}; //better // pair<int, string> foo(); // auto h = foo(); //ok unordered_map<string, int> m{{"sanjay", 1}, {"leetcode", 2}}; //unordered_map 是 hash for(const pair<string const, int> &p: m){ cout << p.first << "->" << p.second << endl; } //上面for在c++11中可以用auto for(auto const &p: m){ cout << p.first << "->" << p.second << endl; } //如果用迭代器的话,可以定义别名 typedef unordered_map<string, int>::const_iterator CIT; for(CIT it = m.cbegin(); it != m.cend(); ++it){ cout << it->first << "->" << it->second << endl; } //在cpp11中可以用auto for(auto it = m.cbegin(); it != m.cend(); ++it){ cout << it->first << "->" << it->second << endl; }
-
批类型转换(在了解构造函数的前提下,尽量使用构造函数)
C++ Python vector a{2, 1, 2, 3}; set b(begin(a), end(a)); a = [2, 1, 2, 3] b = set(a) set a{1, 2, 3}; vector b(begin(a), end(a)); a = set([1, 2, 3]) b = list(a) int x = 12345; string s = std::to_string(x); x = 12345 s = str(x) string str{“12345”}; int x = std::stoi(str); s = “12345” x = int(s) char c = ‘9’; int x = c - ‘0’; c = ‘9’ x = ord( c ) - ord(‘0’) 或者x = int( c ) -
声明变量和初始化、截取、替换、追加
C++ Python string s; //s = “”;
string s = “sanjay”; //先用char数组临时初始化一个string,然后再拷贝给s
string s{“sanjay”};
string s(5, ‘1’); // “11111”s = ""
s = str()
s = "sanjay"
s = ‘’.join([‘1’]*5)string s{“012345”};
s.substr(3); // "345"
s.substr(3,2); // “34”s = "012345"
s[3:] # "345"
s[3:5] #“34”s[1]; // '1’
s[1] = ‘h’; // “0h2345”# python的str是不可变的,不能用下标来改变str
l = list(s)
l[1] = 'h’
s = ‘’.join(l)
或者
s = s[0:1] + ‘h’ + s[2:] # 效率比较低s += " hello"; //“012345 hello” s += " hello"