从向量中删除和添加字符串

Removing & adding strings from a vector

本文关键字:添加 字符串 删除 向量      更新时间:2023-10-16

我是C++新手,我只是想知道如何从向量中删除和添加字符串。我已经尝试了几种实现,但该程序似乎无法正常工作。

//allows the user to list thier top 10 video games
cout << "Please list your Top 10 favourite video games below.n";
string gameTitle;
vector<string> gameList(10);
cin >> gameTitle;
gameList.insert(gameList.begin(), gameTitle);
//prints out the game list
vector<string>::iterator iterGameList;
cout << "Your Top 10 video games are:n";
for (iterGameList = gameList.begin(); iterGameList != gameList.end() ++iterGameList)
{
    cout << *iterGameList << endl;
}
//allows the use to remove a game title from the list

对此的任何帮助将不胜感激。附言我是否必须通过迭代器将 find() 传递给 erase()。

到目前为止

,将项目添加到vector的最常见方法是使用 push_back ,如下所示:

vector<string> gameList;
for (int i=0; i<10; i++) {
    std::string game;
    std::cin >> game;
    gameList.push_back(game);
}

要删除您使用的项目,请erase .例如,要删除矢量中当前的所有项目,您可以使用:

gameList.erase(gameList.begin(), gameList.end());

。尽管擦除所有内容是一项足够常见的操作,但clear()可以做到这一点。

而不是gameList.insert(gameList.begin(), gameTitle);

使用gameList.push_back(gameTitle);

有关push_back的信息,请查看文章:http://www.cplusplus.com/reference/vector/vector/push_back/