C++ has become more pythonic

学习python以后,对比之前的学得c++,发现现代c++(c++11 and later)的使用越来越pythonicauto的使用几乎是最常见的。


原文

Literals

  • binary Literals
static const int primes = 0b101010101010
  • raw string
path = r'c:\...\...'
const char *path = R"(c:\...\...)"  

Range-Based For Loops

  for x in myList:
  for(int x: myList){}

Auto

x = 'hello world'
print(x)

auto x = "hello world";
std::cout << x;

Tuple

myTuple = (1,2,3)
print(myTuple[0])

auto myTuple = std::make_tuple(1,2,3);
cout << std::get<0>(myTuple);
x,y,z  = myTuple

std::tie(x,y,z) = myTuple //std::tie std::make_tuple

Uniform initalization

myList = [4,5,6]
myList.append(7);

auto myList = vector<int>{4, 5, 6};
myList.push_back(7);
myDict = {5: "foo", 6: "bar"}
print(myDict[5])

auto myDict = std::unordered_map<int, const char *>{{5: "foo"}, {6: "bar"};
cout << myDict[5];

Lambda expressions

myList.sort(key= lambda x:abs(x))

std::sort(myList.begin(), myList.end(), [](int x, int y){return x > y;});
// std::map<int, int, std::greater<int>> m { {-1, 77}, {0, 42}, {1, 84} };
def adder(amount):
    return lambda x:x+amount
print(adder(5)(6)) # amount = 5, x = 6

auto adder(int amount){
  return [=](int x){return x + amount;};
} 
std::cout << adder(5)(6)

Standard Algorithm

retult = filter(lambda x: x >= 0, myList)# 底层实现参考c++ impl

auto result = std::vector<int>{};
std::copy_if(myList.begin(), myList.end(), std::back_inserter(result), [](int x){return x >= 0;}); //开空间然后复制

Parameter packs

def foo(*args):
    return tuple(args)
triple = foo(5,6,7)
# args = (5,6,7) *args = 5 6 7


template<typename... T>auto foo(T&&... args){
  return std::make_tuple(args...);
}

auto triple = foo(5,6,7);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值