【问题标题】:c++ how to make a function (subroutine) argument either a vector of doubles or a vector of intsc ++如何使函数(子例程)参数成为双精度向量或整数向量
【发布时间】:2013-09-27 02:20:17
【问题描述】:

嘿,我只是想知道在 C++ 中是否有可能在我的程序中有一个函数作为输入,该函数采用向量或向量。这是我想要的一个例子:

void PrintValues(const std::string& title, std::vector<std::vector<double>>& v)
{
    std::cout << title << std::endl;
    for(size_t line = 0; line < v.size(); ++line)
    {
        for(size_t val = 0; val < v[line].size(); ++val)
        {
            std::cout << v[line][val] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

我有两个二维向量,我想在这个程序中打印,我想调用这个函数来打印两个向量,其中一个是双精度的,另一个是整数。这是可能的还是我的整数会自动转换为双精度数??

谢谢

【问题讨论】:

标签: c++ vector arguments 2d-vector


【解决方案1】:

让你的函数成为模板

template <typename T>
void PrintValues(const std::string& title, std::vector<std::vector<T> >& v)
{
    std::cout << title << std::endl;
    for(size_t line = 0; line < v.size(); ++line)
    {
        for(size_t val = 0; val < v[line].size(); ++val)
        {
            std::cout << v[line][val] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

及用途:

std::vector<std::vector<int> > x;
std::vector<std::vector<double> > y;
PrintValues("Int",x);
PrintValues("Doubles",y);

【讨论】:

  • 这部分:std::vector&lt;std::vector&lt;T&gt;&gt;可能会导致C++98报错。应该是:std::vector&lt;std::vector&lt;T&gt; &gt;。 ;)
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多