C++ iterator question

2019-08-30 09:09发布

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.

3条回答
戒情不戒烟
2楼-- · 2019-08-30 09:13

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" ;
}
查看更多
祖国的老花朵
3楼-- · 2019-08-30 09:14

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";
}
查看更多
虎瘦雄心在
4楼-- · 2019-08-30 09:20

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

查看更多
登录 后发表回答