作為一個C 新手,在嘗試學習C 的模板和迭代器時,我寫了一個函式,使用C 的模板和迭代器來檢查一個數是否在陣列中。代碼如下:
template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){
for(;begin != end; begin ){
if(*begin == target){
return true;
}
}
return false;
}
int main(void){
vector<int> array{1,2,3,4,6,7};
if(find(array.begin(),array.end(), 7)){
cout << "find!";
}
else{
cout << "not found!";
}
}
當我運行上面的代碼時,我會遇到錯誤,如下所示:
template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){
^~~~~~
test.cpp:2631:94: error: expression list treated as compound expression in initializer [-fpermissive]
template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){
^
test.cpp:2631:95: error: expected ';' before '{' token
template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){
^
;
test.cpp: In function 'int main()':
test.cpp:2643:8: error: reference to 'find' is ambiguous
if(find(array.begin(),array.end(), 7)){
^~~~
In file included from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /algorithm:62,
from test.cpp:3:
C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /bits/stl_algo.h:3897:5: note: candidates are: 'template<class _IIter, class _Tp> _IIter std::find(_IIter, _IIter, const _Tp&)'
find(_InputIterator __first, _InputIterator __last,
^~~~
In file included from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /bits/locale_facets.h:48,
from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /bits/basic_ios.h:37,
from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /ios:44,
from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /ostream:38,
from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /iostream:39,
from test.cpp:1:
C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c /bits/streambuf_iterator.h:368:5: note: 'template<class _CharT2> typename __gnu_cxx::__enable_if<std::__is_char<_CharT2>::__value, std::istreambuf_iterator<_CharT> >::__type std::find(std::istreambuf_iterator<_CharT>, std::istreambuf_iterator<_CharT>, const _CharT2&)'
find(istreambuf_iterator<_CharT> __first,
^~~~
test.cpp:2631:43: note: 'template<class T> bool find<T>'
template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){
^~~~~~~~
我只是不知道該功能有什么問題,真誠地希望有人能提供幫助!
uj5u.com熱心網友回復:
您應該在函式引數中的迭代器型別之前添加 typename。此外,如果您為函式使用名稱 find 并在代碼中包含 std 命名空間,則會發生沖突。因此,您應該為函式使用另一個名稱,或者對 std 函式使用范圍決議運算子。在這里,我為您修復了它:
template<typename T>
bool findElement(typename std::vector<T>::iterator &begin,
typename std::vector<T>::iterator &end, T target){
for(;begin != end; begin ){
if(*begin == target){
return true;
}
}
return false;
}
int main(void){
std::vector<int> array{1,2,3,4,6,7};
auto it1 = array.begin();
auto it2 = array.end();
if(findElement(it1, it2, 7)){
std::cout << "find!";
}
else{
std::cout << "not found!";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/410165.html
標籤:
