自定义对象的矢量属性中位数 C++

Custom object's vector attribute median c++

我正在尝试从我的对象的第三个属性中找到中值。我的对象在一个向量中。

std::vector<Object> obj = 
   { Object {V , H , 5},
     Object {C , B , 2},
     Object {D , F , 6},
     Object {B , H , 4},
     Object {B , H , 4}
   };

答案:

4 

我尝试使用 nth_element 方法,但似乎我需要访问该属性。

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

默认情况下,std::nth_element()operator< 应用于作为参数提供的解引用迭代器。

在 C++ 中,没有为自定义 类 定义 operator<,但作者可以自由定义(重载)一个。

或者,std::nth_element() 可以使用自定义 less 谓词调用以强制执行特定顺序。

Could you show me a generic example ?

我们开始:
根据具有

的对象的特定属性获取中位数的示例
  • 部分排序(又名。std::nth_element())和
  • Object::attr排序的自定义谓词。
#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';
}

输出:

Median: Object { id1: B, id2: H, attr: 4 }

Live demo on coliru


注:

OP 提到了以下片段:

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

obj.begin() + obj.end()/2 又是一个错误。
必须是 obj.begin() + (obj.end() - obj.begin()) / 2.
我改用更紧凑的 obj.begin() + obj.size() / 2.