从向量中删除和添加字符串
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
对此的任何帮助将不胜感激。附言我是否必须通过迭代器将 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/
相关文章:
- 重载加法运算符(使用函数向对象添加字符串)
- 在不使用内置库函数的情况下添加字符串,我做错了什么?
- 添加字符串和文字(C++)
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 添加字符串向量和不同数据类型向量的映射
- 在链接列表中添加字符串的简单方法
- 列表框中的添加字符串 (MFC)
- 添加字符串和文字,顺序如何影响是否可以正确添加字符串
- 向矢量集添加字符串时出现问题<string><>
- 在C++中添加字符串和文字时出现问题
- free():添加字符串时指针无效
- 为什么通过添加字符串文字和char初始化时,为什么不打印字符串
- 矢量尝试添加字符串时会崩溃
- 在数组 C++ 中添加字符串
- 如何添加字符串
- 从向量中删除和添加字符串
- 添加字符串和列表到c++中的映射
- 添加字符串变量后的两个不同的双值
- 为什么我的非所有者绘制的列表框在添加字符串后会出现绘图问题
- 当试图向结构中添加字符串时,程序中断