R
R
rollthebones2021-10-11 09:57:16
C++ / C#
rollthebones, 2021-10-11 09:57:16

How to create your own iterator for a vector in a template class?

There is a task, to write a template container class in which the data should be stored in the form of one of the STL collections. I chose to store them in a std::vector.
I need to write my own bidirectional iterator, which will overload the increment operator (++), so that the iterator iterates through the vector and takes every third element. The problem is that no matter how I try to write it, nothing happens with my already written class.
There I have a printEachThirdElement method, which just prints every third element of the vector, but this needs to be implemented as its own iterator. Please help.

Template class code

#include <iostream>
#include <vector>
#include <algorithm>
template <typename T>
class MyVector {
 public:
    MyVector() : vector() {
    }
 
    MyVector(const T& value) : vector() {
        vector.push_back(value);
    }
 
 
    void info() const {
        std::cout << "[ ";
        for (auto &v : vector) {
            std::cout << v << " ";
        }
        std::cout << "]" << std::endl;
    }
 
    std::int32_t size() const {
        return vector.size(); 
    }
 
    void addElement(const T& value) {
        vector.push_back(value);
    }
 
    void removeElements(const T& value) {
        vector.erase(std::remove(vector.begin(), vector.end(), value), vector.end());
    }
 
    void printEachThirdElement() const {
        for (auto i = vector.begin() + 2; i < vector.end(); i+=3) {
            std::cout << *i << " ";
        }
        std::cout << std::endl;
    }
 
 private:
    std::vector<T> vector;
};



main() function code

int main() {
    MyVector<int> vInt;
 
    vInt.addElement(5);
    vInt.addElement(6);
    vInt.addElement(7);
    vInt.addElement(5);
    vInt.addElement(15);
    vInt.addElement(12);
    vInt.addElement(5);
    vInt.addElement(51);
    vInt.addElement(666);
    vInt.addElement(5);
    vInt.addElement(15);
    vInt.addElement(12);
    vInt.addElement(5);
    vInt.addElement(51);
    vInt.addElement(666);
 
    std::cout << "Each 3 element" << std::endl;
    vInt.printEachThirdElement();
 
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-10-11
@rollthebones

You actually need to implement an iterator for your class and return iterators in begin() and end(). Here is the first article from Google, in which the iterator is implemented step by step.
You only need to rewrite the increment operators to skip elements. Well, carefully count the end iterator so that successive increments from begin do not skip it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question