在搜索字符串时,Vector下标超出了范围

Vector subscript out of range when searching for a string

本文关键字:范围 下标 Vector 搜索 字符串      更新时间:2023-10-16

我正在打开一个文件并读取10k个名字的列表。一旦我将其放入数组(names[])中,我就需要搜索数组,并查看名称是否与输入的字符串匹配,如果匹配,则需要将这些匹配放入向量(vsFirst)中。这很简单,但是我得到了一个超出范围的向量下标。下面是这部分的代码:

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

我做错了什么?我做了一些测试,看起来它甚至没有进入for循环。我对函数的调用是:

vector<string> lastNames;

nSearch.FindLastNames(lastNames, searchTerm);

数组中的所有名字都是lastname, firstname的形式。我知道数组正在加载名字

帮助吗?谢谢你!

要检查是否找到子字符串,您需要与std::string::npos进行比较

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

if (holder.rfind(find, index) != std::string::npos && holder.rfind(find, index) != std::string::npos)