compare_language_difference

比较C++和Python数据结构和函数的区别

  1. 自动类型
  • 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;
    }
    
  1. 批类型转换(在了解构造函数的前提下,尽量使用构造函数)

    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 )
  2. 声明变量和初始化、截取、替换、追加

    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"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zedjay_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值