Solved

does STL vector has a function to sort?

Posted on 2004-04-12
26
1,375 Views
Last Modified: 2013-12-14
This is just an example.
I have a vector of apples. An apple has 2 integers(int a, int b). Is there a STL library to sort the vector automatically by specified member(int a)..
thanks
0
Comment
Question by:Carl3003
  • 12
  • 8
  • 3
  • +2
26 Comments
 
LVL 11

Expert Comment

by:avizit
ID: 10810866
you can use

there is
1.  sort()
2.  stable_sort ()
3. partial_sort()

and you may have to write a function to compare two vectors.

check :  http://www.sgi.com/tech/stl/sort.html

/abhijit/
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10812465
You have algorithms

#include <algorithm>

There you have template versions of sort supporting stl containers.
 
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10812487
template<class RandomAccessIterator>
   void sort(
      RandomAccessIterator _First,
      RandomAccessIterator _Last
   );
template<class RandomAccessIterator, class Pr>
   void sort(
      RandomAccessIterator _First,
      RandomAccessIterator _Last,
      BinaryPredicate _Comp
   );
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10812500
You may use template sort functions like this:

void main()
{
    vector<string> words;
    string word;
    ifstream ifs("xx.txt");

    while (!ifs.eof())
    {
        ifs >> word;
        if (ifs.fail())
            break;
        words.push_back(word);
    }

   
    sort(words.begin(), words.end());
}

Note, while there is a std::list::sort() member function, sort() isn't a member of std::vector.

Regards, Alex
0
 

Author Comment

by:Carl3003
ID: 10815290
But how these examples fit with my example because my classs Apple has 2 members-id and quality and i want to sort the vector only by id?
0
 
LVL 6

Accepted Solution

by:
Mafalda earned 180 total points
ID: 10815514
#include <iostream>
#include <vector>

using std::vector;
using std::ostream;

  class A
  {
  public:
    A(int a, int b, int c) : _a(a), _b(b), _c(c)
    {}
    bool operator<(const A& a) const{ return _b < a._b;}
    void print() {std::cout << _a << ", " << _b << ", " <<  _c << std::endl;}
  private:
    int _a;
    int _b;
    int _c;
  };



int main(int argc, char * argv[])
{

  A a1(1,2,3);
  A a2(2,3,1);
  A a3(8,1,9);

  vector<A> v;

  v.push_back(a1);
  v.push_back(a2);
  v.push_back(a3);

  sort(v.begin(), v.end());
  v[0].print();
  v[1].print();
  v[2].print();

}
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10815526
output is ofcourse

8,1,9
1,2,3
2,3,1


And this becaus the operator< compares the _b member
0
 

Author Comment

by:Carl3003
ID: 10815687
Hi  Mafalda,
There was an error in the program when i compiled. I assumed that i have to use #include <algorithm> but it didnt work eaither. I am using VS c++. Below is the error message.

error C2065: 'sort' : undeclared identifier
warning C4508: 'main' : function should return a value; 'void' return type assumed
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 20 total points
ID: 10815709
you should have

using namespace std;

somewhere at top. Otherwise you have to use std::sort(..) instead of sort(..)

Regards, Alex
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10815722
Yes sorry,

for main

#include <algorithm>
using std::sort;

and omit
using std::ostream;
as it is not used


well you can always use once

using namespace std;

and then you do not need to specify each class used like:

using std::cout;
using std::endl;
using std::sort;


0
 
LVL 44

Assisted Solution

by:Karl Heinz Kremer
Karl Heinz Kremer earned 50 total points
ID: 10815729
You can also use the second version of the sort() command (the one with three parameters). The advantage of this is that your class does not have to define the < operator:

class CompareApples
{
public: // operator must be public
   bool operator()(const apple arg1, const apple arg2) const
   { return arg1._b < arg2._b; }
};


Then you call the sort function like this:
sort(appleVector.begin(), appleVector.end(), CompareApples);
0
 

Author Comment

by:Carl3003
ID: 10815754
it compiles. So basically this program orders the vector by _b  ?
0
 

Author Comment

by:Carl3003
ID: 10815787
bool operator<(const A& a) const{ return _b < a._b;}

 bool operator<(const A& a) const{ return _a< a._a;}

 bool operator<(const A& a) const{ return _c < a._c;}

in this way i can choose any member..
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10815840
You can have only one ... but you can have a condition in the function to decide which comparisson to do

In example (remember this is only an example !!!)

class A
{
...
  void set_sort(int sorted_by) { _sort_by = sorted_by;}
  bool operator<(const A& a) const{ if (_sort_by == 1)  
                                                        return _b < a._b;  
                                                    else
                                                         return _c < a._c;}

...


private:
  int _sort_by;
...

}
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10815859
By the way,  you can have a different operator< for each class you have !
For each type (class) you will decide how to sort
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10815890
class Orange : public Fruit
{
...
bool operator<(const Orange& a) const{ return _b < a._b;}
...
}

class Apple : public Fruit
{
...
 bool operator<(const Apple& a) const{ return _a< a._a;}
...
}
0
 
LVL 44

Assisted Solution

by:Karl Heinz Kremer
Karl Heinz Kremer earned 50 total points
ID: 10815919
If you want to sort your vector in different ways, use something like this:

class CompareApples_a
{
public: // operator must be public
   bool operator()(const apple arg1, const apple arg2) const
   { return arg1._a < arg2._a; }
};

class CompareApples_b
{
public: // operator must be public
   bool operator()(const apple arg1, const apple arg2) const
   { return arg1._b < arg2._b; }
};


sort(appleVector.begin(), appleVector.end(), CompareApples_a);
sort(appleVector.begin(), appleVector.end(), CompareApples_b);
0
 

Author Comment

by:Carl3003
ID: 10815920
Mafalda  thanks, i think that was enough information for me. I am going to try to implement it on my own program. Is there any way i can reach you in future in case i have any additional problems?
0
 

Author Comment

by:Carl3003
ID: 10815941
khkremer  thank you as well..
0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 10815972
You're welcome.
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10815992
I would of course appreciate if you accept my answer ... ;o)

You can always post here any aditional questions as I am still "hooked" to it
I will be happy to help "free of charge" ;o)



Cheers,
Mafalda
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10816013
For new issues it would be better to new questions so other experts can help you as well and benfit the points reward
0
 

Author Comment

by:Carl3003
ID: 10816082
Ok, i split the points in way i found each answer most helpful for me..
0
 

Author Comment

by:Carl3003
ID: 10816100
just one last question, is it possible to ask question through e-mail ?
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10816242
It is not advisable for several reasons, the main one in my opinion is that others can not benefit from the correspondance.
It is explained somewhere in the EE policies documents
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10821815
My comment about the points reward didn't sound like I wanted it to sound ... I am not a points freak ... it was a general comment.
Splitting the points was a good idea ;o)
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

821 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