【发布时间】:2018-04-10 21:26:04
【问题描述】:
我正在尝试使用列表向量来存储信息,然后删除列表中的中间项并再次打印列表。我不确定如何访问存储在向量中的列表的各个变量,或者如何删除元素。
我正在尝试从列表中删除元素“小狗”。
#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;
int main() {
vector<list<string>> hashT;
hashT.resize(3);
int index = 0;
hashT[0].push_back("hello");
hashT[0].push_back("Puppy");
hashT[0].push_back("friend");
typename list<string>::iterator it = hashT[0].begin();
for (; it != hashT[0].end(); ++it)
{
index = 0;
//print lists?
cout << *it;
//delete puppy?
hashT[0].erase(hashT[0].begin() + index)
//print list?
index++;
}
return 0;
}
当前代码-
#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;
int main() {
vector<list<string>> hashT;
hashT.resize(3);
int index = 0;
hashT[0].push_back("hello");
hashT[0].push_back("Puppy");
hashT[0].push_back("friend");
typename list<string>::iterator it = hashT[0].begin();
for (; it != hashT[0].end(); ++it)
{
if(*it == "Puppy")
{
hashT[0].erase(it);
}
}
typename list<string>::iterator it2 = hashT[0].begin();
for (; it2 != hashT[0].end(); ++it2)
{
cout << *it2;
}
return 0;
}
它仍在打印所有 3 个值。
【问题讨论】:
-
hashT[0].push_back("hello");这已经表现出未定义的行为。hashT是空的,没有元素。hashT[0]访问超出范围的索引。 -
@IgorTandetnik 我做了 hashT.resize(3) ,现在它打印(谢谢)我将如何删除一个元素。我将编辑调整大小的代码。
-
如何删除 which 元素?完全不清楚您要达到的目标。
-
@IgorTandetnik 试图从列表中选择元素小狗
-
拥有一个列表向量肯定是一个坏主意。你是怎么想到的?