【问题标题】:A template declaration cannot appear at block scope模板声明不能出现在块范围内
【发布时间】:2017-02-08 18:03:03
【问题描述】:

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

#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;
}

【问题讨论】:

  • 其实你可以用std::min_element.
  • 我认为这里的重点是 OP 试图了解如何实现这样的函数模板。

标签: c++ vector codeblocks


【解决方案1】:

你不能在函数内部定义模板,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() 即使对于空向量也是很好的定义。

【讨论】:

  • 非常感谢
  • 完成 :) 是的,这正是我想要的。您的回答很好,感谢您的关注:)
  • 这段代码有很多个编译错误,没有考虑空向量的情况。 min 应该返回一个迭代器,而不是一个元素,或者断言向量不为空。当然,在实际代码中,只需使用std::min_element
  • @ChristianHackl 好的,我修复了错误。 OP 在他的问题中按值返回向量元素,所以我做了下一个不复制 elemType 的最接近的事情。
  • @SU3:现在编译。我认为它仍然是一个设计不佳的函数接口,因为如果不对空向量调用未定义的行为,您实际上无法实现它。
猜你喜欢
  • 2020-09-07
  • 1970-01-01
  • 2020-03-23
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
相关资源
最近更新 更多