我正在创建一个程序,将数据文件读入一个 vector ,然后显示该 vector 的最小和最大信息。我还必须使用类模板来查找最小值和最大值。我想知道是否有一种方法可以引用任何 vector 而不必专门标记我想使用的两个 vector 。在我下面的代码中,我必须声明 vector 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;
}
}
最佳答案
你有一个简单的误解。仅仅因为 min
和 max
的函数参数是 v1
并不意味着你唯一可以调用它的是 v1
。实际上,它将是传入的 vector 的本地拷贝,在本地命名为 v1
。
#include <vector>
#include <iostream>
template<typename T>
size_t sizeit(std::vector<T> v) // try changing to v1, v2 and vx
{
return v.size(); // change to match
}
int main() {
std::vector<int> v1 { 1, 2, 3, 4, 5 };
std::vector<float> v2 { 1., 2., 3. };
std::cout << "v1 size = " << sizeit(v1) << "\n";
std::cout << "v2 size = " << sizeit(v2) << "\n";
}
关于c++ - 具有多个 vector 的类模板实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833813/