在我的游戏引擎项目中,我大量使用了 STL,主要是 std::string
和 std::vector
类。
在很多情况下,我必须遍历它们。现在,我这样做的方式是:
for( unsigned int i = 0; i < theContainer.size(); i ++ )
{
}
- 我的做法是否正确?
如果不是,为什么,我应该怎么做?
在这个实现中,size() 真的在每个循环周期都执行了吗?性能损失可以忽略不计吗?
最佳答案
C++11 有一个新的容器感知 for 循环语法,如果您的编译器支持新标准,则可以使用它。
#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 容器的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4925148/