【问题标题】:Printing/modifying a specific member variable of a class object, whose class defines the type of elements the list(STL) contains打印/修改类对象的特定成员变量,其类定义列表(STL)包含的元素类型
【发布时间】:2017-07-16 12:17:34
【问题描述】:
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。这样的操作怎么做?

【问题讨论】:

  • 您使用(仍然正确,但)老式 for 循环而不是范围 for 的任何特殊原因?
  • 我还不太习惯。我以前在很多场合都使用过基于范围的循环,但在这个特殊场合,它并没有打动我。我想我更专注于我遇到的问题。
  • @PuneetSingh 如果您的代码有问题,您应该在问题中明确说明(逐字错误消息)。

标签: c++ list stl


【解决方案1】:

...例如将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
}

【讨论】:

  • 感谢您指出错误。我打算写list&lt;pair&gt; 而不是list&lt;int&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多