-3

我试图循环一个列表并获取元素的地址。但是在使用变体类时,所有元素的地址都是相同的。

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

当你##标题##

看起来变体标准库无法获取原始变量自己的地址。因此,每次我尝试遍历链表时,母链表中所有元素的地址都会改变。因此,对于母链表中的那些链表,我只能显示,不能回推。我的一位朋友告诉我,c++ 完全是关于指针的,他讨厌 Java,因为它确实有指针!现在我不能在这个库中使用 c++ 中的指针。我听说这个问题可以通过 boot:: variant、std:: optional 或多态来解决。但我不知道这些是如何工作的。不管怎样,有人说这个库之所以没有触及地址的想法是因为他们对如何赋值存在分歧

4

1 回答 1

1

对于int循环,您创建了一个局部变量并获取其地址。

for (auto i : std::get<std::list<int>>(v))  // local variable, same address each time

应该

for (auto& i : std::get<std::list<int>>(v)) // reference, refers to the actual element

这与变体无关。

对于string循环,您已经使用了参考。

for (const auto& s : std::get<std::list<std::string>>(v)) // reference

这就是为什么事情按预期工作的原因。

于 2019-06-02T02:16:41.850 回答