基数排序与C ++崩溃中的向量向量

时间:2011-11-23 02:17:38

标签: c++ vector radix-sort

我正在尝试编写一个基数排序,它使用随机数向量和向量的向量向量。

这是代码,错误在收集和/或分发功能的某个地方 - 任何帮助都会受到赞赏,我只是没有发现它。它没有给我一个错误消息,只是崩溃。这是我的代码:

#include <iostream>
#include <vector>
#include <ctime>


using namespace std;

void distribute(vector<int> & myList, vector< vector<int> > & bins, int place);
void gather(vector<int> & myList, vector< vector<int> > & bins);
int getNumDigits(vector<int> myList);


int main(){
    int place = 1;
    vector<int> myList(20);
    vector< vector<int>  > bins;


    //initialize the vector
    srand((unsigned)time(0));

    for (int i = 0; i < myList.size(); i++){

        myList[i] = rand() % 300;
    }

    //get mumber of digits of largest

    place = getNumDigits(myList);

    cout << "Unsorted list: " << endl ;
    for (int i = 0; i < myList.size(); i++){

        cout << myList[i] << " ";
    }

    distribute(myList, bins, place);
    gather(myList, bins);

cout << endl << "Sorted once " ;

for (int i = 0; i < myList.size(); i++){

 cout << myList[i] << " ";
 }

system("pause");
return 0;

}//end main

void distribute(vector<int> & myList, vector< vector<int> > & bins, int place){


bins.clear();

int modder = place * 10;


for (int i = 0; i < myList.size(); i++){

    bins[(myList[i]) % modder].push_back(myList[i]);

    }//endfor  (myList[i]) % modder



}//end distribute


void gather(vector<int> & myList, vector< vector<int> > & bins){

 for (int i = 0; i < 10; i++){
     for (int j = 0; j < bins[i].size(); j++){

         myList.push_back(bins[i][j]);

     }//end inner
 }//end outer

 }

int getNumDigits(vector<int> myList){

 int place = 0;
 int biggest = 0;
 for (int i = 0; i < myList.size(); i++){

     if (myList[i] > biggest)
         biggest = myList[i];

     }

 while (biggest > 0){
     place++;
     biggest = biggest / 10;
     }

 return place;

}

2 个答案:

答案 0 :(得分:1)

for (int j = 0; j < bins[i].size(); i++)看起来不正确。

我想你的意思是j++,而不是i++

答案 1 :(得分:1)

bins中的distribute向量空间不足。将其开头改为:

bins.clear();

int modder = place * 10;

bins.resize(modder);

向量会在向其添加项目时自动调整大小,但您无法在不调整大小的情况下访问超出矢量大小的项目。