访问嵌套结构中的数据

accessing data within nested structures

本文关键字:数据 结构 嵌套 访问      更新时间:2023-10-16

我正在编写一个打印出哈希表的功能, 哈希表是 vector< list < Entry > >Entry的定义是struct Entry { string key, desc; unsigned num; };,但是当我编译此代码时,我会遇到错误...

void HT::hTable_print ( )
{
        bool lastempty = false;
        for(unsigned int i = 0; i < hsize; i++){
                list<Entry>& l = hTable[i];
                if(!l.empty()){//if list isnt empty
                        for(unsigned int x = 0; x < l.size();x++){//loop through list
                                if(lastempty){
                                        cout << endl;
                                }

                                Entry e = l.front()+x;
                                cout << setw(4) << x << ":  " << e.key << " - "
                                << setw(5) << e.num << "   -  " << e.desc 
                                << endl;
                        }
                        lastempty = false;
                 }else{
                        lastempty = true;
                }
        }
}

我正在尝试循环循环浏览矢量,并将每个列表元素分配到一个变量,然后循环循环该列表打印出必要的信息,但是当我调用e.key e.nume.desc时,我会遇到错误。如何正确调用每个Entry结构的信息?

编辑:汇编时我收到的一些错误:

hTable.cc:69:24: error: no match for ‘operator+’ (operand types are ‘__gnu_cxx::__alloc_traits<std::allocator<Entry> >::value_type {aka Entry}’ and ‘unsigned int’)
     Entry e = l.front()+x;
/usr/include/c++/7/bits/stl_iterator.h:397:5: note:   template argument deduction/substitution failed:
hTable.cc:69:25: note:   mismatched types ‘const std::reverse_iterator<_Iterator>’ and ‘unsigned int’
     Entry e = l.front()+x;
                     ^
/usr/include/c++/7/bits/stl_iterator.h:1198:5: note:   template argument deduction/substitution failed:
hTable.cc:69:25: note:   mismatched types ‘const std::move_iterator<_IteratorL>’ and ‘unsigned int’
     Entry e = l.front()+x;
                         ^

注意std::list::front()如何返回列表中的第一个元素的引用。您要做的是带std::list::begin()具有一个可前进的迭代器std::advance(),然后再解释:

list<Entry>::const_iterator iter = l.begin();
advance(iter, x);
const Entry& e = *iter;

或根据评论中的建议,首先通过迭代器迭代列表

unsigned int x = 0;
for (const auto& e : l) {//loop through list
   ++x;
   // .... stuff ...
}