【问题标题】:Class template implementation with multiple vectors具有多个向量的类模板实现
【发布时间】: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


【解决方案1】:

你有一个简单的误解。仅仅因为你的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

【讨论】:

  • v.size() 也会帮助 OP 的 max 和 min 函数。
  • 知道大小相对于最小值和最大值有什么作用?
  • @NStafford 您的模板化函数仅适用于 10 个大小的向量。如果您使用 v.size() 它们将适用于每种尺寸。并检查你的 v1 向量的大小......
  • 啊,这解决了我必须为循环定义大小的问题。我明白了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多