C++迭代器问题

发布于 2024-10-23 20:16:28 字数 162 浏览 3 评论 0 原文

看到一道面试题,要求用“iterator”来读取vector>。我们要设计必要的接口吗?

很困惑这个问题想问吗?或者说如何回答这样的问题。

我可以想象它是为了测试C++ STL实现和面向对象设计。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你的他你的她 2024-10-30 20:16:28

Matrix 是 3*4 维度。如果只需要通过迭代器访问,这应该给你一个想法 -

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

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" ;
}
动听の歌 2024-10-30 20:16:28

您可能会发现这个网站很有用:http://en.wikipedia.org/维基/迭代器#C.2B.2B

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

┊风居住的梦幻卍 2024-10-30 20:16:28

只是为了好玩,我的回答是“请使用迭代器打印 vector >”的值。 :

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

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";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文