0

我试图将迭代器从模板函数返回到向量(还不是模板类成员——我还在写那个)。编译器不断给我错误(复制如下以方便谷歌搜索)。我基本上知道问题出在哪里,但确切的语法是难以捉摸的。

我阅读了互联网,搜索了 SO,包括我必须在哪里以及为什么要放置“模板”和“类型名”关键字?,但没有找到有效的答案。我想我应该在这里提出问题并自己回答。

(略)原代码如下:

#include <vector>
#include <algorithm>  // std::lower_bound

template<typename T> std::vector<T>::iterator
              insertIntoVector(std::vector<T>& vec, const T& val)
{  itr = [some std::vector<T> iterator];
   return itr;  // return iterator to val in vec.
} // End of insertIntoVector();

编译器错误:

error C2145: syntax error: missing ';' before identifier 'insertIntoVector'
error C2065: 'T' : undeclared identifier
error C2923: 'std::vector' : 'T' is not a valid template type argument for parameter '_Ty'

变得明智,我尝试了这个:

template<typename T> typename std::vector<T>::iterator
              insertIntoVector(std::vector<T>& vec, const T& val)

更多编译器错误:

error C1075: end of file found before the left brace '{'

如果这个问题被解锁,我会在下面发布我的答案。否则,请参阅我在何处以及为什么必须放置“模板”和“类型名称”关键字的答案?.

4

1 回答 1

1

奇怪的是,我必须在返回类型周围添加括号才能编译它。那是,

 template<typename T> (typename std::vector<T>::iterator)    // Tested--works as expected.
             insertIntoVector(std::vector<T>& vec, const T& val)

一直工作,但是

 template<typename T>  typename std::vector<T>::iterator     // Compile errors
             insertIntoVector(std::vector<T>& vec, const T& val)

在 MSVC 2013 上给了我问题,但在 MSVC 2012 上编译。我不知道为什么。任何人?

下面的代码在 MSVC 2013 上编译并正确运行。

// The following is based on Matt Austern's article,
// "Why you shouldn't use set (and what you should use instead)"
// (http://lafstern.org/matt/col1.pdf).
// I modified it slightly, mostly just reformatting and adding comments,
// but I also changed it to return an iterator to the inserted element.
// Also changed sorted_vector to sortedVector (cammelCase)

#include <vector>
#include <algorithm>  // std::lower_bound


 template<typename T> (typename std::vector<T>::iterator)  // Tested--works as expected.
             insertIntoVector(std::vector<T>& vec, const T& val)
{  // Insert t into vector vec such that v remains in sorted order
   // and all elements of vec are unique (like a set).
   // This only makes sense if the vector elements are
   // maintained in sorted order.
   // A sorted vector might perform better than a set if
   // there are many more access operations than insertions
   // (smaller storage, fast access via [], ... at the cost
   // of much slower insertions).
   // Note: Type T must have a defined < operator.
   /// Todo: overload this function to allow passing a Compare()
   /// function pointer.

   // std::lower_bound() gives log2(N) + O(1) performance.
   typename std::vector<T>::iterator itr
             = lower_bound(vec.begin(), vec.end(), val);
   if ( (vec.end() == itr) || (val < *itr) )
   {  itr = vec.insert(itr, val);
   }
   return itr;  // return iterator to val in vec.
} // End of insertIntoVector();
于 2014-10-19T06:39:21.487 回答