c++ - C++中foreach循环的使用

标签 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;
}

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

我习惯于只在 STL 中使用 foreach 循环-容器...

最佳答案

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

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

更新:

您可以从 begin()end() 方法返回任何东西。让我从头告诉你它是如何工作的:

  1. std::begin()std::end() 都查找 Type::begin()分别键入::end()
  2. 他们得到这个对象并像使用指针一样使用它。为什么是指针?因为所有 STL 和 STL 兼容的迭代器都使用指针接口(interface)。
  3. 从第 2 点开始,您可以从 begin()end() 返回任何看起来像指针(使用其接口(interface))的东西:指针,或迭代器。指针实际上就像一个随机访问迭代器。

此外,STL 提供了一个关于迭代器的小概念:

everything that looks like an iterator is an iterator.

关于指针接口(interface)的例子:

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

关于c++ - C++中foreach循环的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30898705/

相关文章:

c++ - vector 预分配无法正常工作

c++ - 如何在读取文件时获得更多性能

java - 无法在 for-each 循环中写入 "i+2"作为后置条件 [Java]

c++ - 在 tbb::parallel_for 中使用 tbb::queueing mutex 的简单示例程序无法编译

c++ - 如何在声明变量时评估表达式(在表达式模板中)

c++ - 来自 std::_Rb_tree_const_iterator<Type>::operator++ 的段错误

javascript - 为什么是 angular.forEach 上下文?

php - 在 foreach 循环中循环的数组中添加项目

php - php foreach循环中的HTML表,其中仅当元素等于表列标题名称时才填充单元格数据

javascript - 如何使用 jQuery 在 json 子数组中添加值?