【发布时间】: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++ 迭代器的方式允许我执行这些操作。我知道我可以只存储索引,但我不想这样做。
【问题讨论】: