C++ iterator question
I saw an interview question, which was asked to use "iterator" to read vector<vector<int>>
. We have to design the necessary interface?
Quite confusing about does this question 开发者_开发知识库want to ask? Or how to answer this kind of question.
I can imagine that it intends to test C++ STL implementation and objected-oriented design.
Matrix
is in 3*4 dimension. If needed to access only through iterators, this should give you an idea -
vector< vector<int> > Matrix(3, vector<int>(3,4));
for( vector<vector<int>>::iterator i = Matrix.begin(); i != Matrix.end(); ++i )
{
for( vector<int>::iterator j = (*i).begin(); j != (*i).end(); ++j )
{
cout << *j << "\t" ;
}
cout << "\n" ;
}
You may find this website to be useful: http://en.wikipedia.org/wiki/Iterator#C.2B.2B
Just for fun, here is what my answer would have been to "Please use an iterator to print the values of a vector<vector<int> >
." :
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
using std::ostream;
using std::vector;
using std::cout;
template <class T>
ostream& operator<<(ostream&os, const vector<T>& v)
{
os<<"(";
// Can't use std::copy(ostream_iterator) easily due to ADL
for(typename vector<T>::const_iterator it = v.begin();
it != v.end();
it++) {
os<<(*it)<<", ";
}
return os<<")";
}
int main()
{
vector<vector<int> > vv(3, vector<int>(4));
cout << vv << "\n";
}
精彩评论