Home > Blockchain >  Error "No Viable Conversion From Returned Value of Type 'int[2]' to function return t
Error "No Viable Conversion From Returned Value of Type 'int[2]' to function return t

Time:11-05

coder newbie here, I have an issue on HackerRank. It tells me to make a function which compares the elements of 2 arrays and returns 2 values in an array. However I get the "No Viable Conversion" error. When I change the type of 'scores' to vector, I get a compiler error, saying "Segmentation Fault". What I would like to find out is what this is, why it happens and where I can find out more about this.

vector<int> compareTriplets(vector<int> a, vector<int> b) {
int sA = 0, sB = 0;
vector<int> scores;
for(int i = 0; i <3; i  ){
    if (a[i] > b[i]){
        sA  ;
    }else{
        sB  ;
    }
}
scores[0] = sA;
scores[1] = sB;
return scores;}

CodePudding user response:

The problem is that you created a vector of size 0(an empty vector) and then were trying to assign elements to its 0th and 1st index which didn't exist. You should use :

//pass the vector by reference instead of by value
vector<int> compareTriplets(const vector<int> &a,const vector<int> &b) {
int sA = 0, sB = 0;
vector<int> scores(2); //create vector of size 2
for(int i = 0; i <3; i  ){
    if (a[i] > b[i]){
        sA  ;
    }else{
        sB  ;
    }
}
scores[0] = sA;
scores[1] = sB;
return scores;
    
}

when creating the std::vector of a particular size. Secondly you should pass the vectors a and b by reference instead of by value as i did in my example. This way it will be faster.

  • Related