有没有更漂亮的 c++ 语法迭代器?
在 C++ 中是否有更漂亮/更简洁的方式使用迭代器?从我看过的教程来看,我要么到处设置 typedef(对于很多一次性 for 循环来说这会很乏味):
typedef std::vector<std:pair<int, int> >::iterator BlahIterator;
或者有冗长的 for 循环,例如:
for (std::vector<std:pair<int, int> >::iterator it = ... ) ...
有更好的方法吗?
Is there a prettier / less-verbose way to use iterators in C++? From the tutorials I've seen, I either set up typedefs everywhere (which gets tedious to do for a lot of one-off for-loops):
typedef std::vector<std:pair<int, int> >::iterator BlahIterator;
or have verbose-looking for loops like:
for (std::vector<std:pair<int, int> >::iterator it = ... ) ...
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 c++0x 中,您可以使用 auto 关键字:
With c++0x you can use the auto keyword:
我通常使用以下命名模式:
然后使用
Blahs::iterator
,即我不命名迭代器,而是命名容器(通常是其中包含的东西)。typedef
是一种非常有用的抽象机制。请注意,“Blah”向量称为“Blahs”(即复数),而不是“BlahVector”,因为特定容器并不重要。
I usually use the following naming pattern:
and then use
Blahs::iterator
, i.e I don't name the iterator but the container (and usually the thing contained in it).typedef
is a very useful abstraction mechanism.Note that a vector of "Blah" is called "Blahs" (i.e. just the plural), not a "BlahVector", because the specific container doesn't matter.
一种可能性是将循环(或使用迭代器的任何代码)写入其自己的小型通用算法中。通过将其设为模板,编译器可以/将自动推导迭代器类型:
One possibility is to write your loop (or whatever code that uses the iterator) into a small generic algorithm of its own. By making it a template, the compiler can/will deduce the iterator type automatically:
我通常会定义这个,尽管有人告诉我我会为此下地狱:
然后,为了从 0 循环到 n,这是一个常见的任务,我说
forn(i, n) foo(i);< /code>,并循环任何标准容器 c,我说
forall(it, c) foo(it);
请注意typeof
是标准的 GCC 扩展。I usually define this, though I've been told I'm going to hell for it:
Then, to loop from 0 to n, a common task, I say
forn(i, n) foo(i);
, and to loop any standard container c, I sayforall(it, c) foo(it);
Do note thattypeof
is a GCC extension to the standard.在 C++11 中,您可以将基于范围的 for 循环与 auto 关键字结合使用:
In C++11 you can use the range-based for loop combined with the auto keyword:
通过boost,您可以使用FOR_EACH 宏。
With boost, you can use the FOR_EACH macro.
这些算法在某种程度上解决了这个特定问题。
尤其是新的 lambda 函数。
或者使用 lambda:
注意:不要陷入使用 std::for_each 替换所有循环的陷阱。有一大堆使用迭代器的算法,允许您根据容器的内容进行操作或执行操作。
The algorithms sort of get around that particular problem.
Especially with the new lambda functions.
Or with lambda:
Note: don't fall into the trap of using std::for_each to replace all loops. There are a whole bunch of algorithms that use iterators that allow you to manipulate or do operations based on the contents of a container.