erase和remove区别
在这个案例中,template只能用typename,这样在print函数中才可以用到模板,而且main函数中vector需要实例化为类型erase和remove的区别在于rease是真正删除了元素,迭代器不能再访问了remove只是简单地把要remove的元素移到了容量的最后,迭代器还是可以访问的,不知道容器内部结构,所以无法做到真正删除templatevoid print(vector
   ·  
 在这个案例中,template只能用typename,这样在print函数中才可以用到模板,而且main函数中vector需要实例化为类型
erase和remove的区别在于rease是真正删除了元素,迭代器不能再访问了 
  remove只是简单地把要remove的元素移到了容量的最后,迭代器还是可以访问的,不知道容器内部结构,所以无法做到真正删除
template <typename T>
void print(vector<T>& a)
{
    // 打印容器a中的所有元素
    for (vector<T>::iterator it = a.begin(); it != a.end(); it++)
        cout << *it << " ";
    cout << endl;
}
int main()
{
    vector<int> array;
    array.push_back(1);
    array.push_back(2);
    array.push_back(3);
    array.push_back(3);
    array.push_back(4);
    array.push_back(5);
    array.erase(array.begin());                                  // 调用erase删除1
    print(array);
    vector<int>::iterator pos;
    pos = remove(array.begin(), array.end(), 2);                 // 调用remove删除2
    print(array);
    if ((pos + 1) == array.end())
    {
        cout << "(pos + 1) == array.end()" << endl;
    }
    remove(array.begin(), array.end(), 3);
    print(array);
    system("pause");
    return 0;
}更多推荐
 
 




所有评论(0)