删除列表矢量中的元素并显示当前列表

时间:2017-10-29 22:56:17

标签: c++ list vector iteration

我正在尝试使用列表向量来存储信息,然后删除列表中的中间项并再次打印列表。我不知道如何访问存储在vector中的列表的各个变量,或者如何删除该元素。

我正在尝试从列表中删除元素'puppy'。

V

当前代码 -

#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;
}

它仍在打印所有3个值。

1 个答案:

答案 0 :(得分:0)

#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;

int main() {

    vector<list<string>> hashT;
    hashT.resize(3);


    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);
            break;
        }
    }

    typename list<string>::iterator it2 = hashT[0].begin();

    for (; it2 != hashT[0].end(); ++it2)
    {
        cout << *it2;
    }
    cout << endl;


    return 0;
}
相关问题