简体   繁体   English

将通用迭代器传递给 function cpp

[英]passing generic iterator to function cpp

Trying to send an iterator function using Template, that can get any iterator (from array, queue, etc..).尝试使用模板发送迭代器 function,它可以获取任何迭代器(来自数组、队列等)。 [in the example, I send vector] [在示例中,我发送矢量]

THE ERROR: line 15 not compile:错误:第 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());
}

After fixing one compile time error after another I get this code:在一个接一个地修复一个编译时错误后,我得到了这个代码:

#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());
}

The errors and solutions are:错误和解决方法是:

  1. values ==> val values ==> val
  2. missing public: before the constructor缺少public:在构造函数之前
  3. You cannot pass an rvalue to a function, which expects an lvalue reference, therefore I changed the function to get const lvalue references.您不能将右值传递给需要左值引用的 function,因此我更改了 function 以获取const左值引用。

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

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