我在 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()
方法返回任何东西。让我从头告诉你它是如何工作的:
std::begin()
和std::end()
都查找Type::begin()
和分别键入::end()
。- 他们得到这个对象并像使用指针一样使用它。为什么是指针?因为所有 STL 和 STL 兼容的迭代器都使用指针接口(interface)。
- 从第 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/