user7337963 user7337963 - 1 year ago 82
C++ Question

forward iterators, how to return const value

I have made a dynamic array class, each element in the array is defined via struct made like this

template <typename T>
struct element{
int i;
int j;
T val;

I have defined forward iterator and const iterator for my class, the iterator needs to return to return
i, j, val
but only val can be modifiable,
can not be modified.

How can i do that?

Answer Source

Extending @Bathsheba's answer, your iterators could return this struct:

template<typename T>
struct element_ref {
    const int& i;
    const int& j;
    T& val;

    element_ref(element& e) : i(e.i), j(e.j), val(e.val) {}

Its constructor takes the actual element and stores references to its fields. only the val reference is modifiable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download