简体   繁体   English

从std :: vector删除Element <std::string> &gt;

[英]Remove Element from std::vector<std::string> >

My compiler complains. 我的编译器抱怨。

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

int main(){

        vector<string> vec[2];
        vec[0].push_back("test1");
        vec[0].push_back("test2");

        cout << vec[0][0] << endl;
        vec[0].erase(vec.begin());
        cout << vec[0][1] << endl;

}

What is wrong when I call erase? 我打电话给擦除时怎么了?

vec is an array of vector<string> s. vecvector<string>的数组。 I believe you meant vec[0].begin() like so: 我相信您的意思是vec[0].begin()像这样:

vec[0].erase(vec[0].begin());
    vec[0].erase(vec[0].begin());
    cout << vec[0][1] << endl;

After you erased the first element, there's only one left. 删除第一个元素后,只剩下一个。 This one element is at position 0, which means index 1 is off bounds -> undefined behaviour. 这个元素位于位置0,这意味着索引1越界->未定义的行为。

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

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