if u pass a std::vector by value to a function, does all of it's content get copyed?
thx
Short answer: yes. Passing a std::vector by value constructs a new vector with copies of all its elements (linear in size). Passing by const reference avoids that deep copy when you only need to read. (cppreference.com)
A modern wrinkle: if the function takes the vector by value and the caller passes a temporary or uses std::move, the parameter is built via the move constructor (typically just swaps pointers), which is constant-time for std::vector. That makes the “take by value, then move into a member” pattern efficient for sink-style APIs. Example:
struct Holder {
std::vector<int> data;
void set(std::vector<int> v) { data = std::move(v); } // lvalues copy, rvalues move
};
// calls:
Holder h;
std::vector<int> src = {1,2,3};
h.set(src); // copies elements, then moves into data
h.set(std::vector<int>{4,5}); // moves, no deep copy When an rvalue is passed to a by-value parameter, the move constructor is used; with an lvalue, it copies. (cppreference.com)
On ’s nested case, is right: binding a parameter as vector<vector<int>>& is just another name for the same outer container; no inner vectors are copied during parameter passing. Be aware, though, that modifying an inner vector (e.g., push_back/insert) may trigger a reallocation inside that inner vector, which moves/copies its elements and invalidates its iterators and references. Use reserve on the inner vector first if you know how many items you will add. (en.cppreference.com)
Rule of thumb aligning with :
const std::vector<T>&.std::vector<T>&.Jump to Post— pecet 1Reference to vector is like just "another name" for your original vector. You still work on memory taken by your original vector. So if you worry, that internal vector could be copied - you don't have to. It won't be copied.
If a vector is passed by value, the data will be copied for use locally. If the vector is small, there is no problem, but if it is large, then the parameter-passing itself could consume a lot of resources. You should probably pass it by reference, and use the const keyword to ensure that the data doesn't get inadvertently modified.
if i pass vectors of vector by reference then internal vectors also get passed by reference?
eg function (vector<vector <int> > &a);
Reference to vector is like just "another name" for your original vector. You still work on memory taken by your original vector. So if you worry, that internal vector could be copied - you don't have to. It won't be copied.
thanks a lot..
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.