更快的方式进行排序结构C数组++ [英] Faster way to sort an array of structs c++
问题描述
我有一个名为伯爵宣称所谓的数在它两件事结构,一个int叫做频率,串词叫。为了简化,我的计划需要在一本书作为一个文本文件,我算多少次出现的每个字。我有结构的数组,我有我的计划,其将各出现一个词的时间算,现在我想通过上面的频率比我有以下方式对数组进行排序更快的方法。我用冒泡排序算法,下面却是把我的code太长用这种方法来运行。任何其他建议或帮助将受到欢迎!我从算法库抬头排序,但不明白我怎么会在这里使用它。我是新的C ++如此大量的解释如何使用排序将有很大的帮助。
无效sortArray(结构计算[]数组,INT大小)
{
INT CUR_POS = 0;
串the_word;
布尔标志= TRUE; 对(INT I = 0; I&≤(大小);我+ +)
{
标志= FALSE;
为(中间体J = 0; J&≤(大小); J ++)
{
如果((数组[J + 1]。频率)GT;(阵列[J]。频率))
{
CUR_POS =阵列[J]。频率;
the_word =阵列[J] .word;
阵列[J]。频率=阵列[J + 1]。频率;
阵列[J] .word =阵列[J + 1] .word;
数组[J + 1]。频率= CUR_POS;
数组[J + 1] .word = the_word;
标志=真实的;
}
}
}
};
您只需要更少的定义运营商的结构,
并使用std ::排序,见例如:
http://en.wikipedia.org/wiki/Sort_% 28C%2B%2B%29
I have a struct called count declared called count with two things in it, an int called frequency and a string called word. To simplify, my program takes in a book as a text file and I count how many times each word appears. I have an array of structs and I have my program to where it will count each time a word appears and now I want a faster way to sort the array by top frequency than the way I have below. I used the bubble sorting algorithm below but it is taking my code way too long to run using this method. Any other suggestions or help would be welcome!! I have looked up sort from the algorithm library but don't understand how I would use it here. I am new to c++ so lots of explanation on how to use sort would help a lot.
void sortArray(struct count array[],int size)
{
int cur_pos = 0;
string the_word;
bool flag= true;
for(int i=0; i<(size); i++)
{
flag = false;
for(int j=0; j< (size); j++)
{
if((array[j+1].frequency)>(array[j].frequency))
{
cur_pos = array[j].frequency;
the_word = array[j].word;
array[j].frequency = array[j+1].frequency;
array[j].word = array[j+1].word;
array[j+1].frequency = cur_pos;
array[j+1].word = the_word;
flag = true;
}
}
}
};
You just need to define operator less for your structures, and use std::sort, see example:
http://en.wikipedia.org/wiki/Sort_%28C%2B%2B%29
这篇关于更快的方式进行排序结构C数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!