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

37210 次点击
所在节点    Python
77 条回复
skydiver
2016-08-27 22:10:36 +08:00
应该用右值引用吧 auto&&
zhenyan
2016-08-27 22:11:59 +08:00
@regeditms VS2020 还差不多
jyf007
2016-08-27 22:13:35 +08:00
向着 lisp 和 smalltalk 前进
taowen
2016-08-27 22:15:33 +08:00
@regeditms clang++ 4.0 应该是目前唯一支持 structured bindings 的编译器
wodesuck
2016-08-27 22:22:46 +08:00
可以 这代码很骚
不过主要骚的地方都是 range-v3 吧, c++17 的特性似乎就只有 auto [x, y] = xxxx 了
htfy96
2016-08-27 22:41:24 +08:00
@billlee
@yangff 开个 O2 gcc 下完全一样……
ninjadq
2016-08-27 22:44:47 +08:00
仿佛学过 C++ +1 = =
tracymcladdy
2016-08-27 22:57:01 +08:00
还是 c 纯粹
regeditms
2016-08-27 23:02:59 +08:00
@taowen 哦, 看来 mac 上也要用 brew 安装 clang 最新版本了。
bjrjk
2016-08-27 23:04:48 +08:00
你确定这个是 C++?
lzhCoooder
2016-08-27 23:32:47 +08:00
带着手动管理内存的包袱,却有这么高级的语法真的合适吗?
真的彻底和 ANSI C 分道扬镳了
lsmgeb89
2016-08-27 23:41:09 +08:00
现在除了 cppcon 哪里还能看点 C++17 的东西?
yangff
2016-08-27 23:54:54 +08:00
@k9982874 还好, C++的 auto 都能推倒类型
taowen
2016-08-27 23:56:55 +08:00
yuankui
2016-08-28 09:21:49 +08:00
这语法,丑的一笔。。
svenFeng
2016-08-28 09:34:58 +08:00
感觉适应一下新标准花不了多少时间,还可以学到很多东西,可现在也很多人还是用 C+class 操着 C++,很多人声称 STL 就是个垃圾(ーー;)
sinopec
2016-08-28 09:50:05 +08:00
c++坑太深,奇技淫巧跟新东西太多,学无止境啊,而且学的大部分还都用不到,好处是,现在学啥语言都不太费力....
linux40
2016-08-28 09:55:27 +08:00
c++17 标准库还是加了很多东西嘛。。。
htfy96
2016-08-28 09:56:28 +08:00
感觉国内的风向就是
1 纯 C 好 简洁
2 学了 C 自然就懂 C++了
3 新标准有什么用,一堆公司还在用 C++98
4 C++=C + STL 或者退化成 C with class
5 C++异常不管什么时候都差劲 还是 errCode 靠谱

虽然是因为国内一些客观因素决定的(比如说教学、招人成本之类的),但是这样下去只能会搞成国内特色的东西
linux40
2016-08-28 09:58:31 +08:00
至少动态语言是在模仿 lisp 。。。

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

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

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

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

© 2021 V2EX