I’ve got a program that populates a STL linked list with structs, and I’m trying to pass struct members from a node on the list (one that I’m currently on via an iterator). One of the things I’m trying to accomplish is a function that will calculate a running average. Rather than storing the count and total in the struct, and then computing the average upon output, I’d like to store the count and average in the struct, thus discarding my quantity value after the average has been recalculated. My struct looks like this:
struct mystruct
{
string item;
long avg;
short count;
} data;
These structs are stored in a list, with an iterator, it, that allows me to move through the list. Would this be the proper way to call my average function, provided I’ve traversed through the list and it equals the node who’s data I want to calculate the average with?
// prior to running the code below, the `count` and `avg` members for the
// struct at iterator location `it` are both 1 and 100 respectively
long qty = 50;
calc_average(it->count, it->avg, qty);
cout << "The current count is " << it->count << endl;
// Outputs 'The current count is 2'
cout << "The current average is " << it->avg << endl;
// Outputs 'The current average is 75'
void calc_average(short &count, long &avg, long quant)
{
avg = ( (avg * count) + quant ) / (count + 1);
count++;
}
Does this seem correct? I’m trying to implement this using the STL list, but it seems more confusing than just implementing my own linked list class. I think I’m just getting confused with the structure and how the iterators actually work, and what/how things are actually being passed around. Coding is still fairly new to me so much of this is a learning process…
Thanks!
Assuming that
Xis the type of the objects in the list, then you can do something like this:Just remember:
container.begin()is the a pointer to the first elementcontainer.end()is a pointer to one-past-the-last element*itis a reference to the pointed-to elementit != container.end()is how you tell if you are at the endit->xis a member of the pointed-to element++itis probably more efficient thanit++EDIT: OP asks:
I think you understand how it works now. You’d have some code to search for the indicated node, and then some other code to invoke your function: