学习python以后,对比之前的学得c++,发现现代c++(c++11 and later)的使用越来越pythonic,auto的使用几乎是最常见的。
原文
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);