[英]Usage of the foreach loop in C++
I've found an example at cpluplus.com . 我在cpluplus.com上找到了一个例子。 Here it is:
这里是:
#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;
}
Why can we use a for-each
loop on the object of the type smatch
? 为什么我们可以在
smatch
类型的对象上使用for-each
循环?
I'm used to using the foreach loop only with STL -containers... 我习惯只使用STL -containers的foreach循环......
The so-called foreach
loop looks for the begin()
and end()
in the scope they are needed. 所谓的
foreach
循环在需要的范围内查找begin()
和end()
。 So, if your class implements begin()
and end()
with iterator interface you may use new foreach
loop. 因此,如果您的类使用迭代器接口实现
begin()
和end()
,则可以使用新的foreach
循环。
As @NathanOliver said, you should avoid calling this loop as foreach
loop because you may confuse it with std::for_each
algorithm. 正如@NathanOliver所说,你应该避免将这个循环称为
foreach
循环,因为你可能会将它与std::for_each
算法混淆。 Call it range-based for
. 称之为
range-based for
。
UPDATE: 更新:
You may return any thing from begin()
and end()
methods. 您可以从
begin()
和end()
方法返回任何内容。 Let me tell you how it works from the beginning: 让我从一开始就告诉你它是如何工作的:
std::begin()
and std::end()
both look for Type::begin()
and Type::end()
respectively. std::begin()
和std::end()
分别查找Type::begin()
和Type::end()
。 begin()
and end()
that looks like a pointer (uses its interface): a pointer, or an iterator. begin()
和end()
返回任何看起来像指针(使用其接口)的东西:指针或迭代器。 Pointer actually is just like a random-access iterator. Also, STL provides a small concept about iterators: 此外,STL提供了一个关于迭代器的小概念:
everything that looks like an iterator is an iterator.
看起来像迭代器的所有东西都是迭代器。
Example about pointer 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;
}
Reading section: 阅读部分:
Nicolai M. Josuttis C++11 STDLIB Nicolai M. Josuttis C ++ 11 STDLIB
STL compatible iterators for custom containers 用于自定义容器的STL兼容迭代器
Writing STL compatible iterators 编写STL兼容的迭代器
How to implement an STL-style iterator and avoid common pitfalls 如何实现STL样式的迭代器并避免常见的陷阱
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.