C ++模板函数与向量

时间:2014-04-26 01:55:53

标签: c++ generics template-function

我有以下代码行和编译错误。这应该是我对模板函数或c ++泛型或其他东西的错误理解。提前感谢您指出。

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
T* find(vector<T> &vec, T value)
{
  vector<T>::iterator first = vec.begin();
  vector<T>::iterator last = vec.end();
  for(; first != last; first ++)
      if(*first == value)
          return first;
  return 0;
}

控制台中的编译错误

debug.cpp: In function ‘T* find(std::vector<T, std::allocator<_CharT> >&, T)’:
debug.cpp:9: error: expected `;' before ‘first’
debug.cpp:10: error: expected `;' before ‘last’
debug.cpp:11: error: ‘first’ was not declared in this scope
debug.cpp:11: error: ‘last’ was not declared in this scope

3 个答案:

答案 0 :(得分:3)

你需要使用typename vector<T>::iterator first和最后类似的。否则编译器会发现声明不明确,因为它没有意识到vector<T>::iterator是一种类型。它可以是成员函数或其他东西。从技术上讲,它们被称为dependent typenames(因为它们依赖于模板类型T。每次有依赖类型时都使用typename来避免这样的头痛。请参阅例如http://pages.cs.wisc.edu/~driscoll/typename.html更多细节。

答案 1 :(得分:2)

除了由于类型名称依赖性而不需要包含typename关键字之外,您还要重新发明其他人的算法,即std::find。关于什么是typename依赖关系以及为什么需要解决它,this answer在解释它方面做得比我做得好得多。

并且您还将容器迭代器类型视为项类型指针,这种做法将使用向量,但如果您想要使用不同的容器,其中迭代器是包装器而不是直接指针,则会严重限制您的代码。 / p>

关于缩短代码以及解决typename问题:

template <typename T>
T* find(std::vector<T> &vec, const T& value)
{
    typename std::vector<T>::iterator it = std::find(vec.begin(), vec.end(), value);
    return (it != vec.end()) ? &(*it) : nullptr;
}

注意:使用C ++ 11,auto

可以避免这种情况
template <typename T>
T* find(std::vector<T> &vec, const T& value)
{
    auto it = std::find(vec.begin(), vec.end(), value);
    return (it != vec.end()) ? &(*it) : nullptr;
}

答案 2 :(得分:0)

以下是工作版本,但仍不清楚为什么原帖中的代码不正确。

#include <iostream>
#include <vector>

using namespace std;

template <typename IteratorType, typename T>
IteratorType find(IteratorType first, IteratorType last, T &value)
{
  for(; first != last; first ++)
      if (*first == value)
          return first;
  return last;
}
相关问题