Solved

sorting arrays

Posted on 2000-04-03
13
213 Views
Last Modified: 2013-12-14
Hi, experts:

I'd like to know if there is existing C/C++ code for sorting an array(int, float, or char) in descending order? and more, if it is an int array, I need to get rid of those elements whose value is 0, so the array will only contain non-zero values(the size is shrinking as well).  how do I achieve this? Do I have to use STL?

Thanks in advance.
0
Comment
Question by:Embt
  • 4
  • 3
  • 2
  • +3
13 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 2680597
The easiest solution - if you don't want to use STL - would be the CRT function 'qsort()'. But STL would make life easier anyway...
0
 
LVL 22

Expert Comment

by:nietod
ID: 2680618
I would use the qsort() as jkr said, and then remove the 0 entries using memmove().   Note that if there are no negative entries, then the 0 entries will occur at the end of the sorted items and there won't be any need to remove the 0 entries, jus ignore them.
0
 
LVL 86

Expert Comment

by:jkr
ID: 2680675
The main drawback using STL is that sorting is only implemented for lists and not vectors, thus creating a little bit overhead ;-)
0
 
LVL 22

Expert Comment

by:nietod
ID: 2680686
I don't think that is true.  Isn't the sort algorithm a generic template function that will work with any random access container?
0
 
LVL 9

Expert Comment

by:jasonclarke
ID: 2680756
You are correct about the STL sort algorithm nietod, it work just fine on vectors and anything else that has appropriate iterators.

std::list does, however have a sort method defined on it, which vector does not, maybe that is what jkr is referring too.

you could use the STL sort algorithm to sort a simple C array too.
0
 
LVL 22

Expert Comment

by:nietod
ID: 2680766
>> std::list does, however have a sort method
>> defined on it, which vector does not
That's was probably the problem.  I wonder why they didn't put a sort in both?

>> you could use the STL sort algorithm to sort a
>> simple C array too.
That's what I thought.  as far as the template is concerned, a pointer to an array item is the same as an iterator to a vector or list item..
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:jasonclarke
ID: 2680801
> I wonder why they didn't put a sort in both?

I think its because the std::vector doesn't need one.  vector has a random access iterator which means that the standard algorithm will work just fine.

list only has a forward iterator I think, so, std::sort will not work.


(BTW, see the horror of the compiler errors when you compile the following code with VC++ at least:

void main()
{
    std::list<int> l1;
    std::sort(l1.begin(), l1.end());
}

)

0
 

Author Comment

by:Embt
ID: 2681660
Thanks for the discussion, I ended up with using vector and doing the sorting, it works fine for the vector. however, it did not completely solve my problem. the actual thing I want to do is not just sorting the array(or vector), it is like the following.

1. I have a set of (string, float) value, I can either use map or array of structures to store them. if I use map, the key(string part) would be unique.

2. I need to sort the float value in the above in desceding order, and get rid of "0" value.

How do I do this?  can somebody give me some sample code? I would increase the points if needed. or do I need to repost it? I am not sure
0
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
ID: 2682142
If you use a map the data will be sorted (effectively sorted) automatically, but so if you just use a map and never add 0 entries, you will be done.

like

map<string,int> Map;

while (!Done)
{
   string S = ??; // I'm not sure where you get the data to be added.
   int I;

  if (I != 0)
    Map[string] = I;
}

That's about as much help as we can give you without more details from you.
0
 
LVL 6

Expert Comment

by:graham_k
ID: 2682440
hmm, never adding the zer0 entries is a clever solution.  Otherwise, use erase_if();
0
 
LVL 14

Expert Comment

by:AlexVirochovsky
ID: 2682626
Example of sorting strings:
http://www.snippets.org/strsort.C
0
 
LVL 9

Expert Comment

by:jasonclarke
ID: 2683118
Here is an example of using the STL with vectors to do what you want.  The remove_if, erase combination achieves the removal of the zeros is they are already there.

#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <iostream>

using namespace std;

struct myPair
{
    myPair(float v, const string& s)
        : mValue(v), mString(s) {}

    float       mValue;
    string      mString;

    class MatchValue : public binary_function<myPair, int, bool>
    {
    public:
        bool operator()(const myPair& match, int value) const
        { return match.mValue == value; }
    };

    bool operator<(const myPair& rhs)
    { return mValue < rhs.mValue; }
};

ostream& operator<<(ostream& o, const myPair& mp)
{
    o << "[" << mp.mValue << ", " << mp.mString << "]";
    return o;
}

void main()
{
    // Create and populate the vector
    vector<myPair> v;

    v.push_back(myPair(2,"a"));
    v.push_back(myPair(5,"b"));
    v.push_back(myPair(0,"c"));
    v.push_back(myPair(3,"d"));
    v.push_back(myPair(0,"e"));

    copy(v.begin(), v.end(), ostream_iterator<myPair>(cout, " "));
    cout << endl;

    // Sort it
    sort(v.begin(), v.end());  

    copy(v.begin(), v.end(), ostream_iterator<myPair>(cout, " "));
    cout << endl;

    // Remove the zeros
    vector<myPair>::iterator newEnd = remove_if(v.begin(), v.end(),
                                                bind2nd(myPair::MatchValue(), 0));

    v.erase(newEnd,v.end());

    copy(v.begin(), v.end(), ostream_iterator<myPair>(cout, " "));
    cout << endl;
}
0
 

Author Comment

by:Embt
ID: 2684127
Thanks all for the discussion, the issue is going to be closed. it is very hard to decide to give the credits to which one of you since you are all very helpful. Thanks!
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now