0

When I do this:

#include <iostream>
#include <vector>

using namespace std;

void print(vector<int> &v)
{
    int i;
    for(i = 0; i < v.size(); i++)
        cout<<v[i]<<" ";
    cout<<endl;
}

int main()
{
    vector <int> A = {1,2,3,4,5};
    print(A);
}

I am not required to make the vector const. But when I pass a sub part of the vector:

#include <iostream>
#include <vector>

using namespace std;

void print(vector<int> &v) // Throws Error. Needs it as const vector<int> &v
{
    int i;
    for(i = 0; i < v.size(); i++)
        cout<<v[i]<<" ";
    cout<<endl;
}

int main()
{
    vector <int> A = {1,2,3,4,5};
    print({A.begin(), A.begin()+2});
}

The compiler expects that the vector is passed as const (void print(const vector<int> &v)). Why is it so?

user248884
  • 851
  • 1
  • 11
  • 21
  • any idea what an rvalue is ? Can a lvalue reference bind to an rvalue ? When you pass `A`, it is an lvalue. When you pass `{iterator, iterator}` it is an rvalue. – badola Jul 17 '18 at 07:29
  • This is a duplicate: https://stackoverflow.com/q/1565600/9593596 – lubgr Jul 17 '18 at 07:30
  • Because the construct `{A.begin(), A.begin()+2}` creates a temporary, and a temporary cannot be passed by non-`const` reference. Logically, an output operation does not normally change an object (otherwise printing it twice would produce different results each time) so it makes sense for your `print()` to accept a `const` reference anyway. – Peter Jul 17 '18 at 07:40
  • @badola I wasnt aware of it. Thank you! – user248884 Jul 17 '18 at 08:07
  • @Peter But why is it a temporary? Vectors are defined in heap memory and not stack. Logically yes, It doesnt make a difference if its const too. My point of asking was to understand the concept behind it. – user248884 Jul 17 '18 at 08:08
  • 1
    Vectors are not defined in "heap memory". They are a self-contained data structure that must be created somehow (e.g. using a constructor). In the statement `print({A.begin(), A.begin() + 2})`, neither `A.begin()` not `A.begin() + 2` are of type `std::vector`, but a `std::vector` must somehow exist to be passed to `print()`. A `vector` created from `A.begin()` and `A.begin() + 2` is not the same as `A` - it is a distinct object. So the compiler duly creates one temporarily for the purposes of passing it to `print()` and immediately destroys it afterward. – Peter Jul 17 '18 at 08:40
  • You might be thinking about the *elements contained* in a `std::vector`, which are allocated from the *free store*, by the `std::allocator` member. C++ does not define "heap" or "stack" (in this context). Those are implementation-specific – Caleth Jul 17 '18 at 08:54

0 Answers0