ç¯å²foræãèªä½ã¯ã©ã¹ã§ä½¿ã
ç¯å²foræã¨ã¯
C++11ã«ç¯å²foræããããVisualStudioã§ã¯2012ãã使ããããã«ãªã£ãã
ããã¯ãSTLã®ã³ã³ããããçµã¿è¾¼ã¿é
åãforæã§æåããæå¾ã¾ã§ã®è¦ç´ ãå¦çããæã«ãå¾æ¥ã®foræã§ãã¡ãã¡ãæåãããçµããã¾ã§ãã¨ããç¯å²ãæ¸ããªãã¦æ¸ãã¨ãããã®ã
ä¾
#include <iostream> int main() { int a[3] = {1, 2, 3}; //ä»ã¾ã§(C++03) : é åã®ç¯å²ãæå®ããªããã°ãªããªãã£ã for(int i = 0; i < 3; ++i) { std::cout << a[i] << std::endl; } //ç¯å²foræ(C++11) : é åã®æåããæå¾ã¾ã§æä½ãããã¨ãèªæ for(int it : a) { std::cout << it << std::endl; } }
ãã®ä¾ã§ã¤ã¡ã¼ã¸ã¯ã¤ãããã¯ããã¾ããä¸è¨ã®ç¯å²foræã¯åæ¨è«ã使ã£ã¦ããæ¸ãã¦ãããã
for(auto it : a) { std::cout << it << std::endl; }
STLã®ã³ã³ããã«ã使ãã
#include <iostream> #include <vector> int main() { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); //C++03 for(std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) { std::cout << *it; } //C++11 for(std::vector<int>::value_type it : vec) { std::cout << it; } }
ååãé·ãã¿ã¤ãã³ã°ã大å¤ã ããå¯èªæ§ãä¸ããã®ã§åæ¨è«ã使ã£ãã»ããè¯ã
#include <iostream> #include <vector> int main() { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); //C++03 for(auto it = vec.begin(); it != vec.end(); ++it) { std::cout << *it; } //C++11 for(auto it : vec) { std::cout << it; } }
ç¯å²foræãèªä½ã¯ã©ã¹ã§ä½¿ããããã«ãã
ãããããæ¬é¡ããã®ç¯å²foræãèªä½ã¯ã©ã¹ã§ä½¿ãã«ã¯ã©ã®ãããªè¦ä»¶ãæºããã°ããã®ã ãããï¼
çãã¯ãã¤ãã¬ã¼ã¿ãæ»ããbeginã¨è¨ãååã®ã¡ã³ãé¢æ°ã¨ãendã¨è¨ãååã®ã¡ã³ãé¢æ°ãã¢ã¬ã°è¯ãã
ããã§è¨ãã¤ãã¬ã¼ã¿ã¨ã¯éæ¥åç
§æ¼ç®åã¨åç½®ã¤ã³ã¯ãªã¡ã³ãæ¼ç®åã¨ä¸ç価æ¼ç®åã®3ã¤ãå®ç¾©ãããã¯ã©ã¹ã§ãã*1ã
ã¤ã¾ãããéæ¥åç
§æ¼ç®åã¨åç½®ã¤ã³ã¯ãªã¡ã³ãæ¼ç®åã¨ä¸ç価æ¼ç®åã®3ã¤ãå®ç¾©ãããã¯ã©ã¹ãã®ã¤ã³ã¹ã¿ã³ã¹ãè¿ãbeginã¨endã¨ããååã®ã¡ã³ãé¢æ°ãæã¤ãã¯ã©ã¹ãªãç¯å²foræã使ç¨åºæ¥ãã
ä¸ã®è¦ä»¶ãæºããã°ãã©ããªã«ãµãããæ¼ç®åã®ãªã¼ãã¼ãã¼ãçããã¦ãã¦ãã®ç¯å²foræã使ããã¨ãã§ããã
ä¾
#include <iostream> //éæ¥åç §æ¼ç®åã¨åç½®ã¤ã³ã¯ãªã¡ã³ãæ¼ç®åã¨ä¸ç価æ¼ç®åãå®ç¾©ãã class hoge_iterator { public: hoge_iterator() : count_(0) { } int operator *() { return count_; } void operator ++() { } bool operator !=(hoge_iterator&) { return ++count_ < 5; } private: int count_; }; //ã¤ãã¬ã¼ã¿ãè¿ãbeginã¨endã¨ããï¼ã¤ã®ã¡ã³ãé¢æ°ãå®ç¾©ãã class h { public: hoge_iterator begin() const { return hoge_iterator(); } hoge_iterator end() const { return hoge_iterator(); } }; int main() { h h_; //ç¯å²foræã使ããï¼ for(auto it : h_) { std::cout << it << "\n"; } }
å®è¡çµæ
1 2 3 4 ç¶è¡ããã«ã¯ä½ããã¼ãæ¼ãã¦ãã ãã . . .
*1:æ¬æ¥ãªãã³ã³ããã®è¦ç´ ã¸ã®çµ±ä¸ããã¢ã¯ã»ã¹æ¹æ³ãå®ç¾ãããã¶ã¤ã³ãã¿ã¼ã³ã§ãã¤ãã¬ã¼ã¿ã®æå³ãèãã¦å®è£ ããã¹ãã ããä»åã¯ããã¾ã§èªä½ã¯ã©ã¹ãç¯å²foræã§åãã°è¯ãã®ã§ãããããæ¸ãæ¹ããã