Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

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

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

There is:

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));
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...