c++ - What is the most modern way, the most "right" way to iterate through a vector, in c++11 -


Now I am learning C ++ and I am looking at several ways to walk again through a vector. I was thinking, because I want to know it correctly, what is the right approach for nowadays?

Depends on the following factors:

  1. Is your loop or just inside the elements?
  2. Do you almost always like auto (AAA) or almost ever auto (ANA)? For example, if you want a std :: vector & lt; Int & gt; You can do this on the loop on some of the elements of the elements:
     for  (int element: v) {// use element}   

    If you are an AAA person, you would write auto element instead.

    If you want to save a copy, you want a conference reference:

     for  (int Const & amp; element: v) {// Usage Element}   

    If you are an AAA person, you can replace it with auto const & amp; Element .

    If you want to modify the values ​​inside the vector, then you want an amended reference:

     for  (int and element: v) {// use Element}   

    Once again, if you prefer AAA, instead of auto & amp; Element

    If you need an iterator inside the loop:

     for  (std :: vector  :: iterator = std :: start (V); it! = Std :: end (v); ++ it) {// use it}   

    And if you are an AAA person: < For pre> (auto = std :: begin (v); it! = Std :: end (v); ++ this) {// use it}}

    Note that the ANA person also does not depend on the actual type (which is not very common) if the code inside the loop automatically is from you.

    Also keep in mind that you will often see loops completely & lt; Algorithm & gt; Suitable algorithms from . For some information on this, they suggested that any loop is bad with more than few lines and it can usually be written very much.

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -