Difference between (const string&) and (string&) pass by reference.

I wrote a code to calculate the scalar product of two vectors. I can't seem to fully understand the passing by reference and the const. When i put in paramters of the void entervalues function a void entervalues(string& vect, vector& vectt); WITHOUT the const, it doesnt compile. When i put void entervalues(const string& vect, vector& vectt); WITH the const before the string, it compiles. Why is this? And why is it better to put the &. why can't i just put void entervalues( string vect, vector vectt); ?

My code is :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void entervalues(const string& vect, vector<double>& vectt); 
double scalar(vector<double> u, vector<double> v); 
double ask_number(int N_MAX){
int n; 
do{ cout << "Enter a size for the vectors between 1 and " << N_MAX << endl; 
cin >> n; }while((n < 1) or (n > N_MAX)); 
return n; 
}   

int main(){

vector<double> U(ask_number(20)); 
vector<double> V(ask_number(20)); 

entervalues("First ", U); 
entervalues("Second ", V); 
cout << "Scalar product is  " << scalar(U,V) << endl; 

return 0; 
}

double scalar(vector<double> u, vector<double> v){
double sum(0.0); 
for(size_t i(0); i < u.size(); ++i){
    sum = sum + u[i]*v[i];}
    return sum;     
} 

void entervalues(const string& vect, vector<double>& vectt){
cout << vect << "vecteur: " << endl; 
for(size_t i(0); i < vectt.size(); ++i){
    cout << "Coordonates: " << i+1 << endl; 
    cin >> vectt[i]; }
}


Thanks :D
Last edited on
1.
Strings "First " and "Second " written in 15, 16 lines are hardly compiled into program, so they are readonly.
When you write void entervalues(string& vect,, you allow this function to modify argument. But argument is readonly. Thit is reason of error.
So you have to add const keyword.
You can rewrite is as
1
2
string s = "First";
entervalues("First ", U);

In this case readonly string is copied into local variable "s", which is readwrite. After it you can use entervalues without const keyword.

2.
If you don' put &
1
2
3
4
5
6
7
8
void f1(string s1)
{
}
void f2()
{
string s2 = "text";
f2(s2);
}

string s2 is copied for f1 and named s1. When you change s1, s2 is not modified.
If you put
1
2
3
4
5
6
7
8
void f1(string s1&)
{
}
void f2()
{
string s2 = "text";
f2(s2);
}

s1 is the onher name for s2. When you change s1, you change s2.

Adding & is preferrable in complex, time extreme applications, because every copying of string take some time, which make system slower.

3. Actually, you can write
void entervalues(string vect,
In this case readonly strings "Second " and "First " will be copied into local valiable of entervalues(...). It makes program simplier, but 2 nanoseconds slower.
Topic archived. No new replies allowed.