c++ - 反转后不返回最后一个元素
问题描述
所以我必须编写一个程序,首先放入一个字符串数组,然后插入排序,输出,然后反转数组并再次输出。我只是有一个小问题。最后一个元素(反转后,最初是第一个元素)不打印?我打赌这很容易解决,但是有人知道如何解决吗?任何帮助表示赞赏!谢谢!
#include <iostream>
#include <string>
using namespace std;
string insertionSort(string[], int);
string reverseSort(string[], int);
string insertionSort(string words[], int numWords) {
int i = 0;
int j = 0;
string temp = "";
for (i = 0; i < numWords; i++) {
j = i;
while (j > 0 && words[j] < words[j - 1]) {
temp = words[j];
words[j] = words[j - 1];
words[j - 1] = temp;
j--;
}
}
return temp;
}
string insertionSortRev(string words[], int numWords) { //reverse array
int start = 0;
int end = numWords;
string temp = "";
while (start < end) {
string temp = words[start];
words[start] = words[end];
words[end] = temp;
start++;
end--;
}
return temp;
}
int main() {
string words[] = {"", "", "", "", "", "", "", "", "", ""};
int numWords = 0;
cin >> numWords;
for (int i = 0; i < numWords; i++) {
cin >> words[i];
}
cout << "UNSORTED: ";
for (int i = 0; i < numWords; i++) {
cout << words[i] << " ";
}
cout << endl;
insertionSort(words, numWords);
cout << "SORTED: ";
for(int z = 0; z < numWords; z++) {
cout << words[z] << " ";
}
cout << endl;
insertionSortRev(words, numWords);
cout << "REVERSED: ";
for (int k = 0; k < numWords; k++) {
cout << words[k] << " ";
}
cout << endl;
return 0;
}
解决方案
一个大小数组的s
索引从0
到s-1
。在你的 reverse 函数中,写end = numWords - 1;
而不是end = numWords
.
推荐阅读
- jenkins - Jenkins管道:如何强制构建等待先前的构建完成
- list - 在 DrRacket 中,我如何制作列表列表
- java - 我需要把41.32万亿放在Java上的一个变量中,但是long数据类型只限于4万亿
- ruby-on-rails - Rails 样式在页面之间持续存在
- unit-testing - Visual Studio 调试器行为怪异
- c# - 试图发送正确形成的对象来查看
- javascript - 如何获取两个属性的值并将其放入另一个属性中?
- intellij-idea - 在intellij idea中,如何在不使用箭头键的情况下在智能建议列表中选择建议项?
- javascript - 如何将当前 URL 参数添加到页面上的所有链接
- angular - 来自角度对象的Graphql输入对象