簡體   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