如何在C ++中使用一维数组按升序(从A-Z)对名称进行排序 [英] How do I sort the names in ascending order (from A – Z) using a one-dimensional array in C++

查看:92
本文介绍了如何在C ++中使用一维数组按升序(从A-Z)对名称进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此程序将询问十个名称的列表,然后按升序对名称进行排序(从A - Z开始)。



我的问题是程序赢了因为它有错误而运行。

This program will ask for the list of ten names then sort the names in ascending order (from A – Z).

My problem is that the program won't run because it has an error.

#include<iostream.h>

main()
{
 char str[10];
 char g;

 for(int j=0; j<10; j++)
  {
     cin>>str[j];
    for(int i=0; i<10; i++)
     {
      if(str[i]>str[i+1])
        {
         g=str[i];
         str[i]=str[i+1];
         str[i+1]=g;
        }
     }
  }
 for(int y=0; y<10; y++)
  {
    cout<<str[y];
  }
 return 0;
}



链接器警告:没有指定模块定义文件:使用默认值

所以什么是错的我的节目?我真的不明白这个错误。

请帮我修改我的代码,使其成功运行。


Linker Warning: No module definition file specified: using defaults
So whats wrong with my program? I really don't understand the error.
Please help me revise my code so that it will run successfully.

推荐答案

#include<iostream.h>

int main(int argc, char* argv[])
{

 char *str[10];
 char *g;
 
 for(int j=0; j<10; j++)
  {
	 str[j]= new char[255];
     cin>>str[j];
 }

 for(int k=9;k>=0;k--)
    for(int i=0; i<k; i++)
     {
      if(*str[i]>*str[i+1])
        {
         g=str[i];
         str[i]=str[i+1];
         str[i+1]=g;
        }
     }
	cout << "----" <<endl;
  
 for(int y=0; y<10; y++)
  {

    cout<<str[y]<< endl;
	delete[] str[y];
  }

 return 0;
}





注:

1. char * str [10]是一个数组10个char指针

2.所以你需要为这些指针分配内存因此

str [j] = new char [255];

3.对于g来引用str [i],g也必须是一个指针

char * g

4.我们需要在退出之前清理内存因此

delete [] str [y]



Note:
1. char *str[10] is an array of 10 char pointers
2. so you need to allocate memory for these pointer thus
str[j]= new char[255];
3. for g to refer to str[i], g must also be a pointer
char *g
4. we need clean up memory before exit thus
delete[] str[y]


嘿,这是C ++!为什么不使用 std :: string std :: vector std :: qsort

你的编码很简单C.

干杯

Andi
Hey, this is C++! Why don't you use std::string, std::vector, and std::qsort?
Your coding is plain old C.
Cheers
Andi


你好

如果你再次查找你的程序你看到str数组不是一个字符串数组但只是字符数组可能是这个问题

你可以使用下面的声明:



hello
if you looking up again your program you see that the str array isn't a string array but just character array may be this is the problem
you sould be use the declaration bellow:

char *str[10];





您可以使用其中一种排序算法(例如按选择排序)



After you can use one of sorting algorithms (e.g sort by selection)


这篇关于如何在C ++中使用一维数组按升序(从A-Z)对名称进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆