此代码应该创建一个字符串数组,然后将它们随机排序,然后打印订单。不幸的是,它在其中一个空格中添加了空行(我认为这是getline的做法)。任何想法如何解决这个问题?我试着设置数组[0] = NULL;它抱怨运营商...排序字符串排列数组
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <string>
#include <cstdlib>
using std::cout;
using std::endl;
using namespace std;
void swap (string &one, string &two)
{
string tmp = one;
one = two;
two = tmp;
}
int rand_loc (int size)
{
return (rand() % size);
}
int main()
{
srand(time(NULL));
int size;
cin >> size;
string *array = new string[size];
//array[0] = NULL ;
for (int x = 0; x < size; x++)
{
getline(cin, array[x]);
}
//for (int x = 0; x < size; x++)
//{
// swap (array[rand_loc(size)], array[rand_loc(size)]);
//}
cout << endl;
for (int x = 0; x < size; x++)
{
//out << array[x] << endl;
int y = x + 1;
cout<<y<<"."<<" "<<array[x]<<endl;
}
delete[] array;
}
你不需要编写自己的'swap()',在STL中有一个['swap()'](http://www.cplusplus.com/reference/algorithm/swap/)。 – Johnsyweb 2011-05-28 09:49:13