c++ - 有效防止重复访问

标签 c++

我有一个计算乘法累加运算的语句,看起来像这样:

return A->set(A->get() + B->get() * C->get());

现在,A、B 和 C 可能不是唯一的,我想尽量减少冗余的 get()。我能想到的优化它的唯一方法是使用

  if (A == B && B == C) {
    double a = A->get();
    return A->set(a + a * a);
  } else if (A == B) {
    double a = A->get();
    return A->set(a + a * C->get());
  } else if (A == C) {
    double a = A->get();
    return A->set(a + B->get() * a);
  } else if (B == C) {
    double b = B->get();
    return A->set(A->get() + b * b);
  } else {
    return A->set(A->get() + B->get() * C->get());
  }

有没有更有效的方法?将其推广到三个以上的参数怎么样?

最佳答案

您可以将它们存储在 map 中。该解决方案可以很容易地扩展到任意多个指针,但为了具体起见,我在这里使用了三个。

std::unordered_map<MyType *, double> computed_values;
for (MyType *p: {A, B, C}) {
    if (computed_values.find(p) == computed_values.end()) {
        computed_values[p] = p->get();
    }
}
double result = computed_values[A] + computed_values[B] * computed_values[C];
A->set(result);

正如其他人所指出的,确保您进行概要分析以确保这实际上值得 std::unordered_map 查找的开销。

关于c++ - 有效防止重复访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822500/

相关文章:

c++ - 如何通过保存在容器中的成员函数指针来调用?

c++ - 安全 bool 成语 bool_type(和安全 bool 成语)如何工作?

c++ - 调试/发布中的控制台程序

c++ - 构建 Tensorflow 时未声明特征仿函数

c++ - 从一对中获取值失败,错误为 : TYPENAME does not provide a call operator

c++ - 将左值绑定(bind)到右值引用 move 构造函数和函数返回

c++ - 派生异常不继承构造函数

c++ - 将 C++ exe 与 C 库 (GNU) 链接时出现问题

c++ - condition_variable::wait_until 意外地通过 g++ (9.4.0)

c++ - Boost.Program_options : Forward parameters after '--' to another program