编译错误-如何在c++模板函数中传递普通参数和模板参数

compiler errors - How to pass normal param as well as template param in a template function in C++?

本文关键字:参数 错误 函数 c++ 编译      更新时间:2023-10-16

在命名空间myNamespace中有一个模板函数(如下所示):

template <typename setX>
void getRandomItems(NaturalNumber size, setX &random, setX &items)
{
    assert(size <= items.size());
    //set of randomly selected indices for items
    set<NaturalNumber> index;
    NaturalNumber r, i;
    while(index.size() < size)
    {
        r = unifRand(0,items.size()-1);
        index.insert(r);
    }
    typename setX::iterator it, sit = items.begin();
    for(i = 0, it = index.begin(); it != index.end(); it ++)
    {
        //find the r-th elt in index
        r = *it;
        for(; i < r; i ++)
            sit++;
        random.insert(*sit);
    }
}

然而,每当我调用这个函数,我得到这些错误:

<>之前generic.h:在函数' void myNamespace::getRandomItems(NaturalNumber, setX&, setX&) [with setX = std::set>, NaturalNumber = long unsigned int] '中:c:87:55:从这里实例化Generic.h:74:32:错误:在' it = index '中' operator= '没有匹配。std::set::begin [with _Key = long unsigned int, _Compare = std::less, _Alloc = std::allocator, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator]() '/usr/include/c++/4.5/bits/stl_tree.h: 24:5:注:候选的是:std::_Rb_tree_const_iterator>& std::_Rb_tree_const_iterator>::operator=(const std::_Rb_tree_const_iterator>>&)c:87:55:从这里实例化Generic.h:74:32: error: no match for ' operator!= ' in ' it != index.std::set<_Key, _Compare, _Alloc>::end [with _Key = long unsigned int, _Compare = std::less, _Alloc = std::allocator, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator]() '/usr/include/c++/4.5/bits/stl_tree.h:291:7:注:候选是:bool std::_Rb_tree_const_iterator<_Tp>::operator!=(const std::_Rb_tree_const_iterator<_Tp>::_Self&) const [with _Tp = std::basic_string, std::_Rb_tree_const_iterator<_Tp>::_Self = std::_Rb_tree_const_iterator>]generic.h:77:4:错误:无法在赋值中将' const std::basic_string '转换为' NaturalNumber '之前

我已经尝试了所有的组合,但没有运气,请帮助我!!

setX不是NaturalNumber的集合,所以当你说it = index.begin()时迭代器是不兼容的。你可以让it成为set<NaturalNumber>的迭代器,我不太明白你在这里真正想做什么。

我还注意到,在你的内部循环中,你没有做任何检查,以确保sit不会跑掉它的集合的末尾。

您正在尝试分配不兼容的迭代器。

也许你的意思是

set<NaturalNumber>::iterator it;
typename setX::iterator sit = items.begin();
不是

typename setX::iterator it, sit = items.begin();