I'm trying to print a sorted vector. I want to print all ones on one row, all twos on one row, all threes on one row, and so on. The problem is that I get "vector subscript out of range" when I try to run the following code. I guess that it is beacuse I read "out of bound" (i+1), but i don't know any other way to do it. I'm not allowd to use map.
#include <iostream>
#include <iomanip>
#include <ctime>
#include <algorithm>
#include <vector>
#include <random>
usingnamespace std;
int main()
{
//Declaration of variables and constants
vector<int> vector1;
vector<int> vector2;
const size_t SIZE = 600;
//Initializing randomization
default_random_engine generator(static_cast< unsigned>(time(0)));
uniform_int_distribution<int> random(1, 100);
//Randomized numbers are being pushed to the vector
for (size_t i = 0; i < SIZE; i++)
vector1.push_back(random(generator));
//Copy the vector to another vector
vector2 = vector1;
//Calculating average
int sum = 0;
float average = 0;
for (auto idx : vector2)
sum += idx;
average = static_cast<float>(sum) / SIZE;
//Printing average
cout << fixed << setprecision(1) << "The average number is: " << average << endl << endl;
//Highest and lowest value are printed
cout << "The highest value in the vector is: " <<
*(max_element(vector2.begin(), vector2.end())) << endl;
cout << "The lowest value in the vector is: " <<
*(min_element(vector2.begin(), vector2.end())) << endl << endl;
//The user writes a number to search for
int tal = 0, counter = 0;
cout << "Write a number to search for: ";
cin >> tal;
cout << endl;
//Sorting the vector
sort(vector2.begin(), vector2.end());
cout << "Sorted vector:" << endl << endl;
//Prints the sorted vector
for (size_t i = 0; i < SIZE; i++)
{
cout << setw(4) << vector2[i];
if (vector2[i+1] != vector2[i])
cout << endl;
}
//Line breaks
cout << endl << endl;
//Search for number of occurences of the user input number and prints these
counter = count(vector2.begin(), vector2.end(), tal);
cout << "The number " << tal << " is found " << counter << " times in the vector." << endl << endl;
//Calculates the most common number in the vector
int times = 0;
int maxvalue = vector2[0];
int countnum = 0;
//Frequency loop
for (auto i : vector2)
{
countnum = (int)count(vector2.begin(), vector2.end(), vector2[i]);
if (countnum > times)
{
times = countnum;
maxvalue = vector2[i];
}
}
//Prints the most common number and the occurencies
cout << "The most common number is " << maxvalue << ". It occures " << times << " times." << endl << endl;
return 0;
}