class pair
{
public:
int a, b;
pair(int tmp_a, int tmp_b)
{
a = tmp_a;
b = tmp_b;
}
};
int main()
{
list<pair> l;
l.push_back(pair(1,6));
l.push_back(pair(2,7));
l.push_back(pair(3,8));
l.push_back(pair(4,9));
l.push_back(pair(5,10));
for (auto& pair_item : l/*std::list<pair>::iterator i = l.begin(); i != l.end(); i++*/) //Edited
{
// print/modify the member variables in the object that iterator i points to
}
return 0;
}
(参考代码)
该列表包含类型对的元素。假设我希望修改列表中的元素(类型对的对象),例如将b
更改为b
+ a
。我怎么能这样做呢?
答案 0 :(得分:3)
...例如将
b
更改为b + a
。我怎么能这样做呢?
您可以执行以下操作:
for(auto& pair_item : l) {
pair_item.b += pair_item.a;
}
至于示例代码中观察到的问题:
for (list<int>::iterator i = l.begin(); i != l.end(); i++)
// ^^^^^^^^^ Isn't matching `list<pair>`
{
(*i).b += (*i).a; // Should do the operation you want
}