【问题标题】:Are there c++ like iterators in dartdart 中是否有类似 c++ 的迭代器
【发布时间】:2021-10-04 14:36:29
【问题描述】:

在 c++ 中,我们有迭代器作为对列表中某些元素的引用。分配给迭代器可以更改列表中的元素。 例如:

        std::map<std::pair<int,int> ,Ship> playgroundMap;
        playgroundMap.insert(std::make_pair(std::make_pair(2,2),Ship(100,Cannon(50))));
        playgroundMap.insert(std::make_pair(std::make_pair(3,3),Ship(200,Cannon(60))));
        std::cout<<"Iterators : "<<std::endl;
        auto shipPtr = playgroundMap.find(std::make_pair(2,2));
        std::cout<<" address of  ship Before                 : "<<&shipPtr->second<<std::endl;
        shipPtr->second.cannon.firepower = 1000;
        auto tmp = Ship(200,Cannon(90));
        shipPtr->second = tmp;
        std::cout<<" address of  ship After newly Assigned   : "<<&shipPtr->second<<std::endl;

        std::cout<<"finalList : "<<std::endl;
        for(auto a : playgroundMap)
        {
            std::cout<<a.second.durability<<std::endl<<a.second.cannon.firepower<<std::endl;
        }

更不用说 c++ 中的引用足以实现这一点。 c++ 中的引用不会像在 dart 中那样在赋值时反弹。 例如在 C++ 中:

        std::map<std::pair<int,int> ,Ship> playgroundMap;
        playgroundMap.insert(std::make_pair(std::make_pair(2,2),Ship(100,Cannon(50))));
        playgroundMap.insert(std::make_pair(std::make_pair(3,3),Ship(200,Cannon(60))));
        std::cout<<"Reference : "<<std::endl;
        auto &shipRef = playgroundMap[std::make_pair(2,2)];
        std::cout<<" address of  ship Before                 : "<<&shipRef<<std::endl;
        shipRef.cannon.firepower = 1000;
        auto tmp = Ship(200,Cannon(90));
        auto &tmpRef = tmp;
        std::cout<<" address of  tmpref (newly created ship) : "<<&tmpRef<<std::endl;
        shipRef = tmpRef;
        std::cout<<" address of  ship After newly Assigned   : "<<&shipRef<<std::endl;

        std::cout<<" address of  finalList : "<<std::endl;
        for(auto a : playgroundMap)
        {
            std::cout<<a.second.durability<<std::endl<<a.second.cannon.firepower<<std::endl;
        }

这将修改 c++ 中的列表元素,而在 dart 中,引用将重新绑定并且列表中的元素不会改变。这完全是另一回事,我理解这两个概念在两种语言中都是不同的。

我的问题是,在 dart 中是否有某种类似 c++ 迭代器的方式允许我执行这些操作。我知道我可以只存储索引,但我不想这样做。

【问题讨论】:

    标签: dart reference iterator


    【解决方案1】:

    平台库中没有类似的东西。 通常,Dart 迭代器允许访问集合的值,而不是更改集合本身。

    这个限制的一个原因可能是 Dart 没有引用变量开始,但没有什么本质上阻止 Dart 拥有一个允许您更改当前元素值的迭代器。至少对于一个列表,它可以工作。哈希集可能不起作用,因为更改后的值不会在迭代的同一位置。

    总而言之,这不是平台库支持或想要支持的东西。在大多数地方,Dart 平台库比 C++ 稍微更像函数式编程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 2020-11-21
      • 2011-11-10
      • 2020-11-16
      • 2011-06-10
      • 2018-05-16
      • 1970-01-01
      相关资源
      最近更新 更多