C + + string ordering

Source: Internet
Author: User

Section One title : Enter ten equal-length strings in the main function, and sort them with another function. The main function then outputs this sequence of strings.

It is done in two ways.

method One : Using two-dimensional array to do function parameters;

method Two : use pointers to one-dimensional arrays for function parameters.

Method 1:2-dimensional array:

#include <iostream>

#include <string.h>

using namespace Std;

int main ()

{

Char str[10][20];

cout<< "input strings in the same length:" <<endl;

for (int i=0;i<10;i++) cin>>str[i];

void sort (char [10][20]);

Sort (str);

cout<< "Now the sorted strings is:" <<endl;

void print (char [10][20]);

Print (str);

return 0;

}

void sort (char a[10][20])

{

for (int i=0;i<10;i++)

{int K=i;char t[20];

for (int j=i;j<10;j++)

if (strcmp (A[j],a[k]) <0)

{

strcpy (T,a[j]); strcpy (A[j],a[k]); strcpy (a[k],t);

}

}

}

void print (char a[10][20])

{

for (int j=0;j<10;j++) cout<<a[j]<<endl;

}

Operation Result:

Method Two: use pointers to one-dimensional arrays for function parameters :

#include <iostream>

#include <string.h>

using namespace Std;

int main ()

{

char (*p) [10];char ch[10][10];

cout<< "Input strings:" <<endl;

for (int i=0;i<10;i++) cin>>ch[i];

P=ch;

void Sort (char (*) [10]);

Sort (p);

cout<< "Now the Strings is:" <<endl;

for (int j=0;j<10;j++) cout<<p[j]<<endl;

return 0;

}

void sort (char (*p) [10])

{

for (int i=0;i<10;i++)

{int K=i;char t[10];

for (int j=i;j<10;j++)

if (strcmp (P[j],p[k]) <0)

{

strcpy (T,p[j]); strcpy (P[j],p[k]); strcpy (p[k],t);

}

}

}

Operation Result:

C + + string ordering

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.