I am a beginner of C++, trying to finish my program in selection sort with vecto
ID: 641021 • Letter: I
Question
I am a beginner of C++, trying to finish my program in selection sort with vector, but it keeps showing up the errors
Can somebody help
void selectionSort(const vector& newMyVector)
{
cout << "Vector in Selection Sort : " ;
int length = newMyVector.size();
for (unsigned int i=0; i < length-1; i++)
{
int min = i;
for(unsigned int j = i+1; j < length; j++)
{
if (newMyVector[j] < newMyVector[min])
{
min = j;
}
}
int temp=newMyVector[min];
newMyVector[min]=newMyVector[i];
newMyVector[i]= temp;
printVector(newMyVector);
}
cout << endl;
}
this is the error on
newMyVector[min]=newMyVector[i];
[Error] assignment of read-only location '(& newMyVector)->std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)min))'
newMyVector[i]= temp;
[Error] assignment of read-only location '(& newMyVector)->std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))'
Explanation / Answer
void selectionSort(vector<int>& newMyVector) // remove const here this is causing issue. u cant modify const object. but u are swapping elements.
{
cout << "Vector in Selection Sort : " ;
int length = newMyVector.size();
for (unsigned int i=0; i < length-1; i++)
{
int min = i;
for(unsigned int j = i+1; j < length; j++)
{
if (newMyVector[j] < newMyVector[min])
{
min = j;
}
}
int temp=newMyVector[min];
newMyVector[min]=newMyVector[i];
newMyVector[i]= temp;
printVector(newMyVector);
}
cout << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.