C++: Proper way to iterate over STL containers

后端 未结 8 1403
灰色年华
灰色年华 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 06:02

    • For random-access containers, it's not wrong.
    • But you can use iterators instead.

      for (string::const_iterator it = theContainer.begin();
           it != theContainer.end(); ++it) {
          // do something with *it
      }
      
    • There are some circumstances under which a compiler may optimize away the .size() (or .end() in the iterator case) calls (e.g. only const access, function is pure). But do not depend on it.

提交回复
热议问题