【问题标题】:Sorting integer elements of a vector对向量的整数元素进行排序
【发布时间】:2012-09-02 16:00:46
【问题描述】:

我想计算存储在向量中的元素的中位数

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;

 ....
 ....
 ....

vector<int> trmVa;
int size;
int median;
int trimVal;

trmVa.push_back(trimVal);
size = trmVa.size();
sort(trmVa.begin(), trmVa.end()); //I am having troubles here!!!!

if(size % 2) {
  median = (trmVa[size/2 - 1] + trmVa[size/2]) /2;
  printf("Module %d \n\n \t Median = %d\n", mod, median); 
}else {
   median = trimVa[size/2];
   printf("Module %d \n\n \t Median = %d\n", mod, median);
}

错误:运算符 - 未为向量 >::iterator algo.h:722 定义。感谢您的帮助。

【问题讨论】:

  • @tuğrulbüyükışık 他正在使用 std::sort
  • sort 的调用看起来不错。但是如果你想要的只是中位数,你可以使用std::nth_element。事实上,你的标题应该反映你想做什么,而不是你认为应该怎么做。
  • 这个compiles for me。修复变量名后。显示你的真实代码。
  • @fclopez:您的其他问题是否得到了满意的回答?考虑将其中一些标记为正确。

标签: c++ algorithm sorting vector


【解决方案1】:

您可以使用std::nth_element 更有效地解决此问题。这只会对向量进行部分排序,并且具有线性复杂度。这是一个奇数向量的例子:

size_t midIndex = trmVa.size()/2;
nth_element(trmVa.begin(), tmrVa.begin() + midIndex, trmVa.end());

中值为

trmVa[midIndex];

您可以轻松地扩展它以覆盖偶数大小的向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-04
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多