10/21/2011

STL vector(with 2 more elements) sorting code / STL에서 2개 이상의 엘리먼트를 가지고 있는 vector 정렬 code

The source is simple but I always don't remember the code well.
If you similar to me, refer to my code easily.


#include <iostream>
#include <cmath>
#include <time.h>
#include <vector>
#include <algorithm>
using namespace std;

class element{
public:
    element(float a, int b){
        value = a;
        index = b;
    }
    float value;
    int index;
};

bool compare(const element &a, const element &b )
{
    return a.value < b.value; //오름차순(ascending order)
    //return a.value > b.value; //내림차순(descending order)
}

void main()
{
    srand( (unsigned int)time(NULL));

    vector< element > A;

    // 값 넣기 (input value)/////////////////////////////////////////////
    for(int i=0; i<20000; ++i){
        A.push_back( element(rand()%10, i) );
    }


    //값 출력  (data print)///////////////////////////////////////////////
    printf("정렬 전(Before ordering) \n");
    for(i=0; i<20000; ++i){
        printf("A[%d] -> value %f :: index -> %d\n", i, A[i].value, A[i].index );
    }


    //정렬 (sorting)
    sort(A.begin(),A.end(),compare);


    //값 출력 (Value print)
    printf("정렬 후(After ordering)\n");
    for(i=0; i<20000; ++i){
        printf("A[%d] -> value %f :: index -> %d\n", i, A[i].value, A[i].index );
    }
      
}

No comments:

Post a Comment