C++ 指定范围内递增初始化一个vector<int> | Python: list(range(31, 90))

通过lambda表达式 + std::iota()实现:

template <typename Tp>
inline void print_vec(const std::vector<Tp>& vec) {
    fmt::print("[{}]\n", fmt::join(vec, ", "));
}


    // 相当于Python的`lst = list(range(31, 90))`
    const std::vector<int> vec = [] () {
        std::vector<int> vec(90 - 31);
        std::iota(vec.begin(), vec.end(), 31);  // 递增,初值为31
        return vec;
    }();  // 原理是定义一个lambda函数然后直接`()`调用
    
    print_vec(vec);

输出:

[31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 
71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 
81, 82, 83, 84, 85, 86, 87, 88, 89]

你可能感兴趣的:(c++,python,开发语言)