C++ の range-based for でループカウンタを使用する
Twitter でみかけたので書いてみた。
一番簡単なのは boost::adaptors:indexed
使うのが楽っぽい。
[コード]
#include <vector> #include <iostream> #include <string> #include <boost/range/adaptor/indexed.hpp> int main(){ std::vector<std::string> table = { "homu", "mami", "mado"}; for(auto&& it : table | boost::adaptors::indexed()){ std::cout << it.index() << ":" << it.value() << std::endl; } return 0; } /* output: 0:homu 1:mami 2:mado */
標準ライブラリに Range ライブラリはよ