[英]C++ Incompatible iterators types
我試圖打印一個圖表,編譯器出錯了。
錯誤如下: class "__gnu_cxx::__normal_iterator, std::allocator>> *, std::vector, std::allocator>>, std::allocator, std::allocator>>>>>" has no會員“開始”
end() 也是如此。
這是代碼:
void printGraph(std::vector<std::list<std::pair<int, int>>> graph)
{
for (std::vector<std::list<std::pair<int, int>>>::iterator i = graph.begin(); i < graph.end(); i++)
{
for (std::list<std::pair<int, int>>::iterator j = i.begin(); j < i.end(); j++)
printf("%d", (*j).first);
putchar('\n');
}
}
在你的內部循環中, i
是一個迭代器類型。 所以i
必須取消引用以引用 object。
for (std::list<std::pair<int, int>>::iterator j = (*i).begin(); j != (*i).end(); j++)
但是,您也可以使用->
運算符來訪問對象的成員
for (std::list<std::pair<int, int>>::iterator j = i->begin(); j != i->end(); j++)
然后您可以使用auto
關鍵字來保存迭代器的規范。
void printGraph(std::vector<std::list<std::pair<int, int>>> const& graph) {
for (auto i = graph.begin(); i < graph.end(); i++)
{
for (auto j = i->begin(); j != i->end(); j++)
printf("%d", j->first);
putchar('\n');
}
}
更緊湊的是,您可以使用基於范圍的 for 循環 (C++11) 並通過結構化綁定聲明 (C++17) 擴展對
void printGraph(std::vector<std::list<std::pair<int, int>>> const& graph) {
for (auto const& lst : graph) {
for (auto const& [first, second] : lst) {
printf("%d", first);
}
putchar('\n');
}
}
其次, std::list
有一個LegacyBidirectionalIterator ,它沒有定義operator <()
。 因此,您不能使用j < i.end()
。 j.= i.end()
但是確實有效。
編輯:那么讓我們添加另一個選項...使用即將到來的 C++20,您將能夠使用范圍,因此循環看起來像這樣:
void printGraph(std::vector<std::list<std::pair<int, int>>> const& graph) {
std::ranges::for_each (graph, [](auto const& lst) {
std::ranges::for_each (lst, [](auto const& pr) {
printf("%d", pr.first);
});
putchar('\n');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.