2014-04-29 23 views
0

给定一个表示记录行号的整数值(从0 开始,以当前大小1结尾),删除学生记录,向上移动电子表格中的所有以下记录一个 行。如果用户输入了一个超出范围的整数(< 0或> = size),则 提示“没有这样的行。不能删除行??”替换?行号。向下移动数组值1

我不知道代码有什么问题。它不会移动有关它的数组信息1;

void drop(string names[], int sections[], int grades[], int size){ 
    int i; 
    int drop; 
    cin >> drop; 
    if (drop > size){ 
     cout << "No such row. Can not drop row" << drop << " /n"; 

    }else{ 
     for (i = 0; i <= drop; i++){ 
      if (i == drop){ 
       names[drop] = {""}; 
       sections[drop] = {}; 
       grades[drop] = {}; 
       for (i = drop; drop < size-1; i++){ 
        names[i] = names[i + 1]; 
        sections[i] = sections[i + 1]; 
        grades[i] = grades[i + 1]; 
       } 
      } 

     } 

    } 
} 
+0

谢谢。非常有帮助 – DaneelD

回答

1

试试这个:

void drop(string names[], int sections[], int grades[], int size){ 
    int i; 
    int drop; 
    cin >> drop; 
    if (drop >= size){  //NOTE: >=, not > 
     cout << "No such row. Can not drop row" << drop << " /n"; 
     return; 
    } 
    for(i=drop; i<size-1; i++) 
     names[i] = names[i + 1]; 
     sections[i] = sections[i + 1]; 
     grades[i] = grades[i + 1]; 
    } 
} 

}

当然,如果你想改变数组的大小,这将是更好地使用向量。

但是,您不能执行以下操作,因为name_of_array [drop]是数组中的元素,而不是数组中的数组。无论哪种情况,这都是非法代码。

names[drop] = {""};  //should be names[drop] = ""; 
sections[drop] = {};  // '' '' sections[drop] = 0; 
grades[drop] = {};  // '' '' grades[drop] = 0; 
1

更改线路

  for (i = drop; drop < size-1; i++){ 

  for (i = drop; i < size-1; i++){ 

else块下的代码可以进一步简化为:

  for (i = drop; i < size-1; i++){ 
       names[i] = names[i + 1]; 
       sections[i] = sections[i + 1]; 
       grades[i] = grades[i + 1]; 
      } 

你不需要在此之前的线路。

0

您对使用标准库算法有何感想?您可以使用以下原料代替循环:

void drop(string names[], int sections[], int grades[], int size) { 
    int drop; 
    cin >> drop; 
    if (drop >= size) { 
     cout << "No such row. Can not drop row" << drop << " \n"; 
    } else { 
     std::move( &names[drop + 1], &names[size], &names[drop]); 
     std::move(&sections[drop + 1], &sections[size], &sections[drop]); 
     std::move( &grades[drop + 1], &grades[size], &grades[drop]); 
    } 
} 

如果你的编译器不支持C++ 11只是改变std::movestd::copy在上面的代码。