基于范围的双对表 [英] Range-based for over pair list
问题描述
说,我想迭代内联定义的许多对。有没有一种较短的写方法:
for(auto pair:std :: initializer_list< std :: pair< int,int> ;> {{1,2},{3,4}})
// ...
?
只需指定第一个元素是一对。其余的将自动推导出:
for(auto& pair:{std :: pair< int,int> {1, 2},{3,4}})
;
带括号的初始化程序被推导为 std :: initalizer_list
,第一个被命名为对的元素将要求 all 元素成为对的初始化。
您标记了C ++ 11,但为了完整起见,在C ++ 17中甚至可以更短:
for(auto& pair:{ std :: pair {1,2},{3,4}})
;
由于类模板参数的推导。如果没有,那么 std :: make_pair
可以保持模板参数推导的好处:
for(auto& pair:{std :: make_pair(1,2),{3,4}})
;
尽管表面上看,它对代码打高尔夫球没有C ++ 17版本有用。 / p>
Say, I want to iterate a number of pairs defined inline. Is there a shorter way to write:
for(auto pair : std::initializer_list<std::pair<int,int>>{{1,2}, {3,4}})
// ...
?
Just specify the first element is a pair. The rest will be deduced automatically:
for(auto& pair : {std::pair<int,int>{1,2}, {3,4}})
;
The braced enclosed initializer is deduced to be std::initalizer_list
, and the first element being named a pair will require all elements to be an initalizer for a pair.
You tagged C++11, but for completeness, it can be even shorter in C++17:
for(auto& pair : {std::pair{1,2}, {3,4}})
;
Due to class template argument deduction. If you don't have that, than std::make_pair
will do if you want to maintain the benefits of template argument deduction:
for(auto& pair : {std::make_pair(1,2), {3,4}})
;
Though ostensibly, it isn't as useful for code golfing as the C++17 version.
这篇关于基于范围的双对表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!