提问者:小点点

将泛型迭代器传递给函数cpp


尝试发送一个迭代器函数使用模板,可以得到任何迭代器(从数组,队列等)。 “在示例中,我发送矢量”

错误:第15行未编译:

ExampleVector <int> vec(values.begin(), values.end())")
template <typename ExampleVectorType>
class ExampleVector //new  class
        {
            template <class InputIterator> // generic iterator
            ExampleVector (InputIterator& first, InputIterator& last) // constructor (do nothing)
            {
            }
        };
int main()
{
    /* Create the values */
    std::vector<int> val{4, 8, 12};
    /* Create the vec */
    ExampleVector <int> vec(val.begin(), val.end());
}

共1个答案

匿名用户

在修复了一个又一个编译时错误之后,我得到了以下代码:

#include <iostream>
#include <vector>
 
template <typename ExampleVectorType>
class ExampleVector //new  class
        {
            public:
            template <class InputIterator> // generic iterator
            ExampleVector (const InputIterator& first, const InputIterator& last) // constructor (do nothing)
            {
            }
        };
int main()
{
    /* Create the values */
    std::vector<int> val{4, 8, 12};
    /* Create the vec */
    ExampleVector <int> vec(val.begin(), val.end());
}

错误和解决方法是:

  1. ==>; val
  2. 在构造函数之前缺少public:
  3. 不能将rvalue传递给需要lvalue引用的函数,因此我更改了该函数以获取constlvalue引用。