C++: Proper way to iterate over STL containers

后端 未结 8 1472
灰色年华
灰色年华 2021-01-06 04:55

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 ite

8条回答
  •  情深已故
    2021-01-06 05:56

    You might want to look at the standard algorithms.

    For example

    vector 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

提交回复
热议问题