vector <template>, c++, class, add to vector

2023-06-05C/C++开发问题
0

本文介绍了vector <template>, c++, class, add to vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试创建一个类,该类将从一组向量中绘制元素(并将这些向量作为类中的容器保存),但我觉得在管理具有许多函数(如 vectorOneAdd、vectorTwoAdd)的向量时为了向向量添加元素是没有意义的.一定有更好的方法,这就是我在这里问的原因,我听说您可以使用模板来做到这一点,但我不太确定如何.需要帮助.不想有很多无意义的代码.

I am trying to create a class thats going to draw elements from a set of vectors (and also hold these vectors as containers inside the class), but i feel that when managing the vector having lots of functions like vectorOneAdd, vectorTwoAdd used in order to add elements to the vector is pointless. There must be a better way, thats why i am asking here, I heard you can use templates to do it, but i am not quite certain how. Assistance needed. Don't want to have lots of pointless code in.

我在下面的意思的例子:

Example of what I mean below:

class Cookie
{
std::vector<Chocolate> chocolateContainer;
std::vector<Sugar> sugarContainer;

void chocolateVectorAdd(Chocolate element);    // first function adding to one vector
void sugarVectorAdd(Sugar element);   // second function adding to another vector
}

请使用示例代码,谢谢:)

Please use example code, thanks :)

推荐答案

使用像vectorOneAdd、vectorTwoAdd这样的函数来向向量添加元素是没有意义的.一定有更好的办法

having lots of functions like vectorOneAdd, vectorTwoAdd used in order to add elements to the vector is pointless. There must be a better way

有:

class Cookie {
    std::vector<Chocolate> chocolateContainer;
    std::vector<Sugar> sugarContainer;

private:
    template<typename T>
    std::vector<T>& get_vector(const T&); // not implemented but particularized

    // write one of these for each vector:
    template<>
    std::vector<Chocolate>& get_vector(const Chocolate&) { return chocolateVector; }
    template<>
    std::vector<Sugar>& get_vector(const Sugar&) { return sugarVector; }

public:
    template<typename T>
    void add(T element) {
        auto& v = get_vector(element);
        v.push_back(std::move(element));
    }
};

这篇关于vector &lt;template&gt;, c++, class, add to vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6