how to 'group' an array by STL ?

Discussion in 'C++' started by William, Jan 18, 2007.

  1. William

    William Guest

    for example, there is an array: int a[]={2, 3, 1,3, 2,1};
    i want to group it as: {2,2,3,3,1,1} , not care the order.

    i can use std::sort( &a[0], &a[len-1]);
    but this will also sort the array which will get less performance than
    group.

    how to do this by STL ? thanks
     
    William, Jan 18, 2007
    #1
    1. Advertising

  2. On Jan 18, 10:46 am, William <> wrote:
    > for example, there is an array: int a[]={2, 3, 1,3, 2,1};
    > i want to group it as: {2,2,3,3,1,1} , not care the order.
    >
    > i can use std::sort( &a[0], &a[len-1]);
    > but this will also sort the array which will get less performance than
    > group.


    You probably want the partition algorithm, take a look at
    http://www.cppreference.com/cppalgorithm/partition.html for more info.

    --
    Erik Wikström
     
    =?iso-8859-1?q?Erik_Wikstr=F6m?=, Jan 18, 2007
    #2
    1. Advertising

  3. William

    Ondra Holub Guest

    William napsal:
    > for example, there is an array: int a[]={2, 3, 1,3, 2,1};
    > i want to group it as: {2,2,3,3,1,1} , not care the order.
    >
    > i can use std::sort( &a[0], &a[len-1]);
    > but this will also sort the array which will get less performance than
    > group.
    >
    > how to do this by STL ? thanks


    You can do something like:

    int* from = &a[0];
    while (from != &a[LEN])
    from = std::partition(from + 1, &a[LEN],
    std::bind1st(std::equal_to<int>(), *from));

    But I do not think you will gain better performance than with std::sort.
     
    Ondra Holub, Jan 18, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Akaketwa
    Replies:
    1
    Views:
    4,948
    impaler
    Sep 22, 2006
  2. Replies:
    0
    Views:
    548
  3. christopher taylor
    Replies:
    0
    Views:
    421
    christopher taylor
    Sep 17, 2008
  4. cpld-fpga-asic
    Replies:
    13
    Views:
    1,205
    rickman
    Jul 6, 2009
  5. Dag Sunde
    Replies:
    0
    Views:
    128
    Dag Sunde
    Nov 18, 2005
Loading...

Share This Page