簡體   English   中英

為什么我的模板化函數需要從一個迭代器到另一個迭代器的轉換?

[英]Why does my templated function require a conversion from one iterator to the other?

我正在嘗試實現一個二叉搜索樹容器。 目前我必須實現一個能夠返回迭代器或常量迭代器的 find() 函數。 我選擇重載 find 函數以適應這兩種可能性

MyIterator<treepair> find(const key& x)
{
    return tree_search<MyIterator<treepair>>(root,x);   
}
const_MyIterator<treepair> find(const key& x) const
{
    return tree_search<const_MyIterator<treepair>>(root,x); 
}

然后函數 tree_search 通過遍歷樹遞歸地找到包含所需鍵的節點:

template<typename iterator>
iterator tree_search(Node<treepair>* x, const key& y) const
{
    if(x == nullptr)
    {
        std::cout<<"element not found"<<std::endl;
        iterator x = end();//HERE I HAVE A PROBLEM
        return x;
    }
    else if (y == x->value.first)
    {
        iterator i{x,tree_maximum()};
        std::cout<<"element found"<<std::endl;
        return i;
    }
    if(y < x->value.first) 
        return tree_search<iterator>(x->left,y);
    else return tree_search<iterator>(x->right,y);
}

現在 end() 函數被重載以提供一個 const_iterator 和一個常規迭代器:

MyIterator<treepair> end(){
return MyIterator<treepair>{nullptr,tree_maximum()};
}

const_MyIterator<treepair> end() const{
return const_MyIterator<treepair>{nullptr,tree_maximum()};
}

但是我收到這個錯誤

test_on_iterators.cc:508:12: error: conversion from ‘const_MyIterator<std::pair<int, int> >’ to non-scalar type ‘MyIterator<std::pair<int, int> >’ requested
      iterator x = end();

這個錯誤是由於類型之間的轉換需要嗎? 編譯器不應該根據它必須生成的迭代器類型來選擇想要的 end() 函數嗎?

編譯器不應該根據它必須生成的迭代器類型來選擇想要的 end() 函數嗎?

不。

tree_search()是一個const方法。 這意味着它的this指針指向一個const對象(即使調用對象tree_search()並不是真正的const )。

因此,當tree_search()內部調用end() ,它會調用可在const對象上調用的重載。 該重載返回一個const_MyIterator 然后tree_search()嘗試將該const_MyIterator分配給非常量MyIterator ,這是您收到錯誤的地方,因為沒有定義從const_MyIteratorMyIterator轉換。

您需要使x成為const_MyIterator以匹配end()const版本返回的內容。

您還應該讓tree_search()返回一個const_MyIterator ,而不是返回一個非常量iterator 如果您希望tree_search()返回非常量Iterator ,則不要將tree_search()聲明為const方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM