Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Proper way to iterate over STL containers

Tags:

c++

iterator

stl

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?

  • Is size() really executed every loop cycle with this implementation? Would the performance loss be negligible?

like image 940
Yarr Avatar asked Nov 28 '22 18:11

Yarr


2 Answers

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;
}
like image 79
ChetS Avatar answered Dec 05 '22 15:12

ChetS


You might want to look at the standard algorithms.

For example

vector<mylass> myvec;

// some code where you add elements to your vector

for_each(myvec.begin(), myvec.end(), do_something_with_a_vector_element);

where do_something_with_a_vector_element is a function that does what goes in your loop

for example

void 
do_something_with_a_vector_element(const myclass& element)
{
 // I use my element here
}

The are lots of standard algorithms - see http://www.cplusplus.com/reference/algorithm/ - so most things are supported

like image 27
Tom Avatar answered Dec 05 '22 15:12

Tom