在C ++中使用foreach循环

时间:2015-06-17 17:44:04

标签: c++ foreach

我在cpluplus.com找到了一个例子。这是:

#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("This subject has a submarine as a subsequence");
  std::smatch m;
  std::regex e ("\\b(sub)([^ ]*)");   // Matches words beginning by "sub"

  std::cout << "Target sequence: " << s << std::endl;
  std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
    for (auto x:m) 
      std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

为什么我们可以在for-each类型的对象上使用smatch循环?

我习惯只在STL - 容器......

中使用foreach循环

1 个答案:

答案 0 :(得分:3)

所谓的foreach循环会在所需范围内查找begin()end()。因此,如果您的类使用迭代器接口实现begin()end(),则可以使用新的foreach循环。

正如@NathanOliver所说,你应该避免将这个循环称为foreach循环,因为你可能会将它与std::for_each算法混淆。称之为range-based for

<强>更新

您可以从begin()end()方法返回任何内容。让我从一开始就告诉你它是如何运作的:

  1. std::begin()std::end()分别寻找Type::begin()Type::end()
  2. 他们得到这个对象并使用它就像指针一样。为何指针?因为所有stl和stl兼容的迭代器都使用指针接口。
  3. 从第2点开始,您可以从begin()end()返回任何看起来像指针(使用其界面)的东西:指针或迭代器。指针实际上就像一个随机访问迭代器。
  4. 此外,STL提供了一个关于迭代器的小概念:

      

    看起来像迭代器的所有东西都是迭代器。

    关于指针接口的示例

    struct A
    { 
        int* val = new int[5];
    
        int* begin() const {
            return val;
        }
    
        int* end() const {
            return val + 5;
        }
    };
    
    
    int main ()
    {
        A a;
        for (const auto &v : a) {
            std::cout << "value: " << v << std::endl;
        }
    
        return 0;
    }
    

    阅读部分:

    Nicolai M. Josuttis C++11 STDLIB

    STL compatible iterators for custom containers

    Writing STL compatible iterators

    How to implement an STL-style iterator and avoid common pitfalls