dart - dart 中是否有类似 c++ 的迭代器
问题描述
在 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 迭代器允许访问集合的值,而不是更改集合本身。
这种限制的原因之一可能是 Dart 没有以引用变量开头,但没有什么能阻止 Dart 拥有一个允许您更改当前元素值的迭代器。至少对于一个列表,它可以工作。哈希集可能不起作用,因为更改的值不会在迭代的同一位置。
总而言之,这不是平台库支持或想要支持的东西。在大多数地方,Dart 平台库比 C++ 更像函数式编程。
推荐阅读
- c - 扫描文件会将功能发送到无响应模式?
- angular - Angular:Karma 给出错误错误:NullInjectorError:没有提供 ElementRef!从 v7 升级到 v8 后
- node.js - 如何在建立连接时使用 knex npm 包获取 MySQL connectionId?
- aws-sdk-js - @aws-sdk/client-s3 getObject 不获取最新版本的版本化存储桶对象
- android - Flutter 项目中使用 Cocos 引擎作为模块
- c# - C# 使用反射将特定属性序列化为 JSON?
- github - GitHub api code_frequency 所有的返回值是什么
- iis - Blazor webassembly (net5.0) 发布在 IIS 中不起作用
- python - 如何通过python从矩阵中删除相同的列表
- typescript - 我可以使用另一个字段的值初始化 Typescript 字段吗