I have the following piece of code
https://godbolt.org/z/n6doeTfGa
#include <vector>
#include <iostream>
class mainClass
{
public:
mainClass(std::vector<int>& outvect) : m_vec(outvect)
{}
auto iterate() -> void
{
for (auto& elem : m_vec)
std::cout << elem << std::endl;
}
private:
std::vector<int> m_vec;
};
int main()
{
std::vector<int> v{1,2,3};
auto classObj = mainClass(v);
v.push_back(4);
classObj.iterate();
}
Now the program just prints 1,2,3. But I would like for it also print all the change that happen to v.
I was able to come up with this solution.
https://godbolt.org/z/ca4xrhxeE
#include <vector>
#include <iostream>
class mainClass
{
public:
mainClass(std::vector<int>& outvect) : m_vec(&outvect)
{}
auto iterate() -> void
{
for (auto& elem : *m_vec)
std::cout << elem << std::endl;
}
private:
std::vector<int>* m_vec;
};
int main()
{
std::vector<int> v{1,2,3};
auto classObj = mainClass(v);
v.push_back(4);
classObj.iterate();
}
But is there a cleaner way to do this without using pointers?