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

A template declaration cannot appear at block scope

本文关键字:范围内 声明 不能      更新时间:2023-10-16

我正在学习Lipmann,我只是在学习。我在这里尝试编写一个代码,该代码将在向量中返回最小元素。当我在代码块中编译代码时,它说:"模板声明不能出现在块范围内"。这是代码:

#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");

在函数的开头,或者返回迭代器而不是元素引用,因为即使对于空向量end()也定义得很好。