Essentially what I'm trying to do is to build a function that will find the minimum value of a vector so I can later apply it to a standard sort. I can't seem to wrap my brain around anything more complicated than this form of code, however intuitively I feel like it would not find the smallest value, simply the last value smaller than where the vector analysis begins from... I haven't gotten to the point of applying the code yet however I have a strong feeling this code will not do what I'm trying to get it to do, could I get a push in the right direction?
int findMin(const vector<int> & v, const int & from)
{
for (int i = from; i < v.size(); i++)
{
if(v[from] > v[i])
{
int min = i;
}
}
}
std::vector<int>::size_type findMin( const std::vector<int> &v, std::vector<int>::size_type pos = 0 )
{
if ( v.size() <= pos ) return ( v.size() );
std::vector<int>::size_type min = pos;
for ( std::vector<int>::size_type i = pos + 1; i < v.size(); i++ )
{
if ( v[i] < v[min] ) min = i;
}
return ( min );
}
The function returns the position of the minimal element. If the initial position is specified incorrectly the function returns the vector size. It is better to use position instead of an integer value for the minimum that to distinguish whether the vector is empty or the initial position was specified incorrectly or it indeed has the minimum.
In a calling function you can use the following code
1 2 3 4 5 6
std::vector<int>::size_type min_pos = findMin( v );
if ( min_pos != v.size() )
{
std::cout << "minimum is " << v[min_pos] << std::endl;
}
Take into account that there is standard algorithm std::min_element that can be used instead of your function.
Some good points made already. My version returns the value of the minimum element, starting at index from.
1 2 3 4 5 6 7 8 9 10 11 12
int findMin(const vector<int> & v, constint & from)
{
int min = v[from];
for (int i = from+1; i < v.size(); i++)
{
if(v[i] < min)
{
min = v[i];
}
}
return min;
}
Your code is invalid because for example the vector can be empty or the initial position can be specified incorrectly. Moreover there is no any sense to pass the second parameter by reference if it is declared as const.