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?