Solved

sorting arrays

Posted on 2000-04-03
13
219 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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
 
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C++ Language error 28 214
IdTCPClient1->Disconnect(); not working 3 66
C++ mouse_event mouse look 7 82
Embarcadero C++ Builder XE10.1 Berlin red arrow Indicator 2 34
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

816 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