加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么我不能在列表迭代器上使用=运算符?

发布时间:2020-12-16 10:55:13 所属栏目:百科 来源:网络整理
导读:我有一个来自std :: list std :: string的迭代器,但是当我尝试使用=来推进它时,我得到一个编译错误. 代码是: #include list#include iostream#include stringint main() { std::liststd::string x; x.push_front("British"); x.push_back("character"); x.p
我有一个来自std :: list< std :: string>的迭代器,但是当我尝试使用=来推进它时,我得到一个编译错误.

代码是:

#include <list>
#include <iostream>
#include <string>
int main() {
    std::list<std::string> x;

    x.push_front("British");
    x.push_back("character");
    x.push_front("Coding is unco");
    x.push_back("Society");
    x.push_back("City Hole");
    auto iter = x.begin();
    iter += 3;
    //std::advance(iter,3);
    x.erase(iter);

    for (auto &e: x) {
        std::cout << e << "n";
    }
}

如果我使用clang -std = c 11 -o li li.cpp编译它,我得到:

li.cpp:13:10: error: no viable overloaded '+='
    iter += 3;
    ~~~~ ^  ~
1 error generated.

为什么我不能使用=这个迭代器?

解决方法

std::list的迭代器是 BidirectionalIterator,它不支持operator = like RandomAccessIterator.

您可以使用InputIterator(包括BidirectionalIterator)支持的运算符

++iter;
++iter;
++iter;

但它很难看.最好的方法就是你所评论的,使用std::advance(或std::next(自C 11)),它可以与InputIterator(包括BidirectionalIterator)一起使用,并且还利用RandomAccessIterator支持的功能.

(强调我的)

Complexity

Linear.

However,if InputIt additionally meets the requirements of
RandomAccessIterator,complexity is constant.

所以你可以在不考虑迭代器类别的情况下使用它,std :: advance将为你做最好的选择.例如

std::advance(iter,3);

要么

iter = std::next(iter,3);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读