0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

for (auto 変数:((初期値)...最終値(, 増加量)))

Last updated at Posted at 2020-02-03

無限ループバグが必ずできないfor文

こういうループが正直欲しい(他人にソース渡すときにバグができない安心感がある)。
for (auto 変数:((初期値)...最終値(, 増加量)))->初期値(デフォルト:0)と増加量(デフォルト:1)は省略可能

ex.cpp

for (auto x:(...<100)) 
{
	printf("%d", x);
}
//以下に等しい
//for(int x = 0 ;x < 100; x++){
//	printf("%d", x);
//}
for (auto x:(100...>1, -1)) 
{
	printf("%d", x);
}
//以下に等しい
//for(int x = 100 ;x > 1; x--){
//	printf("%d", x);
//}
//こういう書き方も可能(static constexpr auto length = 100が定義済み)
//for(auto i = 0: (...<length))
//auto rng = (...<100)みたいに書くことも可能。

ソースコードエディターにfor...で載る->使うとfor(auto i : (...<length))とコードに自動で書かれる

C/C++の特性として柔軟性の高さが挙げられる。

悪魔に魂を売ると言われる危険なマクロを無くすためにtemplate<>を作った。だからこそ柔軟性の高さからfor (auto 変数:((初期値)...最終値(, 増加量)))も可能なはず。

この子のメリットはこれだけではない。

このような書き方もできるようになるのである。

ex.cpp
//template<class T>iEnumerable(T& collection,DefaultRange rng)が定義。
//std::string MyArrey[100]が定義。
for(auto& p :iEnumerable(MyArray,(0...<98,2))){//std::pair<std::string&,int>型が返却
	printf("%s",MyArray[p.second+2] == MyArray[p.second]? p.first.c_str():"Error");
}

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?