C++: Proper way to iterate over STL containers

后端 未结 8 1400
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    2021-01-06 05:38

    You're doing it OK for vectors, although that doesn't translate into the right way for other containers.

    The more general way is

    for(std::vector::const_iterator i = theContainer.begin(); i != theContainer.end; ++i)
    

    which is more typing than I really like, but will become a lot more reasonable with the redefinition of auto in the forthcoming Standard. This will work on all standard containers. Note that you refer to the individual foo as *i, and use &*i if you want its address.

    In your loop, .size() is executed every time. However, it's constant time (Standard, 23.1/5) for all standard containers, so it won't slow you down much if at all. Addition: the Standard says "should" have constant complexity, so a particularly bad implementation could make it not constant. If you're using such a bad implementation, you've got other performance issues to worry about.

提交回复
热议问题