I was trying to write an iterator by myself for my_vec:
#define BEGIN true
#define END false
#include <vector>
#include <iostream>
template<typename Container>
class my_vec {
private:
class iterator {
const my_vec *this_vec;
using iterator_type = typename std::vector<std::pair<int, const Container&>>::const_iterator;
iterator_type itr;
public:
iterator(const my_vec &s, bool state) :
this_vec(&s) {
if (state == BEGIN) {
itr = s.v.begin();
} else { /*(state==END)*/
itr = s.v.end();
}
}
iterator& operator++() {
itr++;
return *this;
}
std::pair<int, const Container&> operator*() const {
return std::make_pair(1, this_vec->dog);
}
bool operator!=(iterator other) const {
return itr != other.itr;
}
}
;
public:
std::string dog = "DOG";
std::vector<std::pair<int, Container>> v;
my_vec(int space) {
v.reserve(space);
}
iterator begin() const {
return iterator(*this, BEGIN);
}
iterator end() const {
return iterator(*this, END);
}
}
;
However, when running the following main.cpp:
#include "my_vec.h"
int main() {
my_vec<std::string> t(6);
t.v.emplace_back(std::make_pair(1, "HELLO"));
t.v.emplace_back(std::make_pair(2, "BYE"));
t.v.emplace_back(std::make_pair(3, "CAT"));
for (const auto &pair : t) {
std::cout << pair.first << std::endl;
std::cout << pair.second << std::endl;
}
return EXIT_SUCCESS;
}
The expected output is:
1
DOG
1
DOG
1
DOG
However, the actual output is:
1
and then the program stops or prints garbage.
It seems like the problem is in this function:
std::pair<int, const Container&> operator*() const {
return std::make_pair(1, this_vec->dog);
}
Why is this behavior happening as 'dog' is not a local variable?
Also, how can it be fixed without changing the function definition of operator*?
Aucun commentaire:
Enregistrer un commentaire