Question

I have the following code, and I was wondering if I'm optimally iterating through my ranged for loop:

struct data_type
{
      int a;
      int b;
};

int main()
{
    // Assume I have initialized a vector storing data_type objects.
    // The vector is called "vec".

     for (const data_type& temp: vec)
     {
           // Observe temp's attributes (int a and int b).
     }
}

Is it best to iterate using constant reference as I have done? Or would iterating by value be better (data_type temp: vec). I'm asking for both writing clearer code and more efficient code.

I've heard that it's better/as efficient to pass by value with small data types, such as ints. My struct "data_type" is just composed of two ints, so I'm not sure if constant reference or value is better to use.

On the topic of clearer code, both constant reference and pass by value seem clear to me (although maybe there's differing opinions on this).

Was it helpful?

Solution

Depending on the vector, you might be only able to iterate with a const iterator - if the content or the vector itself is defined const (or passed as const to you).

If you need only read access to the content, always use const iterators. It is slightly more efficient, and protects you from accidentially modifying the content through function calls etc.

Also always use a reference const T&, which avoids any copying of the values in the vector (simply remember const auto& it for all cases). That can make a lot of difference if the copying is expensive.

Of course, if you want to modify the content, you need a non-const reference iterator.

Licensed under: CC-BY-SA with attribution
scroll top