【问题标题】:How to change the object in a vector when I only have a reference to the vector in c++当我在 C++ 中只有对向量的引用时如何更改向量中的对象
【发布时间】:2021-02-16 11:18:41
【问题描述】:

我必须计算人们的平均年龄,然后我必须计算有多少人比平均年龄年轻。在那之后,我必须让他们变老,然后再次计算有多少人比平均水平年轻。

int magic(Vector<Person>& v, Guild g) {
  if (v.size() == 0) {
    throw runtime_error("");
  }

  int d = accumulate(v.begin(), v.end(), 0,
                     [](int sum, Person p) { return sum += p.get_age(); });
  int a = d / v.size();
  auto count =
      count_if(v.begin(), v.end(), [a](Person p1) { return p1.get_age() < a; });

  for_each(v.begin(), v.end(), [g](Person p) {
    if (p.get_guild() == g) {
      return p.aging();
    }
  });

  auto count2 =
      count_if(v.begin(), v.end(), [a](Person p3) { return p3.get_age() < a; });

  return count + count2;
}

【问题讨论】:

  • Person p n 你的 for_each lambda 是按值计算的。如果您要更改该对象,则需要引用 Person &amp;p。除此之外,考虑使用for (auto&amp; p : v) 并保护破旧的for_each 构造。

标签: c++ vector stl


【解决方案1】:

您的 lambdas 按值接受它们的参数,这意味着您正在制作对象的副本并将它们传递给 lambdas。

修改副本不会改变向量中的原始值。

解决方案是通过引用获取参数。

int magic(Vector<Person>& v, Guild g) {
  if (v.size() == 0) {
    throw runtime_error("");
  }

  // taking the Person by const-ref since we don't need to modify it
  int d = accumulate(v.begin(), v.end(), 0,
                     [](int sum, const Person& p) { return sum += p.get_age(); });
  int a = d / v.size();
  // again, const-ref
  auto count =
      count_if(v.begin(), v.end(), [a](const Person& p1) { return p1.get_age() < a; });

  // Here we take it by reference, so we can modify it.
  // Also capturing the Guild by reference to avoid uneccesary copy
  for_each(v.begin(), v.end(), [&g](Person& p) {
    if (p.get_guild() == g) {
      return p.aging();
    }
  });

  // again by const-ref
  auto count2 =
      count_if(v.begin(), v.end(), [a](const Person& p3) { return p3.get_age() < a; });

  return count + count2;
}

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多