0

I am opening a file and reading in a list of 10k names. Once I have that placed into an array (names[]), I then need to search through the array, and see if names match an entered string, and if so, I then need to place those matches into a vector (vsFirst). This is pretty easy, but I am getting a vector subscript out of range. Here's my code for this portion:

bool NameSearch::FindLastNames(vector<string> &vsFirst, string n)
{
    name = n;
    int count = 0;
    for (int i = 0; i < total; i++)
    {
        string holder = names[i];
        string find = name;
        cout << holder;
        int index = holder.find_first_of(",");
        if ((holder.rfind(find, index)) && holder.rfind(find, index)<=  holder.length())
        {
            cout << "it was found";
            vsFirst.push_back(holder);
            bReady = true;
        }
    }
    return bReady;
} 

What am I doing wrong? I've run some tests and it doesn't look like it's even making it into the for loop. My call to the function is:

vector<string> lastNames;


nSearch.FindLastNames(lastNames, searchTerm);

All names in the array are of the form lastname, firstname. I know the array is getting loaded with the names.

Help? Thank you!

1
  • Where is names defined? Not a global variable I hope. Also your code is inefficient - it makes a lot of string copies. You may want to clear vsFirst in case a reused vector is passed to your function (depending on what behavior you want) Commented Oct 14, 2015 at 3:06

1 Answer 1

1

To check if substring is found or not you need to compare with std::string::npos

change

if ((holder.rfind(find, index)) && holder.rfind(find, index)

to

if (holder.rfind(find, index) != std::string::npos && holder.rfind(find, index) != std::string::npos)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.