[英]Why doesn't the vector change its elements?
Have a vector which contains pointers to a Student class. 有一个包含指向Student类的指针的向量。 I need to selection sort the vector elements only changing the pointers, not the content.
我需要选择对矢量元素进行排序,只改变指针,而不是内容。 Here is my caller code:
这是我的来电代码:
StudentsFileReader* sfr = new StudentsFileReader(filepath);
cout << "Calling sortPositionExchange..." << endl;
SelectionSort::sortPositionExchange(&(sfr->getStudents()));
cout << "Done!" << endl;
Here is my calling code: 这是我的调用代码:
void SelectionSort::sortPositionExchange(vector<Student*>* students)
{
int i, j, min, aux, tam = students->size();
for (i = 0; i < tam - 1; i++)
{
min = i;
for (j = (i + 1); j < tam; j++)
{
if (students->at(j)->getCode() < students->at(min)->getCode())
{
min = j;
}
}
if (i != min)
{
Student* s = students->at(i);
*(&students->at(i)) = *(&students->at(min));
*(&students->at(min)) = s;
}
}
}
The selection sort executes perfectly inside sortPositionExchange function, but when it returns, the vector keeps unchanged. 选择排序在sortPositionExchange函数内完美执行,但是当它返回时,向量保持不变。
What can I do to persist the changes between calling functions? 如何在呼叫功能之间保持更改?
Thanks! 谢谢!
Your method getStudents()
returns a vector, the returned vector is not the original vector, it is a copy of it. 你的方法
getStudents()
返回一个向量,返回的向量不是原始向量,它是它的副本。
In order to fix your issue, make the method getStudents()
return a reference to the original vector. 为了解决您的问题,请使方法
getStudents()
返回对原始向量的引用。
so your method should look something like this: 所以你的方法应该是这样的:
vector<Student*>* getStudents() {
return &studentsVector;
}
and your call should look something like this: 你的电话应该是这样的:
SelectionSort::sortPositionExchange(sfr->getStudents());
Another solution would be to make a method inside StudentsFileReader
that uses SelectionSort::sortPositionExchange
to sort the vector. 另一个解决方案是在
StudentsFileReader
中创建一个方法,该方法使用SelectionSort::sortPositionExchange
对向量进行排序。 This would look something like: 这看起来像是这样的:
void StudentsFileReader::sortPositionExchange() {
SelectionSort::sortPositionExchange(students);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.