Solved

does STL vector has a function to sort?

Posted on 2004-04-12
26
1,350 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
Comment Utility
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
Comment Utility
You have algorithms

#include <algorithm>

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

Expert Comment

by:Mafalda
Comment Utility
template<class RandomAccessIterator>
   void sort(
      RandomAccessIterator _First,
      RandomAccessIterator _Last
   );
template<class RandomAccessIterator, class Pr>
   void sort(
      RandomAccessIterator _First,
      RandomAccessIterator _Last,
      BinaryPredicate _Comp
   );
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
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
Comment Utility
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
Comment Utility
#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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
it compiles. So basically this program orders the vector by _b  ?
0
 

Author Comment

by:Carl3003
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 6

Expert Comment

by:Mafalda
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
khkremer  thank you as well..
0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
Comment Utility
You're welcome.
0
 
LVL 6

Expert Comment

by:Mafalda
Comment Utility
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
Comment Utility
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
Comment Utility
Ok, i split the points in way i found each answer most helpful for me..
0
 

Author Comment

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

Expert Comment

by:Mafalda
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org (http://seleniumhq.org) Go to that link and select download selenium in the right hand columnThat will then direct you to their downlo…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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…

762 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

11 Experts available now in Live!

Get 1:1 Help Now