struct
{
int a;
int b;
}s[100];
对于这个结构体数组,我想用sort函数给其中的a排序,但由于a和b是成组的,怎么能让a排序的时候,b跟着a?用sort函数
比如
a 1 5 3 2 4
b 7 8 9 0 6
我希望是
a 1 2 3 4 5
b 7 0 9 6 8
而用sort函数排序a却是
a 1 2 3 4 5
b 7 8 9 0 6
#include<stdio.h>
#include<algorithm>
using namespace std;
struct
{
int a;
int b;
}s[10];
int main()
{
int i;
for(i=0;i<5;i++)
scanf("%d%d",&s[i].a,&s[i].b);
int *p1=&s[0].a;
int *p2=&s[5].a;
sort(p1,p2);
for(i=0;i<5;i++)
printf("%d %d\n",s[i].a,s[i].b);
return 0;
}
就比如这样,不行。
#include <stdio.h>
struct
{
int a;
int b;
}s[100];
int main()
{
printf("请输入A的数据个数\n");
int n,t,k,i,j;
scanf("%d",&n);
printf("请输入a的值\n");
for(i=0;i<n;i++)
scanf("%d",&s[i].a);
printf("请输入b的值\n");
for(i=0;i<n;i++)
scanf("%d",&s[i].b);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(s[j].a>s[j+1].a)
{
t=s[j].a;
s[j].a=s[j+1].a;
s[j+1].a=t;
k=s[j].b;
s[j].b=s[j+1].b;
s[j+1].b=k;
}
}
}
for(i=0;i<n;i++)
printf("%d\t",s[i].a);
printf("\n");
for(i=0;i<n;i++)
printf("%d\t",s[i].b);
return 0;
}
/*
* File: main.cpp
* Author: chujiangke
*
* Created on 2013年3月30日, 上午1:37
*/
#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
#include<functional>
#include<cstdlib>
#include<cstdio>
using namespace std;
class Node
{
int a;
int b;
public:
Node(int aa=0,int bb=0){this->a=aa;this->b=bb;}
void show(){cout<<"a:"<<a <<" b:"<<b<<endl ;}
int get_a(){return a;}
int get_b(){return b;}
};
bool judgement(Node a,Node b)
{
if( a.get_a()<b.get_a())
{
return true;
}
return false;
}
int main()
{
vector<Node> Nodevector;
int a, b;
cout<<"input the a and b : ";
while(cin>>a>>b)
{
Node temp(a,b);
Nodevector.push_back(temp);
cout<<"input the a and b : ";
}
sort(Nodevector.begin(),Nodevector.end(),judgement);
for(int i=0;i<Nodevector.size();++i)
Nodevector[i].show();
}
default (1)template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)template <class RandomAccessIterator, class Compare>void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
第2种方式,
// sort algorithm example需要你有一定理解能力.