Could this be done with a pointer (*) or a reference (&)?
Yes and no.
Pointer ( *
)
With a list of pointers you can effectively modify the value to which the pointer (pointer) points but the element of the list (the pointer) will not be modified, only that which it points to will be modified:
template <typename T>
using lista_puntero = std::list<T *>;
int a = 1, b = 2, c = 3;
lista_puntero<int> lp{&a, &b, &c};
for (const auto &v : lp)
std::cout << "Direccion: " << v << " Valor: " << *v << '\n';
a += 3;
b += 2;
c += 1;
std::cout << '\n';
for (const auto &v : lp)
std::cout << "Direccion: " << v << " Valor: " << *v << '\n';
The previous code shows the following 1 :
Direccion: 0x7ffd4adfe81c Valor: 1
Direccion: 0x7ffd4adfe818 Valor: 2
Direccion: 0x7ffd4adfe814 Valor: 3
Direccion: 0x7ffd4adfe81c Valor: 4
Direccion: 0x7ffd4adfe818 Valor: 4
Direccion: 0x7ffd4adfe814 Valor: 4
As you can see, the value stored in the list does not change, so it does not meet your first premise: " if I change an item in the list outside of it, this change will be reflected in the list ", this happens because the pointer (pointer) and the pointed data are not the same element. However, the value pointed to by the pointer pointed to by the pointer stored in the list has been changed.
Reference ( &
)
The C ++ language does not allow collections of references 2 , but we can use a reference wrap: std::reference_wrapper
:
template <typename T>
using lista_referencia = std::list<std::reference_wrapper<T>>;
int a = 1, b = 2, c = 3;
lista_referencia<int> lr{a, b, c};
for (const auto &v : lr)
std::cout << "Direccion (wrapper): " << &v << " Valor: " << v << '\n';
a += 3;
b += 2;
c += 1;
std::cout << '\n';
for (const auto &v : lr)
std::cout << "Direccion (wrapper): " << &v << " Valor: " << v << '\n';
The previous code shows the following 3 :
Direccion (wrapper): 0x684170 Valor: 1
Direccion (wrapper): 0x684190 Valor: 2
Direccion (wrapper): 0x683ed0 Valor: 3
Direccion (wrapper): 0x684170 Valor: 4
Direccion (wrapper): 0x684190 Valor: 4
Direccion (wrapper): 0x683ed0 Valor: 4
The reference envelope makes the code easier and follows your first premise " if I change an item on the list outside of it, this change will be reflected in the list " without needing to -referencing the value (without doing *v
) or storing pointers (we do not need the &variable
when adding data to the list), but it's still a trick: deep down the envelope does not change even though the value it references yes, change.
Compiled in Wandbox using GCC 9.0.0 201808 , the values of the pointers may vary with each execution.
To find out the reason behind this limitation, read this answer .
Compiled in Wandbox using GCC 9.0.0 201808 , the values of the pointers may vary with each execution.