Noah Roberts wrote:
I know there must be a way to do this using stl functions and not
reinventing the sort loops and such but I need to sort several arrays
side by side using one as the "key". Interested in ideas here...
Two directions I can think of would be to create some sort of iterator
or to create an object to wrap the value and index of the key array and
then place these in a vector and sort it. Creating an iterator seems
like maybe too complex but would probably be the more efficient
way...maybe it could be generalized enough to use again sometime. It
would certainly teach me more about iterators as I have never built my
own; always use what is there already. The other would be easier,
maybe.
If you have two equal-sized arrays, one of keys and the other of
values, with the keys "linked" to the values conceptually, then
you're doing it all wrong. You're trying to re-define std::map.
Why not use a real std::map instead? It does all the sorting for
you, automatically. Each time you insert a new entry, it gets
added to the map in sorted position.
Research std::map and std::pair for more info.
Some sample code (pretested, working) to give you the idea:
#include <iostream>
#include <utility>
#include <map>
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::pair;
using std::make_pair;
class MyClass
{
public:
MyClass() : msg("") {}
MyClass(string const & Msg) : msg(Msg) {}
string msg;
};
int main()
{
typedef unsigned long int user_id;
map<user_id, MyClassfizzbin;
MyClass Bob ("Bob");
MyClass Tom ("Tom");
MyClass Sam ("Sam");
MyClass Fred ("Fred");
fizzbin.insert(make_pair(37307, Bob));
fizzbin.insert(make_pair(82219, Tom));
fizzbin.insert(make_pair(73884, Sam));
fizzbin.insert(make_pair(21984, Fred));
// At this point, all entries are automatically sorted
// in order of user id. Lookup is blazingly fast because
// it's implemented using binary-tree technology:
// Look-up and print name of user with id# 73884:
cout << fizzbin[73884].msg << endl;
}
--
Cheers,
Robbie Hatley
East Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
http://home.pacbell.net/earnur/