0
#include<bits/stdc++.h>
using namespace std;
bool compare(const vector<long long int>&v1,const vector<long long int>&v2 ) { 
 return v1[0] < v2[0]; 
}

Can anyone tell me the use of const keyword and & in the function argument ?

Aditya Aggarwal
  • 159
  • 1
  • 9
  • 1
    `&` take the parameter by reference; `const` not able to change the parameter. Can I refer you to the book list https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282 – Richard Critten Mar 06 '21 at 19:42
  • 1
    This is not the address. Its pass by reference which is a very important c++ concept that should be taught very early in your c++ book. – drescherjm Mar 06 '21 at 19:42
  • What will happen if we don't use both & and const ? – Aditya Aggarwal Mar 06 '21 at 19:43
  • no `&` - pass by value - take a copy of the vector and all of it's elements; no `const` - you can make changes to the parameter (vector) in the function but the caller will not see your changes as the function is working on a copy – Richard Critten Mar 06 '21 at 19:43
  • const means inside the function you will not modify the vector. – drescherjm Mar 06 '21 at 19:44
  • @drescherjm here we are not modifying our vector we are just changing the order so what's the need of const ? – Aditya Aggarwal Mar 06 '21 at 19:46
  • Inside the compare you are not modifying the vector at all. You are just comparing the first element of 2 vectors – drescherjm Mar 06 '21 at 19:47
  • 1
    @AdityaAggarwal _"...changing the order..."_ nope not happening, no order changing going on in the posted code just a comparison – Richard Critten Mar 06 '21 at 19:47
  • Yes sorry , we are just comparing so what's the need of const ? – Aditya Aggarwal Mar 06 '21 at 19:48
  • 1
    To reassure the caller that a comparison function will not change their vector. And to stop the implementer of the comparison function making a silly mistake. – Richard Critten Mar 06 '21 at 19:48
  • 1
    Some of the answers in this question answer why const is used: [https://stackoverflow.com/questions/3967177/when-to-use-const-and-const-reference-in-function-args](https://stackoverflow.com/questions/3967177/when-to-use-const-and-const-reference-in-function-args) – drescherjm Mar 06 '21 at 19:49

0 Answers0