文章目录
1. list和vector的区别
list 和 vector 的区别:
- list不是连续存储的,list不可以使用下标访;
- vector值提供尾部插入删除push_back() pop_back()
list同时提供了头部插入删除 push_front() pop_front()- list提供一些可以直接使用的函数,
如 :
remove():用于删除元素
sort():用于对list中的元素进行排序
2. 初始化list
相关代码如下:
list<int> li;
for(int i=0; i<10; i++){
// li.push_back(i); // 尾插
li.push_front(i); // 头插
}
3. 利用迭代器遍历list元素
我们可以将迭代器的使用看作是获取list
中元素的指针,list.begin()
可以看作为获取该list的头节点地址,list.end()
可以看作为获取该list的最后一个元素的地址。
1. 遍历可被修改的list元素
list<int>::iterator it = li.begin(); // 迭代器
while(it != li.end()){
cout << *it << " ";
*it = 10+*it;
++it;
}
cout << endl;
2. 遍历不可被修改的list元素(const)
const list<int> cli = li;
list<int>::const_iterator cit = cli.cbegin(); //const型迭代器
while(cit != cli.cend()){
cout << *cit << " ";
++cit;
}
cout << endl;
4. list中一些可以直接使用的函数
remove()
:按值删除元素,如li.remove(15)
即为删除li中值为15的元素。
int main(){
list<int> li;
for(int i=0; i<10; i++){
// li.push_back(i);
li.push_front(i);
}
li.remove(5);
list<int>::iterator it = li.begin();
while(it != li.end()){
cout << *it << " ";
++it;
}
cout << endl;
}
sort()
:对list中的元素进行排序。
int main(){
list<int> li;
for(int i=0; i<10; i++){
// li.push_back(i);
li.push_front(i);
}
li.sort();
list<int>::iterator it = li.begin();
while(it != li.end()){
cout << *it << " ";
++it;
}
cout << endl;
}
advance()
: 移动迭代器指向,如advance(it, 2)
即是将it向后移动两个位置。
需注意的是还可以将移动长度设置为负数,如advance(it ,-2)
即是将it向前移动两个位置。
int main(){
list<int> li;
for(int i=0; i<10; i++){
// li.push_back(i);
li.push_front(i);
}
list<int>::iterator it = li.begin();
advance(it,2);
cout << *it << endl;
}
distance()
: 计算两者之间的距离 , 如distance(li.begin(), it)
即为计算it所指与列表第一个元素之间的距离,我们可以用该函求得it所指的下标。
int main(){
list<int> li;
for(int i=0; i<10; i++){
// li.push_back(i);
li.push_front(i);
}
list<int>::iterator it = li.begin();
++it;
cout << distance(li.begin(), it) << endl;
}
5. c++11 中遍历list元素
在c++中可以直接使用for(int n:li)
来遍历list元素,具体代码如下:
int main(){
list<int> li;
for(int i=0; i<10; i++){
// li.push_back(i);
li.push_front(i);
}
for(int n:li){
cout << n << " ";
}
cout << endl;
}