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

时间:2016-03-06 23:14:41

标签: c++ class templates 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;
    }

}

1 个答案:

答案 0 :(得分:1)

你有一个简单的误解。仅仅因为maxv1的函数参数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"; }

struct
{ 
    unsigned m : 3;
    unsigned n : 5;
} b;

int main(void)
{ 
    b.m = 2;
    b.n = 6;

    printf("%d", b);
}

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