简体   繁体   中英

passing generic iterator to function cpp

Trying to send an iterator function using Template, that can get any iterator (from array, queue, etc..). [in the example, I send vector]

THE ERROR: line 15 not compile:

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
  2. missing public: before the constructor
  3. You cannot pass an rvalue to a function, which expects an lvalue reference, therefore I changed the function to get const lvalue references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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