Code goes below:
#include <vector>
int main()
{
vector<int> v1(5,1);
v1.swap(vector<int> ()); //try to swap v1 with a temporary vector object
}
The code above cannot compile, error:
error: no matching function for call to ‘std::vector<int, std::allocator<int> >::swap(std::vector<int, std::allocator<int> >)’
But, if I change the code to something like this, it can compile:
int main()
{
vector<int> v1(5,1);
vector<int> ().swap(v1);
}
Why?
The std::vector::swap function will always swap the contents of vector in constant time. In practice, both the functions will swap the contents of vectors in O(1) time and give the same performance.
The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type.
1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library.
Because vector<int>()
is an rvalue (a temporary, roughly speaking), and you cannot bind a non-const
reference to an rvalue. So in this case, you cannot pass it to a function taking a non-const
reference.
However, it's perfectly fine to invoke member functions on temporaries, which is why your second example compiles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With