【问题标题】:One variable for either iterator or reverse_iterator? [duplicate]iterator 或 reverse_iterator 的一个变量? [复制]
【发布时间】:2019-01-03 19:24:09
【问题描述】:

我想在 for 循环中遍历一些 std::vectors,但根据某些条件,向量应向前或向后迭代。我想,我可以通过使用普通迭代器或反向迭代器轻松做到这一点:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec{0, 1, 2, 3, 5, 6, 7};
    bool reverse = true;
    std::iterator<random_access_iterator_tag, int> it, end_it;

    if (reverse) {
      it = vec.rbegin();
      end_it = vec.rend();
    } else {
      it = vec.begin();
      end_it = vec.end();
    }

    for (; it != end_it; it++) {
        cout << *it << ", ";
    }
    return 0;
}

但不幸的是,vector::begin()vector::rbegin() 似乎没有使用相同的父类。是否有另一种方法可以在 if-else 结构中没有两个不同的循环的情况下做我想做的事?当然我可以为循环体创建一个函数/lambda,或者使用一些索引算法,但是有没有更优雅的方法?

编译器抱怨赋值it = vec.begin(),因为它们是不同的类型。 gcc 和 VC++ 输出不同的错误,并且似乎对vector::begin 的返回值使用了不同的类型。

【问题讨论】:

  • 我不认为这是一个骗局。链接的问题是关于从反向迭代器到迭代器的转换,这个问题 - 关于遍历容器的统一方式。
  • @Sven 好的,很酷。那么你的意思是它似乎没有使用相同的父类?是什么错误让你这么说?
  • 正如问题中建议/思考的那样,我会使用模板 lambda,例如 [](auto it, auto end_it) { for(; it != end_it; ++it) cout &lt;&lt; *it &lt;&lt; ", ";
  • @CodeMonkey 我稍微编辑了我的问题。我切换到 repl.it 作为一个小型测试环境,现在我看到 VC 和 gcc 有不同的错误,但都是因为类型不兼容。

标签: c++ for-loop iterator stdvector reverse-iterator


【解决方案1】:

不确定是否更好,你会接受没有 std::iterator 的解决方案,但我认为这稍微优雅一些​​:

#include <iostream>
#include <vector>

using namespace std;

int main() {
vector<int> vec{0, 1, 2, 3, 4, 5, 6};
bool reverse = true;

for(int i: vec){
    if(reverse) 
        cout << vec[vec.size()-i] << endl;
    else 
        cout << vec[i] << endl;
  }
}

不是很有效,因为您必须在每个循环中检查是否。

【讨论】:

  • 这不是我想要做的。向量中的数字只是一个示例,不应用作索引(顺便说一句,我的数字 4 丢失了)。不同方向的穿越才是我想要的。
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 2017-09-07
  • 2012-03-04
  • 1970-01-01
  • 2019-03-05
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多