【发布时间】:2016-03-06 23:14:41
【问题描述】:
我正在创建一个程序,它将数据文件读入向量,然后显示向量的最小和最大信息。我还必须使用类模板来查找最小值和最大值。我想知道是否有一种方法可以引用任何向量,而无需专门标记我要使用的两个向量。在下面的代码中,我必须声明向量 v1 以使我的模板执行最小值和最大值。是否可以为任何矢量制作此模板?
//Nicholas Stafford
//COP2535.0M1
//Read in text file into multiple vectors and display maximum and minimum integers/strings.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
//Template code area
template <class T>
T min(vector<T> v1)
{
T lowest = v1[0];
for (int k = 1; k < 10; k++)
{
if (v1[k] < lowest)
lowest = v1[k];
}
return lowest;
}
template <class T>
T max(vector<T> v1)
{
T highest = v1[0];
for (int k = 1; k < 10; k++)
{
if (v1[k] > highest)
highest = v1[k];
}
return highest;
}
int main() {
//Number of items in the file
const int size = 10;
//Vector and file stream declaration
ifstream inFile;
string j; //String for words in data file
vector<int> v1(size); //Vector for integers
vector<string> v2(size); //Vector for strings
//Open data file
inFile.open("minmax.txt");
//Loop to place values into vector
if (inFile)
{
for (int i = 0; i < size; i++)
{
inFile >> v1[i];
v1.push_back(v1[i]); //Add element to vector
}
cout << "The minimum number in the vector is " << min(v1) << endl;
cout << "The maximum number in the vector is " << max(v1) << endl;
}
else
{
cout << "The file could not be opened." << endl;
}
}
【问题讨论】:
-
您是否尝试打印出您的 v1 向量?结果可能会让你大吃一惊。您能否更好地解释“是否可以为任何矢量制作此模板?”您的意思是什么? ?您想要一个同时计算所有最大值的函数吗?
-
我认为你误解了一些东西。您是否尝试过将 v2 传递给您的模板函数?或者将模板定义/实现中的
v1更改为v并观察它仍然接受v1作为参数? -
好的,我发现了错误。当我使用 v1 时,它的最大值和最小值很好,但我不想再为另一个向量制作两个模板,这有点违背了模板的目的。
-
总是小事。当一切都只是对 v 的引用时,它起作用了。当我切换回 v 时,我错过了一个额外的 v1。谢谢
标签: c++ class templates vector