So I'm trying to make a basic program to learn the basics of C++, I'm generating 100 random numbers from 0 to 100 and storing them in a vector, I am then displaying the sum, mean, median, mode, high and low of the vector. I have everything else done except the mode which is where I get stuck. Here is the code I have so far.
int modeFunction()
{
numMode = 0;
count = 0;
for (int n = 0; n < 100; n++)
{
for (int y = 0; y < 100; y++)
{
if (numVector.at(y) == numVector.at(n))
{
numMode = numVector.at(y);
count++;
}
}
}
return numMode;
}
After that I get stuck because in my mind that should work but it doesn't. It just out puts the last number, usually 100. Any help would be much appreciated.
myVector
is astd::vector<int>
(seems like it atleast), you can index it like an array:myVector[y]
andmyVector[n]
will yield the same as themyVector.at
version, but looks nicer imho. :) – Gothaat
has defined behaviour when the index is out of range. Arguablyoperator[]
is a micro-optimization, although as you say it's also a bit of a style difference. – Edgewaysat
yet, but a normal array also has undefined behaviour for out of range access, though it certainly is nice to have defined behavious when you need it. :) – Gothaat
myself. I occasionally wonder whether I should, but in practice I never write code that I want to throw an exception when the index is out of bounds, so it only serves as a debugging assist, it "should" never happen. Despite calling it a micro-optimization, it's a reasonable amount of redundant code, so in the end if I want bounds-checking I just switch to Python ;-) – Edgeways