Hello everyone,
I am currently teaching C++ to myself using the book of B. Stroustrop.
In one task, one shall write program that pushes back input values into a vector and then gives out the median.
It's possible to compile it without any problems.
However, I'm always getting following error message and the program is aborting when executing it:
http://fs5.directupload.net/images/160622/oj9kudzv.png
(expression: vector subscript out of range)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
#include <fstream>
#include "square.h"
using namespace std;
// compute mean and median temperatures
int main()
{
vector<double> temps; // temperatures
for (double temp; cin >> temp; ){ // read into temp
temps.push_back(temp); // put temp into vector
// compute mean temperature:
double sum = 0;
for (int x : temps) sum += x;
cout << "Average temperature: " << sum / temps.size() << '\n';
//compute median temperature:
sort(temps.begin(), temps.end()); // sort temperatures
cout << sizeof(temps);
cout << "Median temperature: "
<< (temps[temps.size()/2 - 1] - temps[temps.size()/2] ) /2 << '\n';}
}
|
When I leave out the "- 1", I don't get any problems. It works with -1 only, but without /2 in the first term as well.
I also tried using even and uneven sizes of the vector, but I am always getting this error. The sizeof(temps); line gives out "wrong" sizes of the vector too. If I input for instance "3 4 5" when running the program, it shows "16" for sizeof(temps); and then aborts, showing the abovementioned message.
So, I think there is something wrong in my code.
I am using VisualStudio2015 on Win7 x86.
Thanks in advance,
hrxs1