I have a basic struct which contains an amount and a date. Then I have
an aggregate (should I use a list or a vector?) of the basic struct. I
need to sort the {list, vector} based on one of the above mentioned
fields.
An example would be nice.
Thx,
-RFH
I already discovered algorithm::sort(), so it looks like instead of
using a list or a vector, I should use an old fashioned array?
-RFH
I googled(tm) for
sort struct in c++ -bubble
and found
http://www.daniweb.com/forums/thread178418.html
LR
If you read the documentation on sort you will find that it works fine
on a std::vector. By default it sorts using 'less than' (assuming
operator < has been defined for the type) but you can provide a
comparison function as the last (optional) argument.
> I have a basic struct which contains an amount and a date. Then I have
> an aggregate (should I use a list or a vector?)
It depends. :) The standard specifically says that all things being
equal, you should usually choose vector. vector has more flexible
iterators, uses contiguous memory, and has some other nice properties.
> of the basic struct. I
> need to sort the {list, vector} based on one of the above mentioned
> fields.
See:
http://www.sgi.com/tech/stl/sort.html
http://www.sgi.com/tech/stl/stable_sort.html
> An example would be nice.
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <list>
#include <vector>
namespace {
typedef long integer_t;
struct point_t
{
integer_t x;
integer_t y;
};
point_t make_random_point() {
point_t const result = { std::rand(), std::rand() };
return result;
}
bool x_less(point_t const& a, point_t const& b) {
return a.x < b.x;
}
}
int main() {
std::size_t const size = 20;
std::vector<point_t> vec( size );
std::generate(vec.begin(), vec.end(), make_random_point);
std::sort(vec.begin(), vec.end(), x_less);
std::list<point_t> lst;
std::generate_n(back_inserter(lst), size, make_random_point);
lst.sort(x_less);
return EXIT_SUCCESS;
}
It does?
(...)
23.1.1 Sequences [lib.sequence.reqmts]
...
2. vector, list, and deque offer the programmer different complexity
trade-offs and should be used accordingly. vector is the type of
sequence that should be used by default.
Thank you. I admit I was not aware that the standard made
recommendations.
sincerely,
- Anand