void alphaout()
{
nodealpha *curr;
nodealpha *curr2;
curr = first;
curr2 = first;
while (curr != NULL)
{
char al1 = curr2 -> alpha;
char al2 = curr -> alpha;
if (al1 < al2)
{
curr2 = curr;
}
std::cout << "ALPHABET : " << curr -> alpha << endl;
curr = curr -> next;
}
}
我制作了一个简单的程序,用户输入每个字母,然后按顺序显示它,而不管用户输入字母的方式如何,但问题是,当它播放字母表的顺序与用户输入的顺序相同时,我无法弄清楚如何以 a 到 z 的方式排列它
我可以想到两种不同的方法,第一种,您可以使用其 ascii 代码的索引将节点的地址保存在数组中:
// here is a function i made for an old project which will give you the index in an array
//of any char you pass to it (sorry for spanish comments but that's my my teacher
//asked for)
int position(char letter)
{
int valor;
//A-ascii 65 -> posicion 0 a-ascii 97 -> 0
//Z-ascii 90 -> posicion 25 z->ascii 122 - 25
if(letra>='A' && letra <='Z')
valor = letra - 65;
else if(letra >='a' && letra<='z')
valor = letra-97;
else
valor= 26; //
return valor;
}
// this is what i would put in your alphaout function to store the ponters
// here we save the pointers to each letter
nodealpha *alpha[size of your aplhabet];
while(curr != NULL){
alpha[position(curr->alpha)] = curr;
curr = curr->next;
}
// after this you can just print the array
cout << "alphabet: " << endl;
for(int i = 0; i < (size of alphabet); i++){
cout << alpha[i]->alph << ", ";
}
这样做的缺点是它不会考虑重复项,它只会成为每个字母的最后一个实例。
至于另一种方法,您可以为字母表中的每个字母扫描一次列表并立即打印出来,但这显然需要更多时间才能完成,但它会计算重复项。
由于字符由ASCII
组成,而ASCII
由数字组成,我们可以首先将char
类型转换为数组中的int
类型,然后通过使用qsort()
我们可以正确重新排列它们。然后在重新排列时将它们重新转换为char
。
以下代码是一个示例:
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
int main ()
{
std::ios_base::sync_with_stdio(false);
std::string order;
std::cout << "Input the alphabet order: ";
std::getline(std::cin, order);
int Alphabet[26];
std::string::iterator iter;
for(iter = order.begin();iter != order.end(); iter++){
Alphabet[order.find(*iter)] = *iter;
}
qsort (Alphabet, order.length(), sizeof(int), [](const void* a, const void* b)->int{
return (*(int*)a - *(int*)b );
});
std::vector<int> Filter;
for(int x = 0; x < order.length(); x++){
if(std::find(Filter.begin(), Filter.end(), Alphabet[x]) == Filter.end()){
Filter.push_back(Alphabet[x]); // to filter out repetitive characters.
}
}
std::vector<int>::iterator Iter;
std::cout << "ALPHABET: ";
for(Iter = Filter.begin(); Iter != Filter.end(); Iter++){
std::cout << static_cast<char>(*Iter);
}
std::cout << std::endl;
return 0;
}