C++ iterator question

放肆的年华 提交于 2019-12-24 18:13:43

问题


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.


回答1:


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" ;
}



回答2:


You may find this website to be useful: http://en.wikipedia.org/wiki/Iterator#C.2B.2B




回答3:


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";
}


来源:https://stackoverflow.com/questions/5347134/c-iterator-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!