基于循环索引的范围

时间:2016-11-02 21:07:39

标签: c++ iterator compiler-optimization

std :: vector上的自定义迭代器返回以下类的对象:

class chunk {
public:
    int    value_;
    size_t fake_index_;
};

迭代器同时更新fake_index_value_

之后我用迭代器创建一个范围类。然后在范围基础上循环范围类,我只使用value_,但不使用fake_index_

这是否意味着编译器会优化迭代器对fake_index_的更新?

测试代码(包含所有迭代器内容......)

#include <vector>
#include <iterator>

class Iterator;

class Chunk {

public:
    int value_;
    int base_bit_index_;
    int real_index_;
    std::vector<int>& data_;
    Chunk (std::vector<int>& data, size_t real_index)
            : data_{data}
    {
        base_bit_index_ = real_index*sizeof(int);
        real_index_ = real_index;
        value_ = data[real_index_];
    }
    int value() { return value_; }
private:
    void increment_index() {
        ++real_index_;
        base_bit_index_ += sizeof(int);
        value_ = data_[real_index_];
    }
    friend class Iterator;
};

class Iterator : public std::iterator<std::input_iterator_tag, int>
{
private:
    Chunk chunk_;
public:
    Iterator(Chunk chunk) :chunk_(chunk) {}
    Iterator(const Iterator& mit) : chunk_(mit.chunk_) {}
    Iterator& operator++() {
        chunk_.increment_index();
        return *this;
    }
    Iterator operator++(int) {Iterator tmp(*this); operator++(); return tmp;}
    bool operator==(const Iterator& rhs)
    {
        return chunk_.real_index_== rhs.chunk_.real_index_;
    }
    bool operator!=(const Iterator& rhs)
    {
        return !(operator==(rhs));
    }
    Chunk& operator*() {return chunk_;}
};
class Range
{
private:
    std::vector<int>& data_;
public:
    Range(std::vector<int>& data)
        : data_{data}
    {
    }
    Iterator begin()
    {
        Chunk chunk(data_, 0);
        Iterator tmp(chunk);
        return tmp;
    }
    Iterator end()
    {
        Chunk chunk(data_, data_.size());
        Iterator tmp(chunk);
        return tmp;
    }
};
int main()
{
    std::vector<int> v1;
    v1.resize(100);
    std::vector<int> v2;
    Range X(v1);
    for (auto chunk : X) {
        v2.push_back(chunk.real_index_);
    }
}

gcc godbolt

测试代码(没有所有迭代器的东西)

#include <vector>
#include <iostream>
int main()
{
    std::vector<int> v2;
    for (size_t i = 0; i < 100; ++i) {
        v2.push_back(i);
        // std::cout<<i<<"\n";
    }
}

gcc godbolt

我的第一印象:无论如何,看起来迭代器糟透了。

0 个答案:

没有答案