Std :: vector insert without knowing the type of elements

Suppose I have a template function that accepts different types of vectors (but for various reasons, I cannot mention this in the template parameter). Here's what I'm trying to do: insert a new, default-built element in a specific location, not knowing its type:

template <typename T>
void foo(T* v) {
  v->insert(v->begin() + 5, decltype(v->at(0))());
}

This does not work, but gives you an idea of ​​what I'm trying to do. I also tried using value_typeout std::vector, but I ran into problems there too . Any ideas how to solve this problem?

+4
source share
2 answers

Uncheck all "type name":

v->emplace(v->begin() + 5);

or

v->insert(v->begin() + 5, {});

, decltype(v->at(0)) . value_type , , , , , .

+9

, v std::vector - , , T , :

template <typename T>
void foo(std::vector<T>* v) {
  v->insert(v->begin() + 5, T());
}

, v->insert() v->begin() + 5 . , v, , v->insert() v->begin(), begin() , + 5.

+1

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


All Articles