Range Based on Cycle Index

The custom iterator on std :: vector returns an object of the following class:

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

The iterator updates both fake_index_and value_.

After that, I create a range class with an iterator. Then in the range base for the loop over the range class I use only value_, but not fake_index_.

Does this mean that the compiler optimizes updating the iterator fake_index_?

Test code (with all iterator files ...)

#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

Test code (without all iterator contents)

#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

My first impression is that the iterator seems to suck anyway.

+4
source share

No one has answered this question yet.

Source: https://habr.com/ru/post/1659655/


All Articles