1

Recently, I round a beautiful way to output a vector from std::partition_point.

  std::cout << "odd:";
  for (int& x:odd) std::cout << ' ' << x;
  std::cout << '\n';

Could anyone give a short description how it works and why it works? I would appreciate if someone could find this usage of for loop in documentation, unfortunately I didn't find it on http://www.cplusplus.com/.

4

2 回答 2

3

这是一个基于范围的 C++ 循环:您指定一个循环变量和一个容器,编译器生成迭代容器的代码,并在执行循环体之前依次为容器的每个项目分配循环变量。在 C++11 之前,此循环构造不可用。

请注意,有一种方法可以在不使用循环的情况下输出容器:

std::ostream_iterator<int> out_it (std::cout, " ");
std::copy( odd.begin(), odd.end(), out_it );
于 2013-08-11T13:37:10.057 回答
0

我认为您可能对 boost::foreach 实现感兴趣:http: //www.boost.org/doc/libs/1_54_0/doc/html/foreach.html。这并不完全是标准 for 循环的实现,但您可以调试和研究 foreach.hpp 文件。下面我附加您可能感兴趣的示例:

#include <string>
#include <iostream>
#include <boost/foreach.hpp>

int main()
{
   std::string hello( "Hello, world!" );

   BOOST_FOREACH( char ch, hello )
   {
     std::cout << ch;
   }

   return 0;
}
于 2013-08-11T14:34:47.630 回答