【问题标题】:Run an iteration in C++ to store variable when certain condition is met当满足特定条件时,在 C++ 中运行迭代以存储变量
【发布时间】:2016-06-14 16:18:57
【问题描述】:

我已经编写了一个程序来存储频道值 > 0.1 时的频道号。 我已经定义了迭代。 在循环中,迭代在不同的通道上运行(例如:通道 1、通道 2 等等)。 然后我调用了另一个程序来计算值。它将一一计算每个通道的值。 我的任务是获取 Channel Value > 0.1 的通道。我不知道如何存储这些频道号码。如果你们能帮助我,将不胜感激。谢谢。

list < int >  GetChannels(Node* node) 
{

 list<int> Channels = GetList(node); //calling a list which I already defined. 
 list<int>::iterator itr;
for (itr=Channels.begin(); itr!=Channels.end(); ++itr) {
    double ChannelValue = CalculateValue(node, *itr); //calling another func
    if (ChannelValue > 0.1) {

`

【问题讨论】:

  • 我已经编辑了代码,使其可读。谢谢
  • 它仍然不可读!您缺少 if 声明的正文!
  • @sean,我认为问题在于里面有什么。我的问题是这是什么语言? C++ 或 C#。
  • 是的,因为这是我的问题。如果 ChannelValue > 0.1,我不知道如何存储频道
  • 是的,正是本。这是我的问题。

标签: c++ visual-studio-2010 visual-c++


【解决方案1】:

您可以创建另一个列表以返回值吗?

list < int >  GetChannels(Node* node) {

   list<int> Channels = GetList(node); //calling a list which I already defined. 
   list<int> output; // Output list.
   list<int>::iterator itr;
   for (itr=Channels.begin(); itr!=Channels.end(); ++itr) {
       double ChannelValue = CalculateValue(node, *itr); //calling another func
       if (ChannelCapacityValue > 0.1) {
            output.insert(*itr);
       }
   }
   return output;
}

【讨论】:

  • 非常感谢本 :)
【解决方案2】:

如果我得到确切的要求,您只需要通过在特定谓词(CalculateValue(node, *itr) &gt; 0.1f)上过滤现有集合来构建一个列表。

这似乎是std::copy_if 的任务,有点:

list<int> channels;
list<int> filteredChannels;

...

copy_if(channels.begin(), channels.end(), back_inserter(filteredChannels), 
    [node] (const int& value) { return CalculateValue(node,value) > 0.1f; }
);

既然 STL 已经为您提供了合适的设施,为什么还要重新发明轮子?

如果您无法访问 C++11 lambda,请提供自定义函数,例如。 bool isValidChannel(const int&amp; channel) { ... } 但这需要绑定 node 参数。

【讨论】:

  • 非常感谢杰克。你的回答真的很有帮助:)
猜你喜欢
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 2020-10-06
相关资源
最近更新 更多