5

我有一个任意 STL 容器 C,其中包含任意类型 T 的元素。我想创建一个 std::vector,它具有所有元素的副本。最干净的方法是什么?

template <typename C>
void myfunction(C container){

     /*Derive the type T of elements within the container*/

     std::vector<T> mystack;

    /* Iterate over container and push_back() the elements into mystack*/
} 
4

2 回答 2

11

STL 结构类似于vector并且set应该包含value_type类型定义为的类型T

std::vector<typename C::value_type> mystack;

顺便说一句,您不需要自己迭代容器。只需使用

template <typename C>
void myfunction(const C& container){
  std::vector<typename C::value_type> mystack(container.begin(), container.end());
  ...
}
于 2010-05-18T18:45:12.307 回答
10

对于容器,Kenny 给出了正确的解决方案。但是,C++ 中的许多函数都采用迭代器对而不是容器……在这里可以应用相同的逻辑。迭代器用于iterator_traits提供有关其相关类型的信息:

template <typename It>
void myfunction(It start, It end) {
    // Get value for iterator:

    typedef typename std::iterator_traits<It>::value_type T;

    // Do something, e.g. calculate the minimum:

    T min_value = *std::min_element(start, end);
}

顺便说一句,因为是所谓的依赖typename类型,所以它是必需的,即它取决于模板参数的性质,C++ 编译器无法自行判断它引用类型名称(而不是说,静态方法或变量)在这种情况下。typedefvalue_type

于 2010-05-18T18:49:56.083 回答