[置顶] 练手小程序3.按给定的字母顺序打印字符串

题目:已知字母序列【d, g, e, c, f, b, o, a】,请实现一个函数针对输入的一组字符串 input[] = {"bed", "dog", "dear", "eye"},按照字母顺序排序并打印,结果应为:dear, dog, eye, bed。

考察知识点:字符串的大小比较

代码如下:

#include "stdafx.h"
#include <map>
#include <assert.h>
#include <vector>
#include <algorithm>
#include <iostream>

std::map<char, int> char_int_map;

//比较两个字符串的大小(此函数纯属练手)
//str_a大于str_b,则返回1;相等则返回0;小于则返回-1
int compare_string(char *str_a, char *str_b)
{
	assert(str_a != NULL && str_b != NULL);
	int result = 0;
	char *pa = str_a;
	char *pb = str_b;

	while (*pa != '\0' && *pb != '\0')
	{
		if (*pa != *pb)
		{			
			if (char_int_map.find(*pa) == char_int_map.end())
			{
				char_int_map[*pa] = 0;
			}

			if (char_int_map.find(*pb) == char_int_map.end())
			{
				char_int_map[*pb] = 0;
			}

			result = char_int_map[*pa++] < char_int_map[*pb++] ? -1 : 1;
			return result;
		}

		++pa;
		++pb;
	}

	if (*pa != '\0')
	{
		result = 1;
	}

	if (*pb != '\0')
	{
		result = -1;
	}

	return result;
}

//定义排序规则
bool compare(char *str_a, char *str_b)
{
	assert(str_a != NULL && str_b != NULL);
	bool result = true;
	char *pa = str_a;
	char *pb = str_b;

	while (*pa != '\0' && *pb != '\0')
	{
		if (*pa != *pb)
		{			
			if (char_int_map.find(*pa) == char_int_map.end())
			{
				char_int_map[*pa] = 0;
			}

			if (char_int_map.find(*pb) == char_int_map.end())
			{
				char_int_map[*pb] = 0;
			}

			return char_int_map[*pa++] < char_int_map[*pb++];			 
		}

		++pa;
		++pb;
	}

	if (*pa != '\0')
	{
		result = false;
	}

	if (*pb != '\0')
	{
		result = true;
	}

	return result;
}

void create_char_num_map(char *char_arr, int nlength)
{
	int number = 0;
	char c;

	for (int i = 0; i < nlength; ++i)
	{
		c = char_arr[i];
		char_int_map[c] = ++number;
	}
}

//按给定的字符序列排序并打印字符串
void sort_str_arr(char **input, int nlength)
{
	std::vector<char *> string_vec;	
	for (int j = 0; j < nlength; ++j)
	{
		string_vec.push_back(input[j]);
	}

	std::sort(string_vec.begin(), string_vec.end(), compare);

	for (std::vector<char *>::iterator iter = string_vec.begin();
		iter != string_vec.end(); ++iter)
	{
		std::cout << *iter << " ";
	}

	std::cout << std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	char char_arr[8] = {'d', 'g', 'e', 'c', 'f', 'b', 'o', 'a'};
	char *input[4] = {"bed", "dog", "dear", "eye"};
	create_char_num_map(char_arr, 8);
	sort_str_arr(input, 4);
	system("pause");
	return 0;
}


你可能感兴趣的:([置顶] 练手小程序3.按给定的字母顺序打印字符串)