如何访问具有地图的2D矢量?

问题描述 投票:0回答:1
int main()
{
    map<int,string> my_map;
    vector<map<int,string> > v_temp;
    vector< vector<map<int,string> > > vectors;
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
             my_map.insert(make_pair(1,"sea"));
             my_map.insert(make_pair(2,"ocean"));
            v_temp.push_back(my_map);
        }
        vectors.push_back(v_temp);
        v_temp.clear();
    }

    for(size_t i=0;i<vectors.size();i++)
        for(size_t j=0;j<vectors[i].size();j++)
            std::cout << "vectors[" << i << "][" << j << "][" << vectors[i][j].first<< " "<<vectors[i][j].second<<"]"<< std::endl;
    return 0;
}
                                                                                                   ^

我正面临编译问题,指出没有成员拥有第一和第二。我该如何访问它。预先感谢。

c++ stl
1个回答
2
投票

vectors[i][j]是没有mapfirstsecond。您想遍历地图的每个pair,并在其上使用firstsecond

for ( size_t i = 0; i < vectors.size(); i++ )
    for ( size_t j = 0; j < vectors[i].size(); j++ )
        for ( const auto &pair : vectors[i][j] )
            std::cout << "vectors[" << i << "][" << j << "][" << pair.first << " " << pair.second << "]" << std::endl;

PS:强烈建议notusing namespace std,请参阅here for reasons

© www.soinside.com 2019 - 2024. All rights reserved.