Nick Redheffer
Nick Redheffer

Reputation: 1

C++ Vector troubles

Heres a function of my program, which keeps crashing. The purpose of the function is the search through the vectors and display what they rank and the frequency, which is read into thier respective vectors. Im guessing its my while loop but im not sure. The vectors are correctly read in.

void searchNames(vector<string> girlsname,vector<int> girlsfeq,vector<string> boysname,vector<int> boysfeq){
    string name1;
    string name;
    int SIZE = girlsname.size();
    int SIZE2 = boysname.size();
    while(name1 != "quit"){
        int i=0;
        int frank=find(girlsname.begin(), girlsname.end(), name1) - girlsname.begin();
        int mrank=find(boysname.begin(), boysname.end(), name1) - boysname.begin();
        name1.clear();
        name.clear();
        cout << "Please enter a name: ";
        cin >> name1;
        cout << endl;
        while(i< SIZE && name1 !=girlsname[i++]){

       frank++;

        }
        name.clear();
        i=0;
        while(i< SIZE2 && name1 !=boysname[i++]){

        mrank++;

        }
        cout << left << setw(15) << "Name" << right << setw(10) << "Girl Rank" << right << setw(10) << "Frequency" << right << setw(10) << "Boy Rank"<< right << setw(10) << "Frequency" << endl;
        if(frank != SIZE && mrank != SIZE2){
        cout << left << setw(15) << name1 << right << setw(10) << frank << right << setw(10) << girlsfeq[frank] << right << setw(10) << mrank << right << setw(10) << boysfeq[mrank] << endl;
} 

}

Upvotes: 0

Views: 81

Answers (2)

Paul92
Paul92

Reputation: 9082

I am not able to reproduce your crash. Instead, I am able to reproduce an infinite loop. Taking a closer look to your while loops, it becomes evident: the value of i is never changing. If it cannot find a name match, it will keep incrementing the value of frank. So, a fix to this problem would be:

    while(i < SIZE && name1 != name) {
        name = girlsname[i];
        frank++;
        i++;
    }

But it can be improved: you don't need that assignment. Also, you can use the advantage of the postfix increment:

    while(i < SIZE && name1 != girlsname[i++]){
        frank++;
    }

Doing this, you also remove the necessity of name and name1.

Upvotes: 0

Ips
Ips

Reputation: 369

First, in any of your loops, you don't change the value of i, so they are potentially infinite.

Second, if I understand what you're trying to do, you have paired vectors and you search for an index on which the name is in the first vector and then use it to get the value from second vector. You can use std::find function for that:

int frank = find(girlsname.begin(), girlsname.end(), name1) - girlsname.begin();

Now, you can access the girlsfreq[frank] value. If the name is not present in the vector, the frank equals size of the vector, which you have to check for. Don't forget to add include:

#include <algorithm>

Upvotes: 1

Related Questions