C ++:迭代STL容器的正确方法 [英] C++: Proper way to iterate over STL containers
本文介绍了C ++:迭代STL容器的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的游戏引擎项目中,我广泛使用STL,主要是 std :: string
和 std :: vector
classes。
In my game engine project, I make extensive use of the STL, mostly of the std::string
and std::vector
classes.
在很多情况下,我必须遍历它们。现在,我这样做的方式是:
In many cases, I have to iterate through them. Right now, the way I'm doing it is:
for( unsigned int i = 0; i < theContainer.size(); i ++ )
{
}
- 我是以正确的方式做的吗?
-
如果没有,为什么,我该怎么做呢?
- Am I doing it the right way?
If not, why, and what should I do instead?
使用此实现,每个循环周期是否真的执行了size()?性能损失是否可以忽略不计?
Is size() really executed every loop cycle with this implementation? Would the performance loss be negligible?
推荐答案
C ++ 11有一个新容器意识到循环语法,如果你的编译器支持新标准,可以使用它。
C++11 has a new container aware for loop syntax that can be used if your compiler supports the new standard.
#include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> vs; vs.push_back("One"); vs.push_back("Two"); vs.push_back("Three"); for (const auto &s : vs) { cout << s << endl; } return 0; }
这篇关于C ++:迭代STL容器的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文