【发布时间】:2015-04-30 21:28:51
【问题描述】:
我编写了一些代码,旨在使用基数排序对字符串数组进行排序,从最低有效数字开始。此函数假定所有字符串的长度相同,并且每个字符都是小写的。
每当我进入将值分配给临时数组的循环时,我都会遇到崩溃。你可以在这里看到我的功能:
#ifndef RADIX_H
#define RADIX_H
#include <string>
#include <iostream>
using namespace std;
void lsd_string_radix(string array[], int array_size, int max_chars)
{
string *temp = new string[array_size];
for(int i = max_chars - 1; i >= 0; i--)
{
int count[26] = {0};
for(int j = 0; j < array_size; j++)
{
count[static_cast<int>(array[j][i]) - 97]++;
}
for(int j = 1; j <= 26; j++)
{
count[j] += count[j - 1];
}
for(int j = 0; j < array_size; j++)
{
temp[count[static_cast<int>(array[j][i])]++] = array[j]; // crashes here
}
for(int j = 0; j < array_size; j++)
{
array[j] = temp[j];
}
}
}
#endif
我猜我的逻辑有问题,但我一辈子都想不通。
【问题讨论】:
-
您是否只是在它崩溃的行中缺少
-97? -
string array[]作为const &std::vector<std::string>参考值传入的值可能会好很多。积极使用static_cast进行排序也可能适得其反。为什么不转换和排序?标准容器使这很容易实现。
标签: c++ arrays string sorting radix-sort