繁体   English   中英

将通用迭代器传递给 function cpp

[英]passing generic iterator to function cpp

尝试使用模板发送迭代器 function,它可以获取任何迭代器(来自数组、队列等)。 [在示例中,我发送矢量]

错误:第 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());
}

在一个接一个地修复一个编译时错误后,我得到了这个代码:

#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. values ==> val
  2. 缺少public:在构造函数之前
  3. 您不能将右值传递给需要左值引用的 function,因此我更改了 function 以获取const左值引用。

暂无
暂无

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

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