简体   繁体   English

使用模板在向量和数组之间交替

[英]Alternate between vectors and arrays using templates

Let's assume that I have a function that prints a set of numbers: 1, 2, 3, 4, 5 and these numbers can either be stored as an array, or, as a vector. 假设我有一个打印一组数字的函数: 1, 2, 3, 4, 5这些数字既可以存储为数组,也可以存储为向量。 In my current system I therefore have two functions that accept either of these parameters. 因此,在当前系统中,我有两个接受这些参数之一的函数。

void printNumbers(std::vector<double> &printNumbers)
{
   //code 
   //....
}

And therefore one that accepts an array.. 因此,它接受一个数组。

void printNumbers(int* numbers)
{
   //code 
   //...
}

This seems a waste of code, and, I was thinking that I could better take advantage of code re-use which got me thinking to this: Can I use a template to determine which type of input is being passed to the function? 这似乎是浪费代码,而且我想可以更好地利用代码重用,这使我开始思考:我可以使用模板来确定将哪种类型的输入传递给函数吗? For example, whether it's a vector or an array or just a single integer value? 例如,它是vector还是array还是仅是一个整数值?

Here is the prototype below: 这是下面的原型:

#include <iostream>

using namespace std;

template<class T>
void printNumbers(T numbers)
{
// code 
// code
}

int main(int argc, char *argv[]) {
   int numbers[] = {1, 2, 3, 4, 5};
   printNumbers<array> (numbers);    
}

Any help would be greatly appreciated. 任何帮助将不胜感激。

The usual idiom is to pass iterators, one for the first element of the range, and one corresponding to "one past the end": 通常的习惯用法是传递迭代器,一个用于范围的第一个元素,另一个对应于“结束后的一个”:

template<class Iterator>
void printNumbers(Iterator begin, Iterator end)
{
  for (Iterator i = begin; i != end; ++i)
    std::cout << *i << " ";
  std::cout << "\n";
}

int main() 
{
   int numbers[] = {1, 2, 3, 4, 5};
   printNumbers(numbers, numbers + 5);
   printNumbers(std::begin(numbers), std::end(numbers); // C++11 version
   std::vector<int> v{1,2,3,4,5};
   printNumbers(v.begin(), v.end());    
}

You could follow the example of the STL algorithms and accept an iterator range. 您可以遵循STL算法的示例并接受迭代器范围。 Containers have their iterator types, and pointers can be used to iterate over arrays: 容器具有其迭代器类型,并且指针可用于遍历数组:

template <typename InputIterator>
void printNumbers(InputIterator start, InputIterator end) {
    // print "*start", and iterate up to "end"
}

For convenience, you can overload this to accept containers and arrays directly: 为了方便起见,您可以对此进行重载以直接接受容器和数组:

template <typename Container>
void printNumbers(Container const & c) {
    printNumbers(c.begin(), c.end());
}

template <typename T, size_t N>
void printNumbers(T (const & a)[N]) {
    printNumbers(a, a+N);
}

In C++11 (or with your own begin and end functions) you can combine these: 在C ++ 11(或带有您自己的beginend函数)中,您可以将这些结合使用:

template <typename Container>
void printNumbers(Container const & c) {
    printNumbers(std::begin(c), std::end(c));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM