What is the proper way to declare the iterator i in the following code?
#include <iostream>
#include <vector>
using namespace std;
template<class Mat>
void f(const Mat& mat)
{
typedef typename Mat::value_type::iterator开发者_StackOverflow itr;
//itr i = (mat.begin())->begin(); //This Line Gives an error
typeof((mat.begin())->begin()) i = (mat.begin())->begin();
}
int main()
{
vector<vector<int> > vvi;
f(vvi);
return 0;
}
Do it the STL way and pass iterators, not containers:
//Beware, brain-compiled code ahead!
template<typename It>
void f(It begin, It end)
{
typedef typename std::iterator_traits<It>::value_type cont;
typedef typename cont::const_iterator const_iterator; // note the const_ pfx
const_iterator i = begin->begin();
// ...
}
int main()
{
vector<vector<int> > vvi;
f(vvi.begin(), vvi.end());
return 0;
}
Your container is const
, but your iterator type is not. Make that const_iterator
:
template<class Mat>
void f(const Mat& mat)
{
typedef typename Mat::value_type::const_iterator itr;
itr i = mat.begin()->begin();
}
Try the const iterator:
typedef typename Mat::value_type::const_iterator itr;
You pass as a const&, so you need a const_iterator:
typedef typename Mat::value_type::const_iterator itr;
itr i = (mat.begin())->begin();
精彩评论