Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error "No Viable Conversion From Returned Value of Type 'int[2]' to function return type 'vector<int>'"

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;}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading