简体   繁体   English

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

[英]Delete an element in a vector of lists and display the current list

I am trying to use a vector of lists to store information and then delete the middle item in the lists and print the list again. 我正在尝试使用列表向量来存储信息,然后删除列表中的中间项目并再次打印列表。 I am not sure how to access the individual variables of the lists stored in vector, or how to delete the element. 我不确定如何访问vector中存储的列表的各个变量,或者如何删除元素。

I am trying to delete the element 'puppy' from the list. 我正在尝试从列表中删除元素“ puppy”。

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

Current Code- 当前代码

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

It is still printing all 3 values. 它仍在打印所有3个值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM