C++容器:list

C++容器:list,第1张

C++容器:list

文章目录
  • 1. list和vector的区别
  • 2. 初始化list
  • 3. 利用迭代器遍历list元素
      • 1. 遍历可被修改的list元素
      • 2. 遍历不可被修改的list元素(const)
  • 4. list中一些可以直接使用的函数
  • 5. c++11 中遍历list元素


1. list和vector的区别

list 和 vector 的区别:

  1. list不是连续存储的,list不可以使用下标访;
  2. vector值提供尾部插入删除push_back() pop_back()
    list同时提供了头部插入删除 push_front() pop_front()
  3. list提供一些可以直接使用的函数,
    如 :
    remove():用于删除元素
    sort():用于对list中的元素进行排序
2. 初始化list

相关代码如下:

    list 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::iterator it = li.begin();  // 迭代器
    while(it != li.end()){
        cout << *it << " ";
        *it = 10+*it;
        ++it;
    }
    cout << endl;

2. 遍历不可被修改的list元素(const)
    const list cli = li;
    list::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 li;
    for(int i=0; i<10; i++){
        // li.push_back(i);
        li.push_front(i);
    }
    li.remove(5);
    list::iterator it = li.begin();
    while(it != li.end()){
        cout << *it << " ";
        ++it;
    }
    cout << endl; 
}  

sort():对list中的元素进行排序。

int main(){
    list li;
    for(int i=0; i<10; i++){
        // li.push_back(i);
        li.push_front(i);
    }
    
    li.sort();

    list::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 li;
    for(int i=0; i<10; i++){
        // li.push_back(i);
        li.push_front(i);
    }
    list::iterator it = li.begin();
    advance(it,2);
    cout << *it << endl;   
}

distance(): 计算两者之间的距离 , 如distance(li.begin(), it)即为计算it所指与列表第一个元素之间的距离,我们可以用该函求得it所指的下标。

int main(){
    list li;
    for(int i=0; i<10; i++){
        // li.push_back(i);
        li.push_front(i);
    }
    list::iterator it = li.begin();
    ++it;
    cout << distance(li.begin(), it) << endl;   
}
5. c++11 中遍历list元素

在c++中可以直接使用for(int n:li)来遍历list元素,具体代码如下:

int main(){
    list li;
    for(int i=0; i<10; i++){
        // li.push_back(i);
        li.push_front(i);
    }
    
    for(int n:li){
        cout << n << " ";
    }
    cout << endl;

}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5692775.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存