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).
1 Answer 1
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.
-
Makes sense. Where you wrote "const auto& it", could I also use "const data_type& it" in the sample code I posted? All the Stack Overflow questions I've come across on ranged for loops involve auto, instead of the actual data type of the vector. My impression is both work, but I'm still unclear.Inertial Ignorance– Inertial Ignorance2018年05月14日 04:09:26 +00:00Commented May 14, 2018 at 4:09
-
Sure.
auto
tells the compiler to put the right type there for you, which is clear and obvious to know for it as you use the vector to that type. It saves some typing for longer types, and if your type changes, it adjust automatically. But of course you can specify the type yourself; that is identical.Aganju– Aganju2018年05月14日 04:11:54 +00:00Commented May 14, 2018 at 4:11