c++ std::list 编译问题?与 list.end() 和 list.end() 有关 - 1

标签 c++ list

在下面的代码中。

int main() {
    list<int> m_list;
    m_list.push_back(1);
    list<int>::iterator it1 = (--m_list.end());   // it works, *it1 return 1;
    list<int>::iterator it2 = (m_list.end() - 1); // compile issue? 
}

有人解释为什么列表 (m_list.end() - 1) 有编译问题吗?为什么 (--m_list.end()) 可以? 如果我们换成其他的,vector,string。这两种情况都有效。

int main() {
    vector<int> m_vector;
    m_vector.push_back(1);
    vector<int>::iterator it1 = (--m_vector.end());   // both work
    vector<int>::iterator it2 = (m_vector.end() - 1); // both work 
}

最佳答案

这背后的原因是 list::end() 返回一个不支持这种操作的双向迭代器

来源:

http://www.cplusplus.com/reference/iterator/BidirectionalIterator/

另一方面,vector::end() 和 string::end() 返回一个支持此类操作的随机访问迭代器

http://www.cplusplus.com/reference/iterator/RandomAccessIterator/

编辑:

如果你真的想完成任务,使用std::prev()函数

list<int>::iterator it2 = (std::prev(m_list.end(), 1));

根据 Pete Becker 的建议, "std::prev 的第二个参数默认为 1"

所以,你也可以这样做:

list<int>::iterator it2 = (std::prev(m_list.end()));

关于c++ std::list 编译问题?与 list.end() 和 list.end() 有关 - 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900717/

相关文章:

c++ - 如何用c语言翻译openssl命令pbkdf2?

list - 为什么在具体化中将 clpfd 变量分配给实际值?

python - 为什么 zip 会更改我的列表?

java - 从java中的列表中获取值

python - 如何将字符串列表转换为每个元素都是其核心类型的新列表?

c++ - 将 void 转换为字节

c++ - cout 没有输出正确的数据

c++ - 递归正则表达式与boost匹配

c++ - C++ 中的默认构造函数与隐式构造函数

list - F#返回元组列表中中间值最大的3个元素元组