具有多个向量的类模板实现

Class template implementation with multiple vectors

本文关键字:实现 向量      更新时间:2023-10-16

我正在创建一个程序,该程序将数据文件读入向量,然后显示向量的最小和最大信息。我还必须使用类模板来查找最小值和最大值。我想知道是否有一种方法可以引用任何向量,而无需专门标记我想使用的两个向量。在下面的代码中,我必须声明向量 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;
    }
}

你有一个简单的误解。仅仅因为minmax的函数参数是v1并不意味着您唯一可以调用它的是称为v1的东西。实际上,它将是传入的向量的本地副本,本地命名为 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";
}

现场演示:http://ideone.com/cK13bR