Archived

This topic is now archived and is closed to further replies.

eotvos

passing parameters to classes in a stl map

Recommended Posts

eotvos    127
I assume this is possible (and most likely simple), but I haven''t figured it out yet. What I''d like to do is have a for loop initializing a starting number of objects with parameters passed to their class constructors. The way I''ve been doing it so far is having a class function called init() which I run in the loop. Every time I''ve attempted setting up some sort of constructor I get a "no default class constructor" error. An unrelated question: is their a sorting algorithm in STL that will sort the objects in map (vector, multimap, whatever) based on the value of a member variable in the objects within the map?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
About your stl question, the sort method from <algorithm> can do what you want. Look at the second version of the sort algorithm specified in this web page. http://www.sgi.com/tech/stl/sort.html Here''s a quick little example.

  
#include <algorithm>
using namespace std;
struct A
{
int myvar;
}

bool testfunc(const A& left, const A& right)
{
return left.myvar < right.myvar;
}

void mysortingfunc(vector<A> &blah)
{
sort(blah.begin(), blah.end(), testfunc);
}

Share this post


Link to post
Share on other sites
Oluseyi    2103
quote:
Original post by eotvos
Every time I've attempted setting up some sort of constructor I get a "no default class constructor" error.

You need two constructors. A default one that takes no parameters (and performs base initialization), and the version that takes params.

In any case, you may want to keep pointers to your objects in the map and simply insert the return value from a new ClassName like so:

...
for(..)
{
theMap.insert(std::pair<key_type, value_type>(key, new ClassName(params...));
}


Any particular reason you posted this in Graphics Programming and Theory?

[Edit: Forgot about the board interpreting template params as HTML tags.]

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!


[edited by - Oluseyi on March 18, 2002 12:13:50 PM]

Share this post


Link to post
Share on other sites
eotvos    127
thanks for the replies.

quote:
Any particular reason you posted this in Graphics Programming and Theory?



My bad, wasn''t paying attention

Share this post


Link to post
Share on other sites