我在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循环答案 0 :(得分:3)
所谓的foreach
循环会在所需范围内查找begin()
和end()
。因此,如果您的类使用迭代器接口实现begin()
和end()
,则可以使用新的foreach
循环。
正如@NathanOliver所说,你应该避免将这个循环称为foreach
循环,因为你可能会将它与std::for_each
算法混淆。称之为range-based for
。
<强>更新强>
您可以从begin()
和end()
方法返回任何内容。让我从一开始就告诉你它是如何运作的:
std::begin()
和std::end()
分别寻找Type::begin()
和Type::end()
。begin()
和end()
返回任何看起来像指针(使用其界面)的东西:指针或迭代器。指针实际上就像一个随机访问迭代器。此外,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