C++ 自定义对象';s向量属性中值c++;

C++ 自定义对象';s向量属性中值c++;,c++,algorithm,stl,C++,Algorithm,Stl,我试图从对象的第三个属性中找到中值。我的对象是向量 std::vector<Object> obj = { Object {V , H , 5}, Object {C , B , 2}, Object {D , F , 6}, Object {B , H , 4}, Object {B , H , 4} }; 我试图使用该方法,但似乎需要访问该属性 std::nth_element(obj.begin(), (obj.begin

我试图从对象的第三个属性中找到中值。我的对象是向量

std::vector<Object> obj = 
   { Object {V , H , 5},
     Object {C , B , 2},
     Object {D , F , 6},
     Object {B , H , 4},
     Object {B , H , 4}
   };
我试图使用该方法,但似乎需要访问该属性

std::nth_element(obj.begin(), (obj.begin() + obj.end())/2, obj.end());

默认情况下,应用
运算符bj[len/2]?不是您需要的吗?
std::nth\u元素
执行部分排序。如果按数字排序,中位数应为
4
。如果正确答案是6,那么您只需要中间元素,而不是中位数。Tks,ΦXocę웃 Пepeúpaツ. 不完全是这样,因为当我这样做时,我可以访问对象,并且我只想要属性。我尝试使用第n_元素方法,但似乎我需要访问属性。这取决于
operatorTks,@Scheff它有多大帮助。我注意到我也可以使用std::sort;
std::nth_element(obj.begin(), (obj.begin() + obj.end())/2, obj.end());
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>

struct Object {
  std::string id1, id2;
  int attr;
};

std::ostream& operator<<(std::ostream &out, const Object &obj)
{
  return out << "Object { id1: " << obj.id1
    << ", id2: " << obj.id2
    << ", attr: " << obj.attr << " }";
}

// demonstrate
int main()
{
  std::vector<Object> obj = 
   { Object {"V", "H" , 5},
     Object {"C", "B" , 2},
     Object {"D", "F" , 6},
     Object {"B", "H" , 4},
     Object {"B", "H" , 4}
   };
  // partial sorting with custom predicate (provided as lambda):
  std::nth_element(obj.begin(), obj.begin() + obj.size() / 2, obj.end(),
    [](const Object &obj1, const Object &obj2) { return obj1.attr < obj2.attr; });
  // get result:
  const std::vector<Object>::iterator iter
    = obj.begin() + obj.size() / 2;
  std::cout << "Median: " << *iter << '\n';
}
std::nth_element(obj.begin(), obj.begin() + obj.end()/2, obj.end());