When a C ++ function takes an argument std::vector, a regular template should pass it by reference const, for example:
int sum2(const std::vector<int> &v)
{
int s = 0;
for(size_t i = 0; i < v.size(); i++) s += fn(v[i]);
return s;
}
I believe this code leads to double dereferencing when accessing the elements of the vector, since the CPU must first dereference vto read the pointer to the first element that needs to be dereferenced to read the first element. I would expect it to be more efficient to pass a shallow copy of a vector object on the stack. Such a shallow copy encapsulates a pointer to the first element, and the size encapsulates a pointer to the same memory area as the original vector.
int sum2(vector_ref<int> v)
{
int s = 0;
for(size_t i = 0; i < v.size(); i++) s += fn(v[i]);
return s;
}
, . : ? , - , .
: , , vector_ref . , .