gpt4 book ai didi

c++ - 如何通过引用将存储在列表中的结构成员传递给函数?

转载 作者:行者123 更新时间:2023-11-27 23:21:03 29 4
gpt4 key购买 nike

我有一个用结构填充 STL 链表的程序,我正在尝试从列表上的一个节点(我当前通过迭代器访问的节点)传递结构成员。我要完成的其中一件事是计算运行平均值的函数。我不想将计数和总数存储在结构中,然后在输出时计算平均值,而是将计数和平均值存储在结构中,从而在重新计算平均值后丢弃我的数量值。我的结构如下所示:

struct mystruct 
{
string item;
long avg;
short count;
} data;

这些结构存储在一个列表中,带有一个迭代器 it,它允许我在列表中移动。这是否是调用我的平均函数的正确方法,前提是我已经遍历了列表并且 it 等于我想要用来计算平均值的数据的节点?

// 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++;
}

这看起来正确吗?我正在尝试使用 STL 列表来实现它,但它似乎比只实现我自己的链表类更令人困惑。我想我只是对结构和迭代器的实际工作方式以及实际传递的内容/方式感到困惑。编码对我来说还是相当新的,所以这在很大程度上是一个学习过程......

谢谢!

最佳答案

假设 X 是列表中对象的类型,那么您可以这样做:

void DoSomething(X& object) {
object.count, object.avg;
}
void DoSomethingElse(int& count, int& average) {
...
}

int main() {
...
for(std::list<X>::iterator it=myList.begin(), end=myList.end(); it != end; ++it) {
DoSomething(*it); // how I'd do it
DoSomethingElse(it->count, it->avg); // Equally valid way that you did it
}
...
}

请记住:

  • container.begin() 是指向第一个元素的指针
  • container.end() 是指向最后一个元素的指针
  • *it 是指向元素的引用
  • it != container.end() 是您判断是否到达终点的方式
  • it->x 是指向元素的成员
  • 从容器中移除对象可能会使未完成的迭代器失效,具体取决于多种因素。
  • ++it 可能比 it++
  • 更高效

编辑:OP 要求:

I'm not iterating through the list and running calc_average on every single node, but rather iterating through the list looking for a specific item value. Once I find the one of interest, I'm calling the calc_average function on that specific node. I just don't need to have the for loop. Instead I would arrive at my desired iterator, and pass that via *it to void DoSomething ?

我想你现在明白它是如何工作的了。您将有一些代码来搜索指示的节点,然后有一些其他代码来调用您的函数:

   std::list<X>::iterator it, end;
for(it=myList.begin(), end=myList.end(); it != end; ++it) {
// Look for the special node:
if( it->magicValue == 42 ) {
// We found it!
break;
}
}

// Either it is equal to end (boo!) or it points to the special node (yay!)
if( it == end ) {
std::cerr << "Could not find special node!\n";
}
if( it != end ) {
DoSomething(*it);
}

关于c++ - 如何通过引用将存储在列表中的结构成员传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019774/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com