I was trying to loop a list and getting the address of the element. But all of the element's address is the same when using variant class.
int main()
{
std::list<std::variant<std::list<int>, std::list<std::string>>> list_of_lists;
std::list<int> int_list = {1, 2, 3};
string a1 ="one";
std::list<std::string> string_list = {a1, "two", "three"};
list_of_lists.push_back(int_list);
list_of_lists.push_back(string_list);
// Iterate over all std::variant elements.
for (const auto& v : list_of_lists) {
// Check if the variant holds a list of ints.
if (std::holds_alternative<std::list<int>>(v)) {
// 'v' holds a list of ints.
for (auto i : std::get<std::list<int>>(v)) {
std::cout << i << ' ';
cout<<&i<<endl;
}
std::cout << '\n';
}
// Check if the variant holds a list of strings.
else if (std::holds_alternative<std::list<std::string>>(v)) {
// 'v' holds a list of strings.
for (const auto& s : std::get<std::list<std::string>>(v)) {
std::cout << s << ' ';
cout<<"string: "<<&std::get<std::list<std::string>>(v)<<endl;
cout<<&s<<endl;
}
std::cout << '\n';
}
}
cout<<"a1 address: "<<&a1<<endl;
}
output:
1 0x8dfcac
2 0x8dfcac
3 0x8dfcac
one string: 0x8f2890
0x8f27d0
two string: 0x8f2890
0x8f2810
three string: 0x8f2890
0x8f2850
a1 address: 0x8dfcc0
As you ## Heading ##
It looks like the variant std library cannot get the original variable's own address. Thus, every time I try to loop through the linked list, all the address of elements in the mother list are changed. Thus, I can only display and I can not push back for those linked lists in the mother linked list. One of my friends told me c++ is all about pointer and he hates Java because it does have pointer! And now I can not use a pointer in c++ with this library. I have heard this problem can be solved by boot:: variant, std:: optional or polymorphism. But I have no idea how these work. Anyway, some people said the reason this library does not touch the address idea is because they have a disagreement about how what assignment