[英]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());
}
錯誤和解決方法是:
values
==> val
public:
在構造函數之前const
左值引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.