Assumed that we have defined a vector (regardless of size and type of the elements; but vec.size() >= 1
) and we want to iterate through the entire vector, but do not want to modify any element:
std::vector<type> vec = someData;
for (type item : vec) {
// do something
// but assumed no manipulation of item
// I can access item which is a copy of vec[i]
}
for (const type &item : vec) {
// do something
// but assumed no manipulation of item
// I can access item which is a immutable reference to vec[i]
}
Both – copy and reference – will create new memory, either with a copy of the value or the address to that value in vec[i]
(remind: we only want to look at the elements!).
For complex types in vec
it is definitely more efficient to use a reference, because the size of the reference in the memory is less than the actual element in vec[i]
.
But what if the elements in vec
are of type int
with 4 Bytes width or so? Will the address or the actual int
contain a bigger size? So rather use a copy or a reference?
(I do not consider to use a reference for types like int or double! … but I am interested, so please make your answers general.)
Thanks :-)