c++ - 在 C++ 中使用 vector 传递任意数量的参数

标签 c++ vector

<分区>

我正在处理使用析构函数来释放资源的 C++ 对象。将这些对象传递给具有任意数量参数的函数时。 在这种情况下有什么办法可以避免使用指针吗?

一种可能的解决方案是将指针 vector 传递给这些对象。 如果我传递对象本身,析构函数将被调用两次,一次是真正的对象,另一次是在释放 vector 时。

#include<iostream>
#include<vector>
class integer {
    private:
        int data;
    public:
        integer(int value = 0): data(value) {}
        ~integer() {}
        void increase() {
            data++;
        }
        friend std::ostream& operator<<(std::ostream& os, const integer& x);
};
std::ostream& operator<<(std::ostream& os, const integer& x) {
    os << x.data;
    return os;
}
void foo(std::vector<integer*> vec) {
    for (auto it = vec.begin(); it != vec.end(); it++) {
        (*it)->increase();
    }
}
int main() {
    integer x1(3);
    integer x2(4);
    integer x3(5);

    std::cout << x1 << " " << x2 << " " << x3 << std::endl;

    foo({&x1, &x2, &x3});

    std::cout << x1 << " " << x2 << " " << x3 << std::endl;

    return 0;
}

预期结果:

3 4 5
4 5 6

最佳答案

我不确定指针有什么问题,但是你当然可以用 reference_wrapper 来避免指针。秒。 (别忘了 #include <functional> )

void foo(const std::vector<std::reference_wrapper<integer>>& vec)
{
    for (auto it = vec.begin(); it != vec.end(); it++) {
        (*it)->increase();
    }
}

现在你可以像foo({x1, x2, x3}) 那样调用它.

live demo


你甚至可以去掉 {}如果你想:

template <typename... Args>
void foo(Args&... args)
{
    static_assert(std::conjunction_v<std::is_same<Args, integer>...>);
    (args.increase(), ...);
}

(别忘了 #include <type_traits> 。) 现在你可以这样调用它 foo(x1, x2, x3) .

关于c++ - 在 C++ 中使用 vector 传递任意数量的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56375693/

相关文章:

c - 在c中重建数组

R:具有不同条件的 For 循环用相同的数据填充 2 个向量

C++模板问题

c++ - 派生自另一个类模板类型推导的类模板

c++ - const限定转换

c++ - vector 中的自动指针(智能)

c++ - 要导出的 Base unique_ptr vector

c++ - 无法访问 vector 元素?

c++ - shared_ptr 的原始指针构造函数是错误的吗?

c++ - 在 C++ 类中使用复杂函数初始化 const 成员