Consider part of the following class dynamic_matrix
which is a container encapsulating a std::vector<std::vector<T>>
with an invariant which states that every row shall have an equal number of elements, and every column shall have an equal number of elements. The majority of the class has been omitted as most parts are irrelevant for this question.
dynamic_matrix
template<typename _Ty>
class dynamic_matrix {
public:
// public type defns
typedef _Ty value_type;
typedef _Ty& reference;
typedef const _Ty& const_reference;
typedef _Ty* pointer;
typedef const _Ty* const_pointer;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef dynamic_matrix_iterator<value_type> iterator; // defined below
private:
typdef std::vector<std::vector<value_type>> vector_2d;
// enables use of operator[][] on dynamic_matrix
class proxy_row_vector {
public:
proxy_row_vector(const std::vector<value_type>& _vec) : vec(_vec) {}
const_reference operator[](size_type _index) const {
return vec[_index];
}
reference operator[](size_type _index) {
return vec[_index];
}
private:
std::vector<value_type>& vec;
};
public:
explicit dynamic_matrix() : mtx() {}
template<class _Uty = _Ty,
class = std::enable_if_t<std::is_default_constructible<_Uty>::value>
> explicit dynamic_matrix(size_type _rows, size_type _cols)
: mtx(_row, std::vector<value_type>(_cols)) {}
// ... a few other constructors, not important here...
// Capacity
bool empty() const noexcept {
return mtx.empty();
}
size_type rows() const noexcept {
return mtx.size();
}
size_type columns() const noexcept {
if(empty()) return static_cast<size_type>(0);
return mtx[0].size();
}
// Element access
proxy_row_vector operator[](size_type _row_index) const {
return proxy_row_vector(mtx[_row_index]);
}
proxy_row_vector operator[](size_type _row_index) {
return proxy_row_vector(mtx[_row_index]);
}
const value_type* inner_data(size_type _row_index) const noexcept {
return mtx[_row_index).data();
}
value_type* inner_data(size_type _row_index) noexcept {
return mtx[_row_index].data();
}
std::ostream& write(std::ostream& _os, char _delim = ' ') const noexcept {
for (const auto& outer : mtx) {
for (const auto& inner : outer)
_os << inner << _delim;
_os << '\n';
}
return _os;
}
// Iterators
iterator begin() {
return iterator(inner_data(0)); // points to first element of matrix
}
iterator end() {
// points to element past end of matrix
return iterator(inner_data(rows()-1) + columns());
}
private:
vector_2d mtx;
};
The custom-iterator, dynamic_matrix_iterator
, which uses a std::bidirectional_iterator_tag
is defined below.
dynamic_matrix_iterator
template<typename _Ty>
class dynamic_matrix_iterator : public std::iterator<std::bidirectional_iterator_tag,
_Ty, std::ptrdiff_t, _Ty*, _Ty&> {
public:
dynamic_matrix_iterator(_Ty* _ptr) : ptr(_ptr) {}
dynamic_matrix_iterator(const dynamic_matrix_iterator& _other) = default;
dynamic_matrix_iterator& operator++() {
ptr++;
return *this;
}
dynamic_matrix_iterator operator++(int) {
dynamic_matrix_iterator<_Ty> tmp(*this);
operator++();
return tmp;
}
dynamic_matrix_iterator& operator--() {
ptr--;
return *this;
}
dynamic_matrix_iterator operator--(int) {
dynamic_matrix_iterator<_Ty> tmp(*this);
operator--();
return tmp;
}
_Ty& operator*() {
return *ptr;
}
_Ty* operator->() {
return ptr;
}
bool operator==(const dynamic_matrix_iterator& _other) {
return ptr == _other.ptr;
}
bool operator!=(const dynamic_matrix_iterator& _other) {
return ptr != _other.ptr;
}
private:
_Ty* ptr;
};
Here is a test-case in which I use a range based for loop to print the elements in the matrix, as well as using the dynamic_matrix::write()
method to compare:
int main(void) {
std::size_t rows = 3;
std::size_t cols = 3;
dynamic_matrix<int> dm(rows,cols);
int count = 0;
// assign increasing natural numbers to each element
for (std::size_t i = 0; i < rows; ++i) {
for (std::size_t j = 0; j < cols; ++j)
dm[i][j] = ++count;
}
int range_count = 0;
// print using iterators
for (auto x : dm) {
std::cout << x << ' ';
++range_count;
if (!(range_count % cols))
std::cout << std::endl;
}
std::cout << std::endl;
// print using inbuilt method
dm.write(std::cout);
}
Now, the iterator-based ranged for loop prints the following:
1 2 3
0 0 0
35 0 4
5 6 0
0 0 35
0 7 8
9
whereas the correct output as given by dynamic_matrix::write
is, of course,
1 2 3
4 5 6
7 8 9
In the incorrect output using iterators, we see some garbage elements between the actual matrix elements which I can only assume are brought about by undefined behaviour when the pointer of the dynamic_matrix_iterator
accesses "random" memory in-between each row-vector of the matrix - running this on a different machine would likely yield different values here or something else unexpected if this is undefined behaviour as I suspect it is.
Question
So given this behaviour, is there a more elegant way to implement iterators for this container? Also, given that a std::vector
uses contiguous storage why is the above actually happening - are the "garbage" values part of the vectors' internal memory used for allowing expansion of the vector?