模板声明不能出现在块范围内

A template declaration cannot appear at block scope

我正在学习李普曼,而且我只是在学习。我在这里尝试编写一个代码,该代码将 return 向量中的最小元素。当我在 Codeblocks 中编译我的代码时,它说:"A template declaration cannot appear at block scope"。这是代码:

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    template <class elemType>
    elemType save;
    elemType min (const std::vector<elemType> &vec) {
      std::vector<elemType>::iterator it = vec.begin(), end_it = vec.end();
      std::vector<elemType>::iterator iter = std::next(it, 1);
      for ( ; it != end_it; it++ ) {
        if ( *it < *(it + 1) ) {
          save = *it;
        }
        if (save < *it) {
          save = *it;
        }
      }
    };

    int massiv[10] = {35, 66, 98, 15, 32, 41, 24, 90, 55, 100};
    std::vector<int> vec_train(massiv,massiv+10);


    min(vec_train);
    return 0;
}

不能在函数内部定义模板,main是一个函数。您需要在 main 之前定义 min 函数模板。

您的代码中还有其他几个问题。

template <class elemType>

必须紧接在函数定义之前。放

elemType save;

它们之间的语法不正确。

另一个问题是您在向量中选择最小值的算法。为什么你有这个

if (*save < *(it + 1) ) { save = *it; }

还有这个

if (*save < *it ) { save = *it; }

同时?

这可能是您想要的:

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

template <class elemType>
const elemType& min(const std::vector<elemType>& vec) {
  typename std::vector<elemType>::const_iterator
    select = vec.begin(),
    it = std::next(select),
    end = vec.end();
  for ( ; it != end; ++it ) {
    if ( *it < *select ) select = it;
  }
  return *select;
};

int main() {
  int massiv[10] = {35, 66, 98, 15, 32, 41, 24, 90, 55, 100};
  std::vector<int> vec_train(massiv,massiv+10);

  std::cout << min(vec_train) << std::endl;
  return 0;
}

如果你需要处理空向量,你可以添加

if (!vec.size()) throw std::length_error("empty vector passed to min");

在函数的开头,或者 return 一个迭代器而不是元素引用,因为 end() 即使对于空向量也是定义明确的。