Using operators and STL containers

Started by
2 comments, last by Trajar 23 years, 11 months ago
I have a class for, which I will need to put into a linked list. This list may get quite large (it hold ALL world obj) and I thought I should use the STL for speed. However, I want to order the items in the list by their Y pos. Using my own linked list, I could overide the + and - operators to check, but with the STL, how do you do these checks to put an item IN A SPECIFIC point in the list? In case your wondering, no I don''t know a lot about STL, and I''m sure there is an stupidly easy way to do this, I am just no familiar with the STL... Thanks in advance Trajar
Advertisement
I don''t know off the top of my head, but you should check out Bjarne Stroustrup''s book "The C++ Programming Language"
He''s the guy who created c++ and the book has just about everything you need to know about c++ and the STL.
I''d use std::lower_bound. std::lower_bound returns the first position where an element can be inserted without violating the order of the list. std::lower_bound returns an iterator to that position, and has the range to search in, the value to find and a function object for comparison as parameters.

Usage:
list<el_type> lst;

struct less : public binary_function<el_type, el_type, bool> {
bool operator()(const el_type &e1, const el_type &e2) { return e1.y < e2.y; }
};

list<el_type>::iterator it = std::lower_bound(lst.begin(), lst.end(), new_el.y, less);

lst.insert(it, new_el);

Hope this helps,

Erik
If you want all of the items in your container sorted, you should probably use something other than a list. It sounds like a map or set might be more appropriate. I''d highly suggest reading up on the net STL tutorials before continuing--STL can be tricky, but it''s very powerful.

This topic is closed to new replies.

Advertisement