C++ 当我在c+中只引用向量时,如何更改向量中的对象+;

C++ 当我在c+中只引用向量时,如何更改向量中的对象+;,c++,vector,stl,C++,Vector,Stl,我必须计算人们的平均年龄,然后我必须计算有多少人比平均年龄年轻。在那之后,我必须让他们变老,再数一数有多少人比平均年龄年轻 int magic(Vector<Person>& v, Guild g) { if (v.size() == 0) { throw runtime_error(""); } int d = accumulate(v.begin(), v.end(), 0, [](int

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

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;
}
int-magic(向量&v,公会g){
如果(v.size()==0){
抛出运行时错误(“”);
}
int d=累加(v.begin(),v.end(),0,
[](int sum,Person p){return sum+=p.get_age();});
INTA=d/v.尺寸();
自动计数=
如果(v.begin(),v.end(),[a](Person p1){返回p1.get_age()
您的lambda正在按值接受它们的参数,这意味着您正在复制对象并将它们传递给lambda

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

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

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;
}
int-magic(向量&v,公会g){
如果(v.size()==0){
抛出运行时错误(“”);
}
//因为我们不需要修改,所以通过const ref获取Person
int d=累加(v.begin(),v.end(),0,
[](int-sum,const-Person&p){return-sum+=p.get_-age();});
INTA=d/v.尺寸();
//再说一遍,const ref
自动计数=
如果(v.begin(),v.end(),[a](constperson&p1){返回p1.get_age()
Person p
n您的
对于每个
lambda是按值计算的。如果要更改该对象,则需要通过引用,
Person&p
。除此之外,考虑使用<代码>(Auto&P:V)并推迟破旧的<>代码>每个构造。非常感谢。