我正在尝试找到一种方法来搜索向量以查找用户输入的字符串。不知道如何开始。一旦找到字符串,我必须删除它的索引并打印索引中的其余字符串。
void addNames(vector<string>& names)
{
names.push_back("Seppi");
names.push_back("Farrell");
names.push_back("Burton");
}
void print(vector<string> names)
{
for (int i = 0; i < names.size(); i++)
{
cout << names[i] << endl;
}
}
int findName(vector<string> names, string nameToErase)
{
int return_value = -1;
names.find()
return return_value;
}
int main()
{
vector<string> names;
addNames(names);
string nameToErase;
cin >> nameToErase;
int indexFound = findName(names, nameToErase);
}
答案 0 :(得分:0)
有std :: find方法。 实施例
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
vector< string > v;
v.push_back( "AAAA" );
v.push_back( "BBBB" );
v.push_back( "BBBB1" );
v.push_back( "BBBB33" );
vector< string >::iterator i = find( v.begin(), v.end(), "BBBB1" );
if( i != v.end() )
{
cout << "Found " << *i << " on index " << i - v.begin() << endl;
}
else
{
cout << "Not found" << endl;
}
return 0;
}
答案 1 :(得分:0)
此方法可以使用
void findAndErase(vector<string> & names, string nameToErase) {
vector<string>::iterator pos = std::find(names.begin(), names.end(), nameToErase);
if (pos != names.end())
names.erase(pos);
}