【发布时间】:2018-04-19 11:17:04
【问题描述】:
我正在创建一个程序,该程序在数组大小为 8 的随机位置创建一个对象数组。创建后,我需要对它们进行排序,以便数组中的所有对象都向上移动,因此没有间隙存在于他们之间。我快到了,但我似乎无法让它们交换到数组中的索引 0,而是交换到索引 1。有什么建议吗? (必须按照我的方式完成,而不是使用其他排序算法或其他)
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct WordCount {
string name = "";
int count = 0;
};
int main() {
cout << "Original random array: " << endl;
srand(static_cast<int>(time(0)));
int i = 0;
WordCount wordArr[8];
while (i < 4) {
int randomNum = 0 + (rand() % static_cast<int>(7 + 1));
if(wordArr[randomNum].name == "") {
wordArr[randomNum].name = "word" + static_cast<char>(i);
wordArr[randomNum].count = i;
i++;
}
}
int j = 0;
while (j < 8) {
cout << wordArr[j].name << " " << wordArr[j].count << endl;
j++;
}
cout << "\n\nSorted array: " << endl;
for (int i = 7; i >= 0; i--) {
for (int j = 0; j <= 7; j++) {
if (wordArr[i].name != "") {
if (wordArr[j].name == "") {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
}
int k = 0;
while (k < 8) {
cout << wordArr[k].name << " " << wordArr[k].count << endl;
k++;
}
return 0;
}
【问题讨论】:
-
C++ 数组没有间隙。
-
@juanchopanza 他的意思是零。检查我的答案。
-
一旦你完成了这个手动操作的练习,请查看
std::partition,它是作为标准一部分的经过良好测试的单个函数调用。请不要错误地认为标准算法会带来惩罚或需要外部库,或者在某种程度上不是“真正的”C++。它们不是,它们是 C++ 的一部分,供您使用。
标签: c++ arrays algorithm loops sorting