std :: vector插入,不知道元素的类型 [英] std::vector insert without knowing the type of the elements

查看:119
本文介绍了std :: vector插入,不知道元素的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个采用各种向量的模板化函数(但是由于各种原因,我无法在template参数中提及这一点)。这是我要执行的操作:在不知道其类型的情况下,在特定位置插入新的默认构造元素:

Suppose I have a templated function that takes various kinds of vectors (but for various reasons I can't mention this in the template parameter). Here's what I'm trying to do: insert a new, default constructed element at a specific spot, without knowing its type:

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

这行不通,但让您了解我的意思试图做。我还尝试使用 std :: vector 中的 value_type ,但是我也遇到了问题。有什么想法可以解决这个问题吗?

This doesn't work, but gives you an idea of what I'm trying to do. I also tried to use value_type from std::vector but I ran into problems there as well. Any ideas how to solve this problem?

推荐答案

回避整个命名类型业务:

Sidestep the whole "name the type" business:

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

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

由于 decltype(v-> at (0))是引用类型。如果正确使用 value_type 应该可以工作,但是却看不到自己在做什么,我不能说这是怎么回事。

Your current version doesn't work because decltype(v->at(0)) is a reference type. value_type should work if you use it correctly, but without seeing what you are doing I can't say what's wrong with it.

这篇关于std :: vector插入,不知道元素的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆