Four years later, Google gave me this answer. With the
standard C++11 (also known as
C++0x), there is now a new and convenient way to achieve this (at the cost of breaking backward compatibility): using the new
auto
keyword. It spares you the trouble of explicitly specifying the type of the iterator to be used (repeating the vector type again), when it is already clear (to the compiler) which type to use. Assuming that
v
is your
vector
, you can do something like this:
for ( auto i = v.begin(); i != v.end(); i++ ) {
std::cout << *i << std::endl;
}
C++11更进一步,为您提供了一种特殊的语法,用于迭代像向量这样的集合。它消除了编写始终相同的内容的必要性:
for ( auto &i : v ) {
std::cout << i << std::endl;
}
要在工作程序中查看它,请构建一个名为
auto.cpp
的文件:
#include <vector>
#include <iostream>
int main(void) {
std::vector<int> v = std::vector<int>();
v.push_back(17);
v.push_back(12);
v.push_back(23);
v.push_back(42);
for ( auto &i : v ) {
std::cout << i << std::endl;
}
return 0;
}
在编写本文时,当您使用 g++ 进行编译时,通常需要通过添加额外的标志来使其与新标准兼容:
g++ -std=c++0x -o auto auto.cpp
现在你可以运行这个例子:
$ ./auto
17
12
23
42
请注意,编译和运行的说明仅适用于Linux上的GNU C++编译器,该程序应该是平台(和编译器)无关的。
.size()
不是类型为unsigned
或者unsigned int
,它的类型是std::size_t
。 - underscore_dstd::size_t
是一个实现定义的typedef。请参阅标��。在当前实现中,std::size_t
可能等同于unsigned
,但这并不重要。假装它是可以导致非可移植代码和未定义的行为。 - underscore_d