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

Removing & adding strings from a vector

我是 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

如有任何帮助,我们将不胜感激。 P.S。我是否必须通过迭代器将 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/