链表 list

list容器具有如下特性:
可以在头部和尾部插入和删除元素
不能随机访问元素,也就是迭代器只能只能++,不能一次性跳转

初始化

list的基本操作

int main(int argc, const char * argv[]) {

//创建list对象
list<int> l;

//尾部添加元素
for (int i = 0; i < 10; i++) {
    l.push_back(i);
}

//头部添加元素
l.push_front(111);

//遍历
for (list<int>::iterator it = l.begin(); it != l.end(); it++) {
    cout << *it << " ";
}
cout << endl;

//list不能随机访问
list<int>::iterator it = l.begin();
it++;
it++;
cout << *it <<endl;

// it = it + 1; //编译报错,不能随机访问
// it = it + 5; //编译报错,不能随机访问

return 0;

}

list的删除
list提供了两个函数用来删除元素,分别是erase和remove。

erase是通过位置或者区间来删除,主要结合迭代器指针来操作

remove是通过值来删除

int main(int argc, const char * argv[]) {

//创建list对象
list<int> l;

//添加数据
for (int i = 0; i < 10; i++) {
    l.push_back(i);
}
l.push_back(100);
l.push_back(100);

//删除头部元素
l.erase(l.begin());

//删除某个区间
list<int>::iterator it = l.begin();
it++;
it++;
it++;
l.erase(l.begin(), it);

//移除值为100的所有元素
l.remove(100);

//遍历
for (list<int>::iterator it = l.begin(); it != l.end(); it++) {
    cout << *it << " ";
}
cout << endl;

return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/87966530