这是一项大学任务,所以我更喜欢伪代码,或者只是对过程的基本概念;但是,任何帮助将不胜感激。
问题:
我有两个并行数组:array courseNames 和array maximumEnrollment 。 我必须使用教师提供的函数,按字母顺序将新元素插入到数组 courseNames 中:
// Assume the elements of the array are already in order
// Find the position where value could be added to keep
// everything in order, and insert it there.
// Return the position where it was inserted
// - Assumes that we have a separate integer (size) indicating how
// many elements are in the array
// - and that the "true" size of the array is at least one larger
// than the current value of that counter
template <typename T>
int addInOrder (T* array, int& size, T value)
{
// Make room for the insertion
int toBeMoved = size - 1;
while (toBeMoved >= 0 && value < array[toBeMoved]) {
array[toBeMoved+1] = array[toBeMoved];
--toBeMoved;
}
// Insert the new value
array[toBeMoved+1] = value;
++size;
return toBeMoved+1;
}
由于数组 courseNames 是空的,所以当我第一次使用该函数时,我不必担心数组是否正常。 所有输入都来自由行分隔的文件,每行包含类的名称(ei.CS150)和允许的最大注册(ei.50)。 第一个数组包含课程的名称,而第二个数组包含最大注册数。
我从文件中读取输入的函数的代码如下所示:
/*
* Read the course names and max enrollments. Keep the courses
* in alphabetic order by course name.
*/
void readCourses (istream& courseFile, int numCourses,
string* courseNames, int* maxEnrollments)
{
//!! Insert your code here
for(int i =0; i < numCourses; ++i){
string course;
courseFile >> course;
int pos = addInOrder(courseNames, numCourses, course);
courseFile >> maxEnrollments[pos];
}
}
我使用 courseNames 元素的位置作为索引来存储给定课程的最大注册人数。当一个新值插入 courseNames 并且我得到添加它的位置时,会出现问题。如果我使用该位置,索引的旧值将被覆盖,一切都将不合适。
我的问题是,我该如何防止这种情况发生?如何找出替换的值以保持数组的顺序并使并行数组 maximumEnrollment *与每个课程的 courseNames 的索引相匹配?
提前感谢您提供的任何帮助!
更新
我还提供了这个功能:
// Add value into array[index], shifting all elements already in positions
// index..size-1 up one, to make room.
// - Assumes that we have a separate integer (size) indicating how
// many elements are in the array
// - and that the "true" size of the array is at least one larger
// than the current value of that counter
template <typename T>
void addElement (T* array, int& size, int index, T value)
{
// Make room for the insertion
int toBeMoved = size - 1;
while (toBeMoved >= index) {
array[toBeMoved+1] = array[toBeMoved];
--toBeMoved;
}
// Insert the new value
array[index] = value;
++size;
}
所以我将代码更改为:
/*
* Read the course names and max enrollments. Keep the courses
* in alphabetic order by course name.
*/
void readCourses (istream& courseFile, int numCourses,
string* courseNames, int* maxEnrollments)
{
//!! Insert your code here
int size = 1;
for(int i =0; i < numCourses; i++){
string course;
int maxEnroll;
courseFile >> course;
courseFile >> maxEnroll;
int pos = addInOrder(courseNames, size, course);
addElement(maxEnrollments, size, pos, maxEnroll);
}
}