【发布时间】:2016-01-17 20:53:49
【问题描述】:
我正在尝试做一个简单的练习,我想从用户输入中填充一个整数数组,并保持输入的顺序,这样就不需要在用户完成后对数组进行排序。
假设数组的状态是这样的:{ 3, 5, 7, 8, 9,-,-,-,-,- }(- 表示空)
现在在这种状态下,比如输入6,arr[1]后面的所有元素都应该向前移动一位,这样6就可以放在arr[2]中了。
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
bool ok = true;
int x // the input
, n = 0 // to keep track of numbers already in the array
, i, j // to iterate in loops
, arr[10];
cout << "Enter 10 numbers: \n";
while (cin >> x) {
if (n == 0) { arr[n] = x; n++; } // for the first entry.
else if (x < arr[0]) { // is x lower than the first element in the array?
for (i = n; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = x; n++;
}
else if (x > arr[n - 1]) { // is x greater than the top of already addded
// elements to the array?
arr[n] = x; n++;
}
else { // when x is in between of elements. Also I think the problem is here.
for (i = 0; i < n && ok; i++)
if (x > arr[i] && x < arr[i + 1]) {
for (j = n; j > i + 1; j--)
arr[j] = arr[j - 1];
ok = false;
}
arr[i + 1] = x; n++;
}
if (n == 10) break; // if you reached to end of the array, break while.
}
for (i = 0; i < 10; i++)
cout << arr[i] << " ";
cin.get();
cin.get();
}
这段代码有很多问题,但是当我尝试输入时:1、10、2、3、4、5、6、7、8、9 程序不会将 10 移动到数组结束,输出:1, 10, 2, 3, 4, 5, 6, 7, 8, 9。
【问题讨论】:
-
您所说的是“容器”。您可以使用二叉树来做到这一点,但最好的是 AVL 树。你仍然可以这样做,但是使用树来代替更有效。 stl 中已经有容器,请参阅 Pustovalov 评论。
-
你为什么不想使用 std::set 自动排序它的值?还是必须使用 C 风格的数组?
-
std::set<int> arr; while (cin >> x) arr.insert(x);3 班轮。 -
@PierreEmmanuelLallemant AVL 不是最好的。 RB 更快。
-
@SashaMN:AVL 比红黑树更严格地平衡,导致插入和删除速度较慢,但检索速度更快(维基百科)。
标签: c++ arrays sorting console-application