本帖最后由 ryxcaixia 于 2015-11-17 13:43 编辑 #include <stdio.h>
#include <stdlib.h>
#include <vector>;
#include <algorithm>
using namespace std;
void splitstr(const char* str, vector<string>* vec)
{
const char* iter = str;
const char* pos = str;
while (*iter != NULL)
{
pos = strchr(iter, ' ');
if (pos == NULL) // last char
{
vec->push_back(iter);
return;
}
char buf[0xF] = {0};
memcpy(buf, iter, pos - iter);
iter = pos+1;
vec->push_back(buf);
}
}
void _swap(int* lhs, int* rhs)
{
if (lhs == rhs) // not swap
return;
int tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
void sort_arr(int* arr, const int len)
{
int min = arr[0];
int min_pos = 0;
int max = arr[0];
int max_pos = 0;
// 找到最大值和最小值, 并记录下他们的位置
for (int i = 0; i != len; i++)
{
if (max < arr[i])
max = arr[i], max_pos = i;
if (min > arr[i])
min = arr[i], min_pos = i;
}
_swap(&arr[max_pos], &arr[len-1]); // 最大值与数组最后一个元素交换
_swap(&arr[min_pos], &arr[0]); // 最小值与数组第一个元素交换
}
int main()
{
// get the str
char buf[0xFF] = {0};
gets(buf);
// vec save the numbers(type string)
vector<string> vecstr;
vecstr.reserve(0xFF);
splitstr(buf, &vecstr);
// str(string) -> number(int)
vector<int> vecnum;
vecnum.reserve(vecstr.size());
for(vector<string>::const_iterator iter = vecstr.begin(); iter != vecstr.end(); iter++)
vecnum.push_back(atoi((*iter).c_str()));
// check
cout << "check stdin" << endl;
copy(vecnum.begin(), vecnum.end(), ostream_iterator<int>(cout, " "));
cout << endl;
// 如果楼主看不懂以上代码没有关系 上面的代码就是把标准输入的字符串 先转成一个一个字符串 再转成整数
// 看下面的就可以了, 结果是普通int数组, 方便楼主你理解
int* arr = (int*)malloc(sizeof(int) * vecnum.size());
int i = 0;
for(vector<int>::const_iterator iter = vecnum.begin(); iter != vecnum.end(); iter++)
arr[i++] = *iter;
// sort the array
int arr_len = vecnum.size();
sort_arr(arr, arr_len);
// after sort
printf("after the sort\n");
for (int i = 0; i != arr_len; i++)
printf("%d ", arr[i]);
printf("\n");
free(arr)
return 0;
}
|