Is it correct to put dynamic_cast in loop??
//Searches for the reservation with the given reservation number, and //deletes it. Uses the confirmReservation function if the reservation to be //deleted was an OK one
void cancelReservation(string resNum)
{
for (int i=0;i<seats+waitingListMax;i++)
{
for (int seat=i;seat<seats;seat++)
{
Ok* okptr=dynamic_cast <Ok*>(reservations[seat]);
}
for ( int wait=seats;wait<seats+waitingListMax;wait++)
{
Waiting* waitingptr=dynamic_cast <Waiting*>(reservations[wait]);
}
if ((reservations[i]!=0) && (reservations[i]->getReservationNumber()==resNum))
if (okptr)
{
//doing somting
}
if (waitptr)
{
//doing somthing else
}
}
Nothing wrong in putting it under a for loop.
Your class should be polymorphic though but that is a basic condition for using dynamic_cast.
In your example, You are not really acheiving much because you overwrite the pointer on every iteration. But that is probably your simplification of original code.
There's nothing wrong with using dynamic_cast within a loop.
But your code does have a different problem: the pointers okptr and waitingptr are only scoped to the innermost {}, so can't be used later.
Related
I wonder how to get access to element of list that contains pointers to objects. I want to achieve that without dereferencing. Propably it will be much easier if i just show what i want. So I have list:
list<ObjectClass*> nameOfObject;
and I have method:
bool collision(list<ObjectClass*>::iterator&);
And inside definition of that method I have:
{
if((*nameOfObject)->getSprite()) return true;
else return false;
}
What i want is to getSprite without needing to dereference nameOfObject inside method, so something like that:
{
if((nameOfObject)->getSprite()) return true;
else return false;
}
Everything that i tried is not working. I thought that it would be easy but i really don;t get it. Any ideas? I will add that list has to contain pointer to the objects, because of polimorphysm.
list<ObjectClass*>::iterator&
It's unclear why iterator is passed by reference.
*nameOfObject
This is ill-formed because std::list doesn't have indirection operator. I suspect that you may have shadowed that variable, and forgotten to include the shadowing variable in the example.
What i want is to getSprite without needing to dereference nameOfObject inside method,
Then you need to have an instance of a class with getSprite member function in the class rather than a pointer/iterator to such. If you do have a pointer/iterator, then there is no way to access the pointed object through the pointer without indirection.
so something like that:
(nameOfObject)->getSprite()
That does dereference nameOfObject. -> is the indirecting member access operator. It is also ill-formed with a list.
Any ideas?
Avoid wanting impossible things ¯\_(ツ)_/¯
You usually don't pass single iterator around.
If you want single object, pass single object (whether by reference or pointer)
I write an example code, hope it helps.
fIter is probably what most close to what you currently have
f is demonstrate you can iterate collection without directly use iterator
//
// https://stackoverflow.com/q/63156916/5980430
//
#include <list>
#include <iostream>
class ObjectClass{
public:
int spriteID;
int getSprite(){return spriteID;}
};
//your *collision* function
void collision(ObjectClass& obj){
std::cout << obj.getSprite() << '\n';
}
void f(std::list<ObjectClass>& objs){
for (auto& obj : objs){
collision(obj);
}
}
//even with iterator, you dereference it before pass in other functions
void fIter(std::list<ObjectClass>& objs){
for (auto it = objs.begin(); it != objs.end(); ++it){
collision(*it);
}
}
int main(){
std::list<ObjectClass> objects;
objects.push_back({1});
objects.push_back({2});
objects.push_back({3});
f(objects);
fIter(objects);
}
https://wandbox.org/permlink/SgI5ibjaIXd644DH
I have the following piece of code -
string classNeeded;//set to either "Max" or "Min"
if(strcmp(classNeeded, "Max") == 0)
{
Maximum maxi;//object of class Maximum declared
}
else
{
Minimum mini;//object of class Minimum declared
}
while(/*Conditions*/)
{
//Some processing
//Use maxi or mini depending on which one is declared
}
I need to check if maxi is declared and use it or if it is not declared, use mini. How do I check if an object is declared or not in C++ Visual Studio 2005?
P.S.: I'm new to coding in VS2005 C++
You can't check if an object in the local scope is created at runtime. You can't even make a decision on that. It either is or it isn't, and is determinable by simply reading the code. What you're doing now is creating 2 objects in two seperate scopes. They don't exist outside the scope in which they are created, so you can't use them later, down in your while loop. You could use pointers with dynamic allocation, but a better idea is to factor out your while loop into a pair of overloaded functions.
void DoIt(Maximum maxi)
{
while(/*Conditions*/)
{
//Some processing
//Use maxi
}
}
void DoIt(Minimum mini)
{
while(/*Conditions*/)
{
//Some processing
//Use mini
}
}
Then:
if(strcmp(classNeeded, "Max") == 0) // no comment
{
DoIt(Maximum());
}
else
{
DoIt(Minimum());
}
If the code in the while loop looks identical for both functions, just with a different object, you could use a template instead.
template<typename T>
void DoIt(T& object)
{
...
}
I was making a "concatenating iterator", i.e. an iterator that would iterate over the ints in an int**.
Its constructor needs:
An array of T**, representing the beginning of each sub-array.
An array of T**, representing the end of each sub-array.
Lo and behold, I ran across a situation where goto seemed to be appropriate.
But something within me screamed "NO!!" so I thought I'd come here and ask:
Should I try avoid goto situations like this? (Does it improve the readability if I do?)
#include <algorithm>
template<class T>
class lazy_concat_iterator
{
// This code was meant to work for any valid input iterator
// but for easier reading, I'll assume the type is: T**
mutable T** m_endIt; // points to an array of end-pointers
mutable T** m_it; // points to an array of begin-pointers
mutable bool m_started; // have we started iterating?
mutable T* m_sub; // points somewhere in the current sub-array
mutable T* m_subEnd; // points to the end of the current sub-array
public:
lazy_concat_iterator(T** begins, T** ends)
: m_it(begins), m_endIt(ends), m_started(false) { }
void ensure_started() const
{
if (!m_started)
{
m_started = true;
INIT:
m_sub = *m_it;
m_subEnd = *m_endIt;
if (m_sub == m_subEnd) // End of this subarray?
{
++m_it;
++m_endIt;
goto INIT; // try next one <<< should I use goto here?
}
}
}
};
How you could use it:
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char* argv[])
{
vector<char*> beginnings(argv, argv + argc);
vector<char*> endings;
for (int i = 0; i < argc; i++)
endings.push_back(argv[i] + strlen(argv[i]));
lazy_concat_iterator<char> it(&beginnings[0], &endings[0]);
it.ensure_started(); // 'it' would call this internally, when dereferenced
}
Yes, you can and should avoid goto, for example this code should do the equivalent for what yours does from the INIT label (this also works for input iterators which was a "hidden requirement" as it doesn't dereference m_it and m_endIt an extra time once the condition is met unlike my previous transformation):
while ((m_subIt = *m_it) == (m_subEnd = *m_endIt))
{
++m_it;
++m_endIt;
}
Previous answer attempt:
Even a forever loop would be clearer and neater than a goto. It highlights the obvious "never terminate" possibility even better.
for (;;)
{
m_sub = *m_it;
m_subEnd = *m_endIt;
if (m_sub != m_subEnd)
break;
++m_it;
++m_endIt;
}
Although I don't see why you need to assign to m_subEnd and m_subIt inside the loop. If you don't you can rewrite this as a while loop:
while (*m_it == *m_endIt)
{
++m_it;
++m_endIt;
}
m_subIt = *m_it;
m_subEnd = *m_endIt;
while (*m_it == *m_endIt)
{
++m_it;
++m_endIt;
}
m_sub = *m_it;
m_subEnd = *m_endIt;
Maybe no for loop, but maybe a do-while?
do {
m_sub = *m_it;
m_subEnd = *m_endIt;
if (m_sub == m_subEnd) // End of this subarray?
{
++m_it;
++m_endIt;
}
} while (m_sub == m_subEnd);
If you don't want to do the comparison twice and still avoid using one of goto's stealth cousins break or continue:
bool anotherround = FALSE;
do {
m_sub = *m_it;
m_subEnd = *m_endIt;
anotherround = m_sub == m_subEnd
if (anotherround) // End of this subarray?
{
++m_it;
++m_endIt;
}
} while (anotherround);
With your knowledge of the context I'm sure you can invent better varnames, but that's the idea.
Regarding a goto's influence on readability: for me the main issue with a goto herey is that it forces the programmer to memorize a potential nonlogical movement in the code - all of a sudden the code can jump almost anywhere. If you use control structures, even if you have to introduce some extra lines or whatnot, the program continues to behave as expected and follow the flow. And in the long run, that's what readability is all about.
Don't use a goto. The only case when a goto can be forgiven is if you have a complicated function (which you shouldn't have anyways) and you want to have a centralized exit/cleanup part at the end of the function, where you could goto upon different errors at different parts of the function, or fall through upon success.
All in all, you should use a do-while loop here.
People created middle and high level compilers with using assembler(and high-level assembler). Assembler has many jmp jnz jg jl commands act like goto. They made it this far. Cant you do the same? If you can't then you answered your own question.
I cant say the same thing for interpreters.
This is my first time using this site so sorry for any bad formatting or weird formulations, I'll try my best to conform to the rules on this site but I might do some misstakes in the beginning.
I'm right now working on an implementation of some different bin packing algorithms in C++ using the STL containers. In the current code I still have some logical faults that needs to be fixed but this question is more about the structure of the program. I would wan't some second opinion on how you should structure the program to minimize the number of logical faults and make it as easy to read as possible. In it's current state I just feel that this isn't the best way to do it but I don't really see any other way to write my code right now.
The problem is a dynamic online bin packing problem. It is dynamic in the sense that items have an arbitrary time before they will leave the bin they've been assigned to.
In short my questions are:
How would the structure of a Bin packing algorithm look in C++?
Is STL containers a good tool to make the implementation be able to handle inputs of arbitrary lenght?
How should I handle the containers in a good, easy to read and implement way?
Some thoughts about my own code:
Using classes to make a good distinction between handling the list of the different bins and the list of items in those bins.
Getting the implementation as effective as possible.
Being easy to run with a lot of different data lengths and files for benchmarking.
#include <iostream>
#include <fstream>
#include <list>
#include <queue>
#include <string>
#include <vector>
using namespace std;
struct type_item {
int size;
int life;
bool operator < (const type_item& input)
{
return size < input.size;
}
};
class Class_bin {
double load;
list<type_item> contents;
list<type_item>::iterator i;
public:
Class_bin ();
bool operator < (Class_bin);
bool full (type_item);
void push_bin (type_item);
double check_load ();
void check_dead ();
void print_bin ();
};
Class_bin::Class_bin () {
load=0.0;
}
bool Class_bin::operator < (Class_bin input){
return load < input.load;
}
bool Class_bin::full (type_item input) {
if (load+(1.0/(double) input.size)>1) {
return false;
}
else {
return true;
}
}
void Class_bin::push_bin (type_item input) {
int sum=0;
contents.push_back(input);
for (i=contents.begin(); i!=contents.end(); ++i) {
sum+=i->size;
}
load+=1.0/(double) sum;
}
double Class_bin::check_load () {
return load;
}
void Class_bin::check_dead () {
for (i=contents.begin(); i!=contents.end(); ++i) {
i->life--;
if (i->life==0) {
contents.erase(i);
}
}
}
void Class_bin::print_bin () {
for (i=contents.begin (); i!=contents.end (); ++i) {
cout << i->size << " ";
}
}
class Class_list_of_bins {
list<Class_bin> list_of_bins;
list<Class_bin>::iterator i;
public:
void push_list (type_item);
void sort_list ();
void check_dead ();
void print_list ();
private:
Class_bin new_bin (type_item);
bool comparator (type_item, type_item);
};
Class_bin Class_list_of_bins::new_bin (type_item input) {
Class_bin temp;
temp.push_bin (input);
return temp;
}
void Class_list_of_bins::push_list (type_item input) {
if (list_of_bins.empty ()) {
list_of_bins.push_front (new_bin(input));
return;
}
for (i=list_of_bins.begin (); i!=list_of_bins.end (); ++i) {
if (!i->full (input)) {
i->push_bin (input);
return;
}
}
list_of_bins.push_front (new_bin(input));
}
void Class_list_of_bins::sort_list () {
list_of_bins.sort();
}
void Class_list_of_bins::check_dead () {
for (i=list_of_bins.begin (); i !=list_of_bins.end (); ++i) {
i->check_dead ();
}
}
void Class_list_of_bins::print_list () {
for (i=list_of_bins.begin (); i!=list_of_bins.end (); ++i) {
i->print_bin ();
cout << "\n";
}
}
int main () {
int i, number_of_items;
type_item buffer;
Class_list_of_bins bins;
queue<type_item> input;
string filename;
fstream file;
cout << "Input file name: ";
cin >> filename;
cout << endl;
file.open (filename.c_str(), ios::in);
file >> number_of_items;
for (i=0; i<number_of_items; ++i) {
file >> buffer.size;
file >> buffer.life;
input.push (buffer);
}
file.close ();
while (!input.empty ()) {
buffer=input.front ();
input.pop ();
bins.push_list (buffer);
}
bins.print_list ();
return 0;
}
Note that this is just a snapshot of my code and is not yet running properly
Don't wan't to clutter this with unrelated chatter just want to thank the people who contributed, I will review my code and hopefully be able to structure my programming a bit better
How would the structure of a Bin packing algorithm look in C++?
Well, ideally you would have several bin-packing algorithms, separated into different functions, which differ only by the logic of the algorithm. That algorithm should be largely independent from the representation of your data, so you can change your algorithm with only a single function call.
You can look at what the STL Algorithms have in common. Mainly, they operate on iterators instead of containers, but as I detail below, I wouldn't suggest this for you initially. You should get a feel for what algorithms are available and leverage them in your implementation.
Is STL containers a good tool to make the implementation be able to handle inputs of arbitrary length?
It usually works like this: create a container, fill the container, apply an algorithm to the container.
Judging from the description of your requirements, that is how you'll use this, so I think it'll be fine. There's one important difference between your bin packing algorithm and most STL algorithms.
The STL algorithms are either non-modifying or are inserting elements to a destination. bin-packing, on the other hand, is "here's a list of bins, use them or add a new bin". It's not impossible to do this with iterators, but probably not worth the effort. I'd start by operating on the container, get a working program, back it up, then see if you can make it work for only iterators.
How should I handle the containers in a good, easy to read and implement way?
I'd take this approach, characterize your inputs and outputs:
Input: Collection of items, arbitrary length, arbitrary order.
Output: Collection of bins determined by algorithm. Each bin contains a collection of items.
Then I'd worry about "what does my algorithm need to do?"
Constantly check bins for "does this item fit?"
Your Class_bin is a good encapsulation of what is needed.
Avoid cluttering your code with unrelated stuff like "print()" - use non-member help functions.
type_item
struct type_item {
int size;
int life;
bool operator < (const type_item& input)
{
return size < input.size;
}
};
It's unclear what life (or death) is used for. I can't imagine that concept being relevant to implementing a bin-packing algorithm. Maybe it should be left out?
This is personal preference, but I don't like giving operator< to my objects. Objects are usually non-trivial and have many meanings of less-than. For example, one algorithm might want all the alive items sorted before the dead items. I typically wrap that in another struct for clarity:
struct type_item {
int size;
int life;
struct SizeIsLess {
// Note this becomes a function object, which makes it easy to use with
// STL algorithms.
bool operator() (const type_item& lhs, const type_item& rhs)
{
return lhs.size < rhs.size;
}
}
};
vector<type_item> items;
std::sort(items.begin, items.end(), type_item::SizeIsLess);
Class_bin
class Class_bin {
double load;
list<type_item> contents;
list<type_item>::iterator i;
public:
Class_bin ();
bool operator < (Class_bin);
bool full (type_item);
void push_bin (type_item);
double check_load ();
void check_dead ();
void print_bin ();
};
I would skip the Class_ prefix on all your types - it's just a bit excessive, and it should be clear from the code. (This is a variant of hungarian notation. Programmers tend to be hostile towards it.)
You should not have a class member i (the iterator). It's not part of class state. If you need it in all the members, that's ok, just redeclare it there. If it's too long to type, use a typedef.
It's difficult to quantify "bin1 is less than bin2", so I'd suggest removing the operator<.
bool full(type_item) is a little misleading. I'd probably use bool can_hold(type_item). To me, bool full() would return true if there is zero space remaining.
check_load() would seem more clearly named load().
Again, it's unclear what check_dead() is supposed to accomplish.
I think you can remove print_bin and write that as a non-member function, to keep your objects cleaner.
Some people on StackOverflow would shoot me, but I'd consider just making this a struct, and leaving load and item list public. It doesn't seem like you care much about encapsulation here (you're only need to create this object so you don't need do recalculate load each time).
Class_list_of_bins
class Class_list_of_bins {
list<Class_bin> list_of_bins;
list<Class_bin>::iterator i;
public:
void push_list (type_item);
void sort_list ();
void check_dead ();
void print_list ();
private:
Class_bin new_bin (type_item);
bool comparator (type_item, type_item);
};
I think you can do without this class entirely.
Conceptually, it represents a container, so just use an STL container. You can implement the methods as non-member functions. Note that sort_list can be replaced with std::sort.
comparator is too generic a name, it gives no indication of what it compares or why, so consider being more clear.
Overall Comments
Overall, I think the classes you've picked adequately model the space you're trying to represent, so you'll be fine.
I might structure my project like this:
struct bin {
double load; // sum of item sizes.
std::list<type_item> items;
bin() : load(0) { }
};
// Returns true if the bin can fit the item passed to the constructor.
struct bin_can_fit {
bin_can_fit(type_item &item) : item_(item) { }
bool operator()(const bin &b) {
return item_.size < b.free_space;
}
private:
type_item item_;
};
// ItemIter is an iterator over the items.
// BinOutputIter is an output iterator we can use to put bins.
template <ItemIter, BinOutputIter>
void bin_pack_first_fit(ItemIter curr, ItemIter end, BinOutputIter output_bins) {
std::vector<bin> bins; // Create a local bin container, to simplify life.
for (; curr != end; ++curr) {
// Use a helper predicate to check whether the bin can fit this item.
// This is untested, but just for an idea.
std::vector<bin>::iterator bin_it =
std::find_if(bins.begin(), bins.end(), bin_can_fit(*curr));
if (bin_it == bins.end()) {
// Did not find a bin with enough space, add a new bin.
bins.push_back(bin);
// push_back invalidates iterators, so reassign bin_it to the last item.
bin_it = std::advance(bins.begin(), bins.size() - 1);
}
// bin_it now points to the bin to put the item in.
bin_it->items.push_back(*curr);
bin_it->load += curr.size();
}
std::copy(bins.begin(), bins.end(), output_bins); // Apply our bins to the destination.
}
void main(int argc, char** argv) {
std::vector<type_item> items;
// ... fill items
std::vector<bin> bins;
bin_pack_first_fit(items.begin(), items.end(), std::back_inserter(bins));
}
Some thoughts:
Your names are kinda messed up in places.
You have a lot of parameters named input, thats just meaningless
I'd expect full() to check whether it is full, not whether it can fit something else
I don't think push_bin pushes a bin
check_dead modifies the object (I'd expect something named check_*, to just tell me something about the object)
Don't put things like Class and type in the names of classes and types.
class_list_of_bins seems to describe what's inside rather then what the object is.
push_list doesn't push a list
Don't append stuff like _list to every method in a list class, if its a list object, we already know its a list method
I'm confused given the parameters of life and load as to what you are doing. The bin packing problem I'm familiar with just has sizes. I'm guessing that overtime some of the objects are taken out of bins and thus go away?
Some further thoughts on your classes
Class_list_of_bins is exposing too much of itself to the outside world. Why would the outside world want to check_dead or sort_list? That's nobodies business but the object itself. The public method you should have on that class really should be something like
* Add an item to the collection of bins
* Print solution
* Step one timestep into the future
list<Class_bin>::iterator i;
Bad, bad, bad! Don't put member variables on your unless they are actually member states. You should define that iterator where it is used. If you want to save some typing add this: typedef list::iterator bin_iterator and then you use bin_iterator as the type instead.
EXPANDED ANSWER
Here is my psuedocode:
class Item
{
Item(Istream & input)
{
read input description of item
}
double size_needed() { return actual size required (out of 1) for this item)
bool alive() { return true if object is still alive}
void do_timestep() { decrement life }
void print() { print something }
}
class Bin
{
vector of Items
double remaining_space
bool can_add(Item item) { return true if we have enough space}
void add(Item item) {add item to vector of items, update remaining space}
void do_timestep() {call do_timestep() and all Items, remove all items which indicate they are dead, updating remaining_space as you go}
void print { print all the contents }
}
class BinCollection
{
void do_timestep { call do_timestep on all of the bins }
void add(item item) { find first bin for which can_add return true, then add it, create a new bin if neccessary }
void print() { print all the bins }
}
Some quick notes:
In your code, you converted the int size to a float repeatedly, that's not a good idea. In my design that is localized to one place
You'll note that the logic relating to a single item is now contained inside the item itself. Other objects only can see whats important to them, size_required and whether the object is still alive
I've not included anything about sorting stuff because I'm not clear what that is for in a first-fit algorithm.
This interview gives some great insight into the rationale behind the STL. This may give you some inspiration on how to implement your algorithms the STL-way.
I have a method where performance is really important (I know premature optimization is the root of all evil. I know I should and I did profile my code. In this application every tenth of a second I save is a big win.) This method uses different heuristics to generate and return elements. The heuristics are used sequentially: the first heuristic is used until it can no longer return elements, then the second heuristic is used until it can no longer return elements and so on until all heuristics have been used. On each call of the method I use a switch to move to the right heuristic. This is ugly, but work well. Here is some pseudo code
class MyClass
{
private:
unsigned int m_step;
public:
MyClass() : m_step(0) {};
Elem GetElem()
{
// This switch statement will be optimized as a jump table by the compiler.
// Note that there is no break statments between the cases.
switch (m_step)
{
case 0:
if (UseHeuristic1())
{
m_step = 1; // Heuristic one is special it will never provide more than one element.
return theElem;
}
m_step = 1;
case 1:
DoSomeOneTimeInitialisationForHeuristic2();
m_step = 2;
case 2:
if (UseHeuristic2())
{
return theElem;
}
m_step = 3;
case 3:
if (UseHeuristic3())
{
return theElem;
}
m_step = 4; // But the method should not be called again
}
return someErrorCode;
};
}
As I said, this works and it's efficient since at each call, the execution jumps right where it should. If a heuristic can't provide an element, m_step is incremented (so the next time we don't try this heuristic again) and because there is no break statement, the next heuristic is tried. Also note that some steps (like step 1) never return an element, but are one time initialization for the next heuristic.
The reason initializations are not all done upfront is that they might never be needed. It is always possible (and common) for GetElem to not get called again after it returned an element, even if there are still elements it could return.
While this is an efficient implementation, I find it really ugly. The case statement is a hack; using it without break is also hackish; the method gets really long, even if each heuristic is encapsulated in its own method.
How should I refactor this code so it's more readable and elegant while keeping it as efficient as possible?
Wrap each heuristic in an iterator. Initialize it completely on the first call to hasNext(). Then collect all iterators in a list and use a super-iterator to iterate through all of them:
boolean hasNext () {
if (list.isEmpty()) return false;
if (list.get(0).hasNext()) return true;
while (!list.isEmpty()) {
list.remove (0);
if (list.get(0).hasNext()) return true;
}
return false;
}
Object next () {
return list.get (0).next ();
}
Note: In this case, a linked list might be a tiny bit faster than an ArrayList but you should still check this.
[EDIT] Changed "turn each" into "wrap each" to make my intentions more clear.
I don't think your code is so bad, but if you're doing this kind of thing a lot, and you want to hide the mechanisms so that the logic is clearer, you could look at Simon Tatham's coroutine macros. They're intended for C (using static variables) rather than C++ (using member variables), but it's trivial to change that.
The result should look something like this:
Elem GetElem()
{
crBegin;
if (UseHeuristic1())
{
crReturn(theElem);
}
DoSomeOneTimeInitialisationForHeuristic2();
while (UseHeuristic2())
{
crReturn(theElem);
}
while (UseHeuristic3())
{
crReturn(theElem);
}
crFinish;
return someErrorCode;
}
To my mind if you do not need to modify this code much, eg to add new heuristics then document it well and don't touch it.
However if new heuristics are added and removed and you think that this is an error prone process then you should consider refactoring it. The obvious choice for this would be to introduce the State design pattern. This will replace your switch statement with polymorphism which might slow things down but you would have to profile both to be sure.
It looks like there really isn't much to optimize in this code - probably most of the optimization can be done in the UseHeuristic functions. What's in them?
You can turn the control flow inside-out.
template <class Callback> // a callback that returns true when it's done
void Walk(Callback fn)
{
if (UseHeuristic1()) {
if (fn(theElem))
return;
}
DoSomeOneTimeInitialisationForHeuristic2();
while (UseHeuristic2()) {
if (fn(theElem))
return;
}
while (UseHeuristic3()) {
if (fn(theElem))
return;
}
}
This might earn you a few nanoseconds if the switch dispatch and the return statements are throwing the CPU off its stride, and the recipient is inlineable.
Of course, this kind of optimization is futile if the heuristics themselves are nontrivial. And much depends on what the caller looks like.
That's micro optimization, but there is no need to set m_elem value when you are not returning from GetElem. See code below.
Larger optimization definitely need simplifying control flow (less jumps, less returns, less tests, less function calls), because as soon as a jump is done processor cache are emptied (well some processors have branch prediction, but it's no silver bullet). You can give a try at solutions proposed by Aaron or Jason, and there is others (for instance you can implement several get_elem functions annd call them through a function pointer, but I'm quite sure it'll be slower).
If the problem allow it, it can also be efficient to compute several elements at once in heuristics and use some cache, or to make it truly parallel with some thread computing elements and this one merely a customer waiting for results... no way to say more without some details on the context.
class MyClass
{
private:
unsigned int m_step;
public:
MyClass() : m_step(0) {};
Elem GetElem()
{
// This switch statement will be optimized as a jump table by the compiler.
// Note that there is no break statments between the cases.
switch (m_step)
{
case 0:
if (UseHeuristic1())
{
m_step = 1; // Heuristic one is special it will never provide more than one element.
return theElem;
}
case 1:
DoSomeOneTimeInitialisationForHeuristic2();
m_step = 2;
case 2:
if (UseHeuristic2())
{
return theElem;
}
case 3:
m_step = 4;
case 4:
if (UseHeuristic3())
{
return theElem;
}
m_step = 5; // But the method should not be called again
}
return someErrorCode;
};
}
What you really can do here is replacing conditional with State pattern.
http://en.wikipedia.org/wiki/State_pattern
May be it would be less performant because of the virtual method call, maybe it would be better performant because of less state maintaining code, but the code would be definitely much clearer and maintainable, as always with patterns.
What could improve performance, is elimination of DoSomeOneTimeInitialisationForHeuristic2();
with separate state between. 1 and 2.
Since each heuristic is represented by a function with an identical signature, you can make a table of function pointers and walk through it.
class MyClass
{
private:
typedef bool heuristic_function();
typedef heuristic_function * heuristic_function_ptr;
static heuristic_function_ptr heuristic_table[4];
unsigned int m_step;
public:
MyClass() : m_step(0) {};
Elem GetElem()
{
while (m_step < sizeof(heuristic_table)/sizeof(heuristic_table[0]))
{
if (heuristic_table[m_step]())
{
return theElem;
}
++m_step;
}
return someErrorCode;
};
};
MyClass::heuristic_function_ptr MyClass::heuristic_table[4] = { UseHeuristic1, DoSomeOneTimeInitialisationForHeuristic2, UseHeuristic2, UseHeuristic3 };
If the element code you are processing can be converted to an integral value, then you can construct a table of function pointers and index based on the element. The table would have one entry for each 'handled' element, and one for each known but unhandled element. For unknown elements, do a quick check before indexing the function pointer table.
Calling the element-processing function is fast.
Here's working sample code:
#include <cstdlib>
#include <iostream>
using namespace std;
typedef void (*ElementHandlerFn)(void);
void ProcessElement0()
{
cout << "Element 0" << endl;
}
void ProcessElement1()
{
cout << "Element 1" << endl;
}
void ProcessElement2()
{
cout << "Element 2" << endl;
}
void ProcessElement3()
{
cout << "Element 3" << endl;
}
void ProcessElement7()
{
cout << "Element 7" << endl;
}
void ProcessUnhandledElement()
{
cout << "> Unhandled Element <" << endl;
}
int main()
{
// construct a table of function pointers, one for each possible element (even unhandled elements)
// note: i am assuming that there are 10 possible elements -- 0, 1, 2 ... 9 --
// and that 5 of them (0, 1, 2, 3, 7) are 'handled'.
static const size_t MaxElement = 9;
ElementHandlerFn handlers[] =
{
ProcessElement0,
ProcessElement1,
ProcessElement2,
ProcessElement3,
ProcessUnhandledElement,
ProcessUnhandledElement,
ProcessUnhandledElement,
ProcessElement7,
ProcessUnhandledElement,
ProcessUnhandledElement
};
// mock up some elements to simulate input, including 'invalid' elements like 12
int testElements [] = {0, 1, 2, 3, 7, 4, 9, 12, 3, 3, 2, 7, 8 };
size_t numTestElements = sizeof(testElements)/sizeof(testElements[0]);
// process each test element
for( size_t ix = 0; ix < numTestElements; ++ix )
{
// for some robustness...
if( testElements[ix] > MaxElement )
cout << "Invalid Input!" << endl;
// otherwise process normally
else
handlers[testElements[ix]]();
}
return 0;
}
If it ain't broke don't fix it.
It looks pretty efficient as is. It doesn't look hard to understand either. Adding iterators etc. is probably going to make it harder to understand.
You are probably better off doing
Performance analysis. Is time really spent in this procedure at all, or is most of it in the functions that it calls? I can't see any significant time being spent here.
More unit tests, to prevent someone from breaking it if they have to modify it.
Additional comments in the code.