0
我正在打開文件並讀取10k名稱的列表。一旦我把它放入一個數組(名稱[]),然後我需要搜索數組,並查看名稱是否與輸入的字符串匹配,如果是這樣,那麼我需要將這些匹配放入一個向量(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的形式。我知道數組正在獲取名稱。
幫助?謝謝!
凡'names'定義爲比較?不是我希望的全局變量。而且你的代碼效率低下 - 它會產生大量的字符串副本。如果重複使用的向量傳遞給你的函數,你可能想清除'vsFirst'(取決於你想要的行爲) –