According to Google C++ Style Guide and Elements of programming interviews, in C++, non-const references are never allowed as input arguments to functions.
Is this convention widely accepted by other companies (Facebook, Linkedin, or even banks)?
I wonder if I should obey this convention during all my programming interviews (onsite or not) ?
In some programming problems, it is convenient (even necessary) to modify variables inside a function. If non-const reference arguments are forbidden, then I have to use pointers instead, which would lead to inconvenient and ugly code like (*pval)++.
For example, if I am asked to solve Leetcode 46. Permutations during an interview, can I write the following code which uses non-const reference arguments?
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
vector<int> current;
vector<bool> used(nums.size(), false);
backtrack(res, nums, current, used);
return res;
}
void backtrack(vector<vector<int>>& res, vector<int>& nums, vector<int>& current, vector<bool>& used){
if(current.size() == nums.size()){
res.push_back(current);
return;
}
for(int i = 0; i < nums.size(); i++){
if(!used[i]){
current.push_back(nums[i]);
used[i] = true;
backtrack(res, nums, current, used);
current.pop_back();
used[i] = false;
}
}
}
};Or is it better for me to write the following code which substitutes non-const reference arguments for pointers?
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
vector<int> current;
vector<bool> used(nums.size(), false);
backtrack(&res, nums, ¤t, &used);
return res;
}
void backtrack(vector<vector<int>>* res, const vector<int>& nums, vector<int>* current, vector<bool>* used){
if((*current).size() == nums.size()){
(*res).push_back(*current);
return;
}
for(int i = 0; i < nums.size(); i++){
if(!(*used)[i]){
(*current).push_back(nums[i]);
(*used)[i] = true;
backtrack(res, nums, current, used);
(*current).pop_back();
(*used)[i] = false;
}
}
}
};