Insert method in any stl collection

I want to write a method that could take a set or list and insert an element into it.

So, I have a

bool getValues(const std::string& query, std::vector<T> *pVals) const {
}

but instead of std :: vector, I want to have something more general so that I can pass either a vector or a set. Some kind of iterator?

+4
source share
2 answers

The way it works STLis to accept pattern iterators to start and end the range that you want to process. When elements are to be inserted as a whole, a special insert iterator can be used.

// accept inserters instead of a container and use a template
// to make it generic (different inserter types)
template<typename InsertIter>
bool getValues(const std::string& query, InsertIter inserter) {

    // make sure what you do here works for both vectors and sets

    for(int i = 0; i < 6; ++i)
        inserter = i; // generic insertion

    // ... etc
}

Use it like this:

std::vector<int> v;

// vectors use a std::back_inserter (calls push_back())
getValues("", std::back_inserter(v));

std::set<int> s;

// sets use an std::inserter (calls insert())
getValues("", std::inserter(s, s.end()));
+4
source

, , , . http://en.cppreference.com/w/cpp/container/set " ", , . Container, - , , .

, -. ​​ . .

, , . , Insertable (T ), , Insertable , . , insert(), . Insertable - .

0

Source: https://habr.com/ru/post/1667408/


All Articles