fclopez
fclopez

Reputation: 55

Sorting integer elements of a vector

I would like to calculate the median of elements stored in a vector

#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);
}

Error: operator- not defined for vector >::iterator algo.h:722. I appreciate the help.

Upvotes: 1

Views: 307

Answers (1)

juanchopanza
juanchopanza

Reputation: 227578

You can solve this problem more efficiently using std::nth_element. This will only do a partial sorting of the vector, and has linear complexity. This is an example for an odd-sized vector:

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

the median value is

trmVa[midIndex];

You can easily extend this to cover even-sized vectors.

Upvotes: 3

Related Questions