以下程序打印出一张洗牌的牌组(整数):
#include#include #include #include typedef unsigned int card; typedef std::array deck; auto shuffled_deck(){ deck d = {}; std::iota(d.begin(), d.end(), 0); std::shuffle(d.begin(), d.end(), std::default_random_engine()); return d; } int main(){ for(auto& i: shuffled_deck()) std::cout << i << ", "; }
编译g++ -std=c++17
程序运行和打印:
18, 34, 27, 46, 11, 3, 12, 19, 33, 21, 41, 13, 36, 49, 40, 22, 8, 9, 28, 2, 6, 30, 50, 24, 37, 32, 35, 4, 15, 45, 47, 43, 14, 44, 20, 23, 29, 7, 31, 51, 26, 10, 42, 48, 0, 38, 5, 16, 17, 1, 25, 39,
这很好,但是直觉告诉我这个套牌可以在编译时创建,所以我制作了这个shuffled_deck
方法constexpr
constexpr auto shuffled_deck(){ deck d = {}; std::iota(d.begin(), d.end(), 0); // Error! Iota isn't constexpr! std::shuffle(d.begin(), d.end(), std::default_random_engine()); return d; }
编译时g++ -std=c++17
会给出编译错误,说明std::iota
不是constexpr
.我的问题是为什么?当然std::iota
可以在编译时确定.标准库是否仅落后于此功能?