Как передать обычный параметр, а также параметр шаблона в функции шаблона в C ++?

У меня есть функция шаблона (как показано ниже) в пространстве имен 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: In function ‘void myNamespace::getRandomItems(NaturalNumber, setX&, setX&) [with setX = std::set<std::basic_string<char> >, NaturalNumber = long unsigned int]’:
synthetic-graph.C:87:55:   instantiated from here
generic.h:74:32: error: no match for ‘operator=’ in ‘it = index.std::set::begin [with _Key = long unsigned int, _Compare = std::less<long unsigned int>, _Alloc = std::allocator<long unsigned int>, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<long unsigned int>]()’
/usr/include/c++/4.5/bits/stl_tree.h:224:5: note: candidate is: std::_Rb_tree_const_iterator<std::basic_string<char> >& std::_Rb_tree_const_iterator<std::basic_string<char> >::operator=(const std::_Rb_tree_const_iterator<std::basic_string<char> >&)
synthetic-graph.C:87:55:   instantiated from here
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<long unsigned int>, _Alloc = std::allocator<long unsigned int>, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<long unsigned int>]()’
/usr/include/c++/4.5/bits/stl_tree.h:291:7: note: candidate is: bool std::_Rb_tree_const_iterator<_Tp>::operator!=(const std::_Rb_tree_const_iterator<_Tp>::_Self&) const [with _Tp = std::basic_string<char>, std::_Rb_tree_const_iterator<_Tp>::_Self = std::_Rb_tree_const_iterator<std::basic_string<char> >]
generic.h:77:4: error: cannot convert ‘const std::basic_string<char>’ to ‘NaturalNumber’ in assignment

Я перепробовал все комбинации, но не повезло, пожалуйста, помогите мне !!!


person user654473    schedule 11.07.2011    source источник
comment
I have tried all combinations: покажите нам, какие комбинации вы пробовали   -  person sehe    schedule 12.07.2011


Ответы (2)


setX не является набором NaturalNumber, поэтому итераторы несовместимы, когда вы говорите it = index.begin(). Вы могли бы вместо этого сделать it итератором set<NaturalNumber>, я не могу понять, что вы действительно хотите здесь делать.

Также я заметил, что в вашем внутреннем цикле вы не выполняете никаких проверок, чтобы убедиться, что sit не выходит за пределы своего набора.

person Mark B    schedule 11.07.2011
comment
Спасибо @ mark-b и @sehe. Другой вопрос, относящийся к этому: как я могу передать набор типов данных шаблона в качестве аргумента такой функции: template ‹class X› void func (set ‹X› myset); Но это показывает ошибки. Как я могу это сделать? - person user654473; 14.07.2011

Вы пытаетесь назначить несовместимые итераторы.

Возможно, вы имели в виду

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

вместо того

typename setX::iterator it, sit = items.begin();
person sehe    schedule 11.07.2011