C++ 17 写法上已经很接近 python 了

2016-08-27 20:35:25 +08:00
 taowen

list 和 map

本节例子选自: https://gist.github.com/JeffPaine/6213790

对 python 这样的动态语言最直观的感受就是 list/map 两种数据结构打天下。 php 和 lua 甚至把这两个都合并成一种数据结构了。 毋庸置疑,学会如何使用 list 和 map 是基础中的基础。

for 循环

Python 版本

import unittest

class Test(unittest.TestCase):
    def test_foreach_on_lazy_range(self):
        for i in xrange(6):
            print i ** 2

C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("foreach on lazy range") {
    for(const auto& x : view::ints(0, 6)) {
        std::cout << x * x << std::endl;
    }
}

注意到 const auto& 的写法,这个表示我对这个变量进行只读的使用。只要是能用 const 的地方就用 const ( http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#a-namerconst-immutableacon1-by-default-make-objects-immutable )。 为什么还需要加上 reference ?因为非 reference 的版本默认的语义我要拥有这个变量( make a copy )。而在 for 循环下我们显然是只打算使用这个变量, 而不是去拥有一份。为什么不用指针而用引用?因为指针可空, reference 不可空。

view::ints 是 range-v3 这个库提供的,作用等同于 xrange 。将来 range-v3 会成为标准库的一部分。

foreach

Python 版本

import unittest

class Test(unittest.TestCase):
    def test_foreach_on_list(self):
        colors = ['red', 'green', 'blue', 'yellow']
        for color in colors:
            print color

C++ 版本

#include <catch_with_main.hpp>

using namespace ranges;

TEST_CASE("foreach on list") {
    auto colors = {"red", "green", "blue", "yellow"};
    for(const auto& color : colors) {
        std::cout << color << std::endl;
    }
}

与 python 不同, c++没有所谓的默认的 list 类型。上面的写法是最简洁的写法。 colors 变量的实际类型 根据 GDB 是 std::initializer_list<const char*>。只有 begin , end , size 几个函数。实际上类似于 python 的 tuple 。 考虑到 python 的 list 类型是 mutable 的,所以更合适的实现是 std::vector 。

#include <catch_with_main.hpp>

using namespace ranges;

TEST_CASE("foreach on vector") {
    auto colors = std::vector<const char*>{"red", "green", "blue", "yellow"};
    for(const auto& color : colors) {
        std::cout << color << std::endl;
    }
}

foreach 倒序

Python 版本

import unittest

class Test(unittest.TestCase):

    def test_foreach_reversed(self):
        colors = ['red', 'green', 'blue', 'yellow']
        for color in reversed(colors):
            print(color)

C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("foreach reversed") {
    auto colors = std::vector<const char*>{"red", "green", "blue", "yellow"};
    for(const auto& color : colors | view::reverse) {
        std::cout << color << std::endl;
    }
}

这里使用了 range-v3 的 view 组合,类似 unix pipe 的语法。

foreach 带下标

Python 版本

import unittest

class Test(unittest.TestCase):
    def test_foreach_with_index(self):
        colors = ['red', 'green', 'blue', 'yellow']
        for i, color in enumerate(colors):
            print(i, color)

C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("foreach with index") {
    auto colors = std::vector<const char*>{"red", "green", "blue", "yellow"};
    for(const auto& [i, color] : view::zip(view::iota(0), colors)) {
        std::cout << i << " " << color << std::endl;
    }
}

view::iota这个的意思是产生一个从 n 开始的逐个加一的 view ,类似 python 里的 generator 。然后 zip 是把两个 view 逐个对应起来合并成一个 pair 的 view 。 然后const auto& [i, color]是 c++ 17 的 structured bindings 的写法,和 python 解开 tuple 里的元素的做法是如出一辙的。

zip

下面这个例子可以看得更清楚。 Python 版本

import unittest
import itertools

class Test(unittest.TestCase):
    def test_zip(self):
        names = ['raymond', 'rachel', 'matthew']
        colors = ['red', 'green', 'blue', 'yellow']
        for name, color in itertools.izip(names, colors):
            print(name, color)

izip 返回的是 generator 。 zip 返回都是 list 。 C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("zip") {
    auto names = std::vector<const char*>{"raymond", "rachel", "matthew"};
    auto colors = std::vector<const char*>{"red", "green", "blue", "yellow"};
    for(const auto& [name, color] : view::zip(names, colors)) {
        std::cout << name << " " << color << std::endl;
    }
}

sorted

Python 版本

import unittest

class Test(unittest.TestCase):
    def test_sort(self):
        colors = ['red', 'green', 'blue', 'yellow']
        for color in sorted(colors):
            print(color)

C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("sort") {
    auto colors = std::vector<std::string>{"red", "green", "blue", "yellow"};
    colors |= action::sort;
    for(const auto& color : colors) {
        std::cout << color << std::endl;
    }
}

这个例子里const char*换成了std::string,因为只有字符串类型才知道怎么比较,才能排序。 action::sort与 view 不同,它返回的是具体的 container ,而不再是 view 了。

如果要倒过来排序,再 python 中是这样的

import unittest

class Test(unittest.TestCase):
    def test_sort_reverse(self):
        colors = ['red', 'green', 'blue', 'yellow']
        for color in sorted(colors, reverse=True):
            print(color)

C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("sort reverse") {
    auto colors = std::vector<std::string>{"red", "green", "blue", "yellow"};
    colors |= action::sort(std::greater<std::string>());
    for(const auto& color : colors) {
        std::cout << color << std::endl;
    }
}

Python 还支持指定属性去排序

import unittest

class Test(unittest.TestCase):

    def test_custom_sort(self):
        colors = ['red', 'green', 'blue', 'yellow']
        for color in sorted(colors, key=lambda e: len(e)):
            print(color)

C++ 版本

#include <catch_with_main.hpp>
#include <range/v3/all.hpp>

using namespace ranges;

TEST_CASE("custom sort") {
    auto colors = std::vector<std::string>{"red", "green", "blue", "yellow"};
    colors |= action::sort(std::less<std::string>(), [](const auto&e) {
        return e.size();
    });
    for(const auto& color : colors) {
        std::cout << color << std::endl;
    }
}

sort的第一个参数是 comparator ,第二个参数是 projector 。这里我们使用了一个 lambda 表达式,从字符串上取得其长度值,用长度去排序。


需要的编译环境

参见: https://taowen.gitbooks.io/modern-cpp-howto/content/unit-testing/chapter.html

37208 次点击
所在节点    Python
77 条回复
kindjeff
2016-08-27 20:38:41 +08:00
仿佛自己没有学过 C++…………
taowen
2016-08-27 20:40:25 +08:00
@kindjeff 2000 年的时候学的 c++,十六年之后重新再学一门新语言,只是名字还是叫 c++。有了 lambda , auto , structured bindings 之后, c++已经是一门适合制造语法糖的语言了。
yangff
2016-08-27 20:40:34 +08:00
第一个 Case 如果都是 int 的话…… 直接用 int 比较合算……
hinkal
2016-08-27 20:55:13 +08:00
你们都在模仿 python 系列,《 java8 写法上已经很接近 python 了》
int64ago
2016-08-27 20:57:51 +08:00
所以的你发的节点是 Python ...

几年没看 C++ 发现已经不认识了
qweweretrt515
2016-08-27 21:07:17 +08:00
啊哈 放佛学过 c++
alexapollo
2016-08-27 21:25:30 +08:00
之前写过一个 C++ Python 化的库,语法比这个更简洁,但介入的点比较少。
janxin
2016-08-27 21:26:09 +08:00
我们来谈谈内存管理吧
shijingshijing
2016-08-27 21:29:49 +08:00
强迫症表示只喜欢 C++这种括号反括号的代码方式~
sc3263
2016-08-27 21:33:39 +08:00
@janxin 智能指针大法好~
k9982874
2016-08-27 21:35:37 +08:00
auto 这种语法糖真是蛋疼。不敢想象一个大型项目全是 auto 该多么欢乐。
neosfung
2016-08-27 21:36:54 +08:00
我现在还只停留在 c++ 0x 上面。。。
zhuangzhuang1988
2016-08-27 21:36:57 +08:00
我那个擦。。
hitmanx
2016-08-27 21:48:13 +08:00
有些还能忍忍,比如 range-based for loop,可能也是习惯 c++11 了。
但是这种 pipeline style 看着实在太怪异了:
1) for(const auto& color : colors | view::reverse)
2) colors |= action::sort;

本来很简单很纯粹的“或”,现在看来也得分情况去理解了,很讨厌这种二义性
missdeer
2016-08-27 21:50:33 +08:00
大部分在 C++11 都实现了,那是 5 年前的东西了
missdeer
2016-08-27 21:53:17 +08:00
@hitmanx 早年的各种 C++ practice 里都说过,不要乱用操作符重载,特别是重载出跟惯用含义不同的行为来,叹气
misaka19000
2016-08-27 21:56:12 +08:00
Python 这种算不算模仿 Lisp 呢?

《黑客与画家》里面就说过,现代的各种编程语言都是在慢慢的模仿 Lisp 的写法,并且这种趋势还在慢慢的增强,一种语言模仿 Lisp 的部分越多就越强大
regeditms
2016-08-27 22:08:28 +08:00
c++17 现在什么编译器才支持哈? vs2015 ?
kingoldlucky
2016-08-27 22:08:57 +08:00
算了 还是看看纯 C 就好了
billlee
2016-08-27 22:10:16 +08:00
int 类型还用常量引用不是蛋疼吗。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/302179

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX