I need to create an iterator able to "find" a value base on input criteria. I am currently stumped on how I should approach this. (Custom vector class)
Here's my code for my iterator
class iterator {
public:
//Variables
int _index;
vector* _v;
//Constructors
iterator() : _index(0), _v(0) { }
iterator(int index, vector * vec) : _index(index), _v(vec) { }
//Functions
iterator& operator=(const iterator& itr){
_v = itr._v;
_index = itr._index;
return *this;
}
friend bool operator==(const iterator& itr_a, const iterator& itr_b){
return (itr_a._index == itr_b._index && itr_a._v == itr_b._v);
}
friend bool operator!=(const iterator& itr_a, const iterator& itr_b){
return !(itr_a == itr_b);
}
iterator& operator++ () { _index++; return *this; }
iterator& operator++ (int) { _index++; return *this; }
iterator& next() { _index++; return *this; }
int& operator*() { return (*_v)[_index]; }
};
Now this iterator code works then trying to use
for(vector::iterator i = vec.begin(); i != vec.end(); i++) std::cout << *i std::end;
Though now I need to create a "find" function in my main class (vector) that can wort with this following code
vector::iterator i = vec.find(5); //Prints out "5" x amount of times
for(; j != vec.end(); j.next()) std::cout << *j << std::endl;
The only issue I find confusing is, since in my iterator class next is classified as "add 1 to index", though if I return an iterator find, it's next would still be "add 1 to index" versus "find next value of element".
How can I go about trying to achieve this? It feels like a super simple answer. (Note, yes this is a school assignment to replicate features of std::vector, I will template my code eventually, I want to make it work with default ints first)
Related
What is the right way to implement an iterator that iterates over a Recordset provided below in C++ style?
class Recordset
{
public:
Recordset(const Recordset&) = delete;
Recordset& operator = (const Recordset&) = delete;
Recordset(Recordset&& other) noexcept = default;
Recordset& operator = (Recordset&&) = default;
//Moves to the next record. Returns false if the end is reached.
bool Next();
//Gets the current record as an instance of type T.
template <class T>
void Get(T& val);
};
my idea is that I probably do something like this:
template <class T>
class Iterator
{
public:
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
Iterator() = default;
Iterator(Recordset s) : m_i(std::move(s))
{
try_next();
}
Iterator(const Iterator&) = delete;
Iterator& operator = (const Iterator&) = delete;
Iterator(Iterator&& other) = default;
Iterator& operator = (Iterator&& other) = default;
T* operator-> () { return cur(); }
T* operator* () { return cur(); }
bool operator== (const Iterator& other) const noexcept
{
//They both are end().
return !m_v && !other.m_v;
}
bool operator!= (const Iterator& other) const noexcept
{
return !operator==(other);
}
Iterator& operator++ ()
{
this->try_next();
return *this;
}
Iterator operator++ (int)
{
Iterator tmp = *this; //would not compile.
this->try_next();
return tmp;
}
private:
bool try_next()
{
if (m_i.Next())
{
T val;
m_i.Get(val);
m_v = val;
return true;
}
return false;
}
T* cur()
{
T& val = *m_v;
return &val;
}
Recordset m_i;
std::optional<T> m_v;
};
template <class T>
std::ranges::subrange<Iterator<T>> make_range(Recordset& s)
{
return std::ranges::subrange(Iterator<T>(s), Iterator<T>{});
}
and use it as follows:
struct Record { int x; std::string y; };
int main()
{
Recordset s;
for (Record& r : make_range(s))
{
std::cout << r.x << r.y << std::endl;
}
return 0;
}
The frist question is how do I implement Iterator operator++ (int) if both Recordset and Iterator are move-only? (temp and this can't point to different records, because there is only one current record in the recordset). Does C++20 require it?
The second question is it a good idea to implement end() in this way? (end() is a simply an iterator containing an empty optional)
Single pass move-only input iterators (A c++20 std::input_iterator) are only required to be weakly incremental, where (void) ++i has the same effect as (void) i++. You can simply have void operator++(int) { ++*this; }. Older requirements for iterators (Cpp17InputIterator) requires iterators to be copyable, and require operator++ to return that copy.
And for your second question, you might want to use a sentinel type, something like:
template<typename T>
bool operator==(const Iterator<T>& it, std::default_sentinel_t) {
return !it.m_v;
}
// != can be rewritten from ==, so no need to write one
template <class T>
auto make_range(Recordset& s)
{
return std::ranges::subrange(Iterator<T>(s), std::default_sentinel);
}
And if you need to work with a algorithm that can't use separate sentinel types, use ranges::common_view. Your current solution also works, except you need to have this == &other || (!m_v && !other.m_v);.
The other day I wanted to try writing my own iterators for a vector, of course, the most primitive example, since there is a lot of confusing code in the c++ standards. So the usual iterator for a vector in the forward direction works fine, but there was a problem with the reverse iterator. I have it completely built on the base iterator, only I changed / inverted the operators specifically for the reverse iterator.
template<typename Vector>
class VectorRevIterator : public VectorIterator<Vector> //This is normal (work) vector iterator
{
public:
using Base = VectorIterator<Vector>;
VectorRevIterator(PointerType ptr) noexcept : Base(ptr) {};
VectorRevIterator(const VectorRevIterator& other) : Base(other) { *this = other; };
VectorRevIterator& operator++()
{
Base::operator--(); //--ptr;
return *this;
}
VectorRevIterator operator++(int)
{
VectorRevIterator itr = *this;
Base::operator--(); //--*this;
return itr;
}
VectorRevIterator& operator--()
{
Base::operator++(); //++ptr;
return *this;
}
VectorRevIterator operator--(int)
{
VectorRevIterator itr = *this;
Base::operator++(); //++*this;
return itr;
}
VectorRevIterator& operator+=(const PointerType otherPtr)
{
Base::operator-=(otherPtr); //ptr -= otherPtr;
return *this;
}
VectorRevIterator operator+(const PointerType otherPtr)
{
VectorRevIterator itr = *this;
Base::operator-(otherPtr); // itr -= otherPtr
return *this;
}
VectorRevIterator& operator-=(const PointerType otherPtr) { return Base::operator+=(otherPtr); }
VectorRevIterator operator-(const PointerType otherPtr) { Base::operator+(otherPtr); }
ReferenceType operator*() const { return *ptr; }
PointerType operator->() const { return std::_Const_cast(Base::operator->()); }
};
Access to iterator from Vector:
template<typename T>
class Vector
{
public:
using ValueType = T;
using PointerType = ValueType*;
using ReferenceType = ValueType&;
using ReverseIterator = VectorRevIterator<Vector<T>>;
public:
T* data;
size_t size;
size_t capacity;
...
// construct/destructor
// custom allocator
// index operators
...
ReverseIterator rBegin() { return ReverseIterator(data + size); }
ReverseIterator rEnd() { return ReverseIterator(data); }
};
The problem itself is that when I try to go through all the elements in the opposite direction VectorRevIterator. When trying to output all this to the console, it seems to shift one element forward and does not see/cannot read the characters of the first element. But then output all the elements, only without the last one.
Here a example:
Vector<String> values;
values.emplaceBack("1");
values.emplaceBack("2");
values.emplaceBack("3");
values.emplaceBack("4");
values.emplaceBack("5");
Vector<String>::ReverseIterator revIt = values.rBegin();
// output with spdlog
for (revIt; revIt != values.rEnd(); ++revIt)
INFO(*revIt); // error on first iteration, but print only 1, 2, 3, 4
// ouput with std::cout
for (revIt; revIt != values.rEnd(); ++revIt)
std::cout << *revIt << std::endl; // doesn't print anything
How solve this problem? To make reverse iterator it just need to revert operators ++ -- += -= and rBegin rEnd functions. Or maybe im forgotten about something?
rBegin() returns an iterator to the first element:
ReverseIterator rBegin() { return ReverseIterator(data + size); }
But it's pointing one element beyond the end and can't be dereferenced. You need to dereference the element before it.
You could therefore adjust the dereference operator in the VectorRevIterator version:
ReferenceType operator*() const { return *std::prev(ptr); }
I am trying to handle std::list of pointer type, like this:
std::list<int*> pNums;
Originally, iterating this container with range-based for loop will look like this :
for(int* pNum : pNums)
{
std::cout << (*pNum) << std::endl;
}
However, I want to iterate this container with a value, not a pointer, like below:
for(int num : Range(pNums))
{
std::cout << num << std::endl;
}
|
Here, Range is a custom wrapping-class of std::list<int*>, something should be defined in this manner, I guess:
class Range
{
Range(std::list<int*>& _list) : list(_list) {}
std::list<int*>& list;
// Basically inherit the original iterator
class custom_const_iterator : std::list<int*>::const_iterator
{
// Define an overloaded dereference operator
const int& operator*() const
{
...
}
...
};
public:
custom_const_iterator begin() { return ...; }
custom_const_iterator end() { return ...; }
};
So, my question is, what should I write down for class Range?
I would take the following approach (explanation in the comments):
class Range
{
private:
// Store iterators to the begin and the end of the range,
// rather than a reference to the whole list
std::list<int*>::const_iterator first;
std::list<int*>::const_iterator last;
class iterator
{
private:
std::list<int*>::const_iterator it;
public:
explicit iterator(std::list<int*>::const_iterator i) : it(i) {}
// you should define all the other operators
// that a std::list iterator has!
iterator& operator++()
{
++it;
return *this;
}
iterator operator++(int)
{
it++;
return *this;
}
// just dereference to get the value
const int& operator*() const { return **it; }
// these two are quite important for basic functionality
bool operator==(const iterator& rhs) const { return it == rhs.it; }
bool operator!=(const iterator& rhs) const { return it != rhs.it; }
};
public:
Range(std::list<int*>& _list)
: first(_list.begin()), last(_list.end())
{}
public:
iterator begin() { return iterator(first); }
iterator end() { return iterator(last); }
};
i have to implement a forward iterator on a stack based on arrays. I can't use std::vectors or anything, i just need that. My development of this program stopped when i begun with forward iterator, and in particular with the operators.
I have a method that takes a generic sequence, and from that, given an offset, creates a stack:
template <typename IterT>
stack(IterT begin, IterT end) : _stack(0), _size(0), _capacity(0) {
try {
for(; begin!=end; ++begin) {
push(static_cast<T>(*begin));
}
}
catch(...) {
clear(); //my method to destroy the stack
throw;
}
}
In my main i do the following:
int a[5] = {1, 2, 3, 4, 5};
stack<int> sint(a, a+5);
cout << sint << endl;
But when the code runs the stack is created but not printed. Can somebody help me? And also give me other helps(on code indentation, improvements, etc...) Thank you, I will post the iterator code forward.
class const_iterator {
const T* data;
unsigned int index;
public:
typedef std::forward_iterator_tag iterator_category;
typedef T value_type;
typedef ptrdiff_t difference_type;
typedef const T* pointer;
typedef const T& reference;
const_iterator() : data(0){}
const_iterator(const T* arr) : data(arr) {}
const_iterator(const const_iterator &other)
: data(other.data){ }
const_iterator& operator=(const const_iterator &other) {
data = other.data;
return *this;
}
~const_iterator() {
data = 0;
}
reference operator*() const {
return *data;
}
pointer operator->() const {
return &(data);
}
const_iterator operator++(int) {
const_iterator tmp(*this);
++*this;
return tmp;
}
const_iterator& operator++() {
++data;
return *this;
}
bool operator==(const const_iterator &other) const {
return data[index] == other.data[index];
}
bool operator!=(const const_iterator &other) const {
return data[index] != other.data[index] ;
}
private:
friend class stack;
const_iterator(unsigned int ind) :
index(ind){}
}; // class const_iterator
const_iterator begin() const {
cout << "begin" << _stack[_size-1] << endl;
return const_iterator(_stack[_size-1]);
}
const_iterator end() const {
cout << "end" << _stack[0] << endl;
return const_iterator(_stack[0]);
}
Last but not least i redefined the << operator to fit the iterator:
template <typename T>
std::ostream &operator<<(std::ostream &os, const stack<T> &st) {
typename stack<T>::const_iterator i, ie;
for(i = st.begin(), ie = st.end(); i!=ie; ++i){
os << *i << std::endl;
}
return os;
}
The code for the stack is the following (I omitted something for readability).
stack()
: _capacity(0), _size(0), _stack(0){}
void push (const T &value){
if (_size == _capacity){ //raddoppio la dimensione
if(_capacity == 0)
++_capacity;
_capacity *= 2;
T* tmp = new T[_capacity];
copy_n(_stack, _size, tmp);
swap(_stack, tmp);
delete[] tmp;
}
_stack[_size] = value;
++_size;
}
void pop(){
T _tmp;
if(!is_empty()){
_tmp = _stack[_size-1];
--_size;
}
}
If you want to create an iterator that looks like a pointer, you don't need index, because data plays its role. Comparison operator should compare datas, not values:
bool operator==(const const_iterator &other) const {
return data == other.data;
}
If you want to create a reverse iterator, it is slightly more complex. First, operator++ should decrement data. Second, dereference operator should return not *data, but *(data - 1). Third, data in the begin() iterator should point to stack[size], and data in the end() iterator should point to stack[0]. You don't need a destructor in any case.
I followed the previous advices and here's the edited result, still i can't figure out how to properly use the constructor in the private section
class const_iterator {
const T *data;
public:
/* ITERATOR TRAITS HERE */
const_iterator() : data(0){}
const_iterator(const T* arr) : data(arr) {}
const_iterator(const const_iterator &other)
: data(other.data){ }
const_iterator& operator=(const const_iterator &other) {
data = other.data;
return *this;
}
~const_iterator() {
data = 0;
}
reference operator*() const {
return *data;
}
pointer operator->() const {
return &(data);
}
const_iterator operator++(int) {
const_iterator tmp(*this);
++*this;
return tmp;
}
const_iterator& operator++() {
++data;
return *this;
}
bool operator==(const const_iterator &other) const {
return data == other.data;
}
bool operator!=(const const_iterator &other) const {
return data != other.data;
}
private:
friend class stack;
const_iterator(const T *d) {
data = d;
}
}; // classe const_iterator
const_iterator begin() const {
return const_iterator(_stack[_size-1]);
}
const_iterator end() const {
return const_iterator(_stack[0]);
}
I'm trying to make the iterator work properly, and for the inequality i != a.end().
I get the error
no know conversion from argument 2 from 'const a3::vector<int>::iterator' to 'const a3::vector<int>&
for the friend function. I need the function to check if the iterator is not equal to vector.end() and am unsure how I would do it.
Class
#include <iostream>
using std::cout;
using std::endl;
namespace a3
{
template <typename T>
class vector
{
public:
class iterator {
public:
int index_;
vector* a_;
iterator() : index_(-1), a_(0) {}
iterator(int index, vector* a) : index_(index), a_(a) {}
iterator& operator=(const iterator& itr)
{
a_ = itr.a_;
index_ = itr.index_;
return *this;
}
iterator& next() {
index_++;
return *this;
}
iterator& operator++() {
return next();
}
int& operator*() { return (*a_)[index_]; }
};
private:
T* mem_;
int sz_;
public:
vector(int sz) : sz_(sz), b_(0, this), e_(sz, this)
{
mem_ = new T[sz];
}
~vector() { delete[] mem_; }
const T& operator[](T i) const { return mem_[i]; }
T& operator[](T i) { return mem_[i]; }
const int& get_size() const { return sz_; }
const iterator& begin() { return b_; }
const iterator& end() { return e_; }
friend bool operator!=(const iterator& itr1, const vector<T>& vec1)
{
return !(itr1.index_ == vec1.end);
}
private:
iterator b_;
iterator e_;
};
}
Main Function
#include "a3_vector.cpp"
int main(int argc, char** argv)
{
using namespace a3;
vector<int> a(10); // allocate an int array of size 10
for (int i=0; i<10; ++i) a[i] = i*2;
// a now looks as follows
//0,2,4,6,8,10,12,14,16,18
// prints the content of the array
vector<int>::iterator i;
for (i = a.begin(); i != a.end(); i.next()) {
cout << *i << endl;
}
}
This is fundamentally wrong:
friend bool operator!=(const iterator& itr1, const vector<T>& vec1)
Iterator comparisons should compare iterators. What you want are comparison operators that look like this:
friend bool operator!=(const iterator& itr1, const iterator& itr2);
friend bool operator==(const iterator& itr1, const iterator& itr2);
After all, that's what this expression is trying to do:
i != a.end()
You're trying to compare two iterators. The error is just trying to convert a.end() to a const vector<T>&, since that's the match that it found for !=. Simply fix != to take an iterator as the second argument and you'll be fine.