访问嵌套结构中的数据
accessing data within nested structures
我正在编写一个打印出哈希表的功能, 哈希表是 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.num
和e.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 ...
}
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 带参数的数据结构的全局声明