iterator for 2d vector

前端 未结 8 992
眼角桃花
眼角桃花 2020-12-04 10:32

How to create iterator/s for 2d vector (a vector of vectors)?

8条回答
  •  半阙折子戏
    2020-12-04 11:11

    Since it's 2020, I'll post an updated and easy method. Works for c++11 and above as of writing. See the following example, where elements (here: tuples of ) of 2D vector (vector of vector) is iterated to compare with another value (string query) and the function then returns first element with match, or indicate "Not found".

    tuple find_serial_data( vector >> &serial,
                                            string query)
    {
        for (auto& i : serial)
        {
            for (auto& j : i)
            {
                if ( get<0>(j).compare(query) == 0) return j;
            }
        }
        cout << "\n Not found";
        return make_tuple( "", 0);
    }
    

    Here is one example without the tuple thing:

    string find_serial_data( vector  > &serials,
                                            string query)
    {
        for (auto& i : serials)
        {
            for (auto& j : i)
            {
                if ( j.compare(query) == 0) return j;
            }
        }
        cout << "\n Not found";
        return  "";
    }
    

提交回复
热议问题