正确的方法通过巨大的const对象的向量

Correct way to pass vector of huge const objects

本文关键字:const 对象 巨大 向量 方法      更新时间:2023-10-16

我想传递以功能函数函数内部无法更改的巨大对象的向量。显然,我想避免复制这些对象。另外,我不想使用指针。我尝试使用Reference_wrapper,但会产生错误。

该函数通常也将使用此类对象的撑杆封闭列表来调用(当它们在fly时构造时(。

MWE带指针:

#include <iostream>
#include <vector>
using namespace std;
struct HugeObject {
    int value = 42;
    // large chuck of data inside
};
HugeObject operator*(const HugeObject &a, const HugeObject &b) {
    return {a.value * b.value};
}
HugeObject op2(const HugeObject &a, const HugeObject &b) {
    HugeObject ret_obj;
    // calculate return object based on a and b
    return ret_obj;
}
HugeObject f(const HugeObject &a, const HugeObject &b, const HugeObject &c) {
    HugeObject ret_obj;
    // calculate return object based on a, b, and c
    return ret_obj;
}
double do_some_calculation(const vector<HugeObject *> &objects) {
    double ret_val = 0.0;
    // do some calculation on objects
    return ret_val;
}
int main() {
    vector<HugeObject> a{{33}, {666}, {32}, {22}, {735}, {0}, {-123}};
    vector<HugeObject *> subset_1{&a[0], &a[3], &a[4]};
    vector<HugeObject *> subset_2{&a[2], &a[4]};
    cout << do_some_calculation(subset_1) << endl;
    cout << do_some_calculation(subset_2) << endl;
    cout << do_some_calculation({&a[0], &a[1]}) << endl;
    // I would like also to call do_some_calculation() on list constructed in place, something like this:
    cout << do_some_calculation({a[0], a[1] * a[2], op2(a[0], a[4]), f(a[0], a[1], a[2])}) << endl; // obviously, error
    HugeObject b = a[1] * a[2],
            c = op2(a[0], a[4]),
            d = f(a[0], a[1], a[2]);
    cout << do_some_calculation({&a[0], &b, &c, &d}) << endl; // compiles but looks ugly
    return 0;
}

在最后一个呼叫中,仅一次使用操作(或功能(构建的对象,因此我不在乎它们 - 但我希望a[0]仍然保持不变。当然,我可以将a[1] * a[2]op2(a[0], a[4])f(a[0], a[1], a[2])中的每个命名为变量(源代码的结尾(,然后在呼叫中使用对它们的引用,但它使代码看起来更丑陋。

您已经将向量传递为const引用,因此还不清楚为什么还要包装元素。

对于第二个通话,我宁愿将算法重构为:

template <typename IT>
double do_some_calculation_with_multiplied_elements(IT begin, IT end, IT mult_begin, IT mult_end) {
    double ret_val = 0.0;
    // multiply mult_begin up to mult_end and use the result
    return ret_val;
}

这样:

cout << do_some_calculation({a[0], a[1] * a[2]}) << endl;

将成为:

cout << do_some_calculation_with_multiplied_elements(a.begin(),a.begin()+1, a.begin()+2, a.end()) << endl;