gpt4 book ai didi

c++ - 如何在 C++ 的模板函数中传递普通参数和模板参数?

转载 作者:行者123 更新时间:2023-11-28 03:48:17 25 4
gpt4 key购买 nike

我在名为 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 heregeneric.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 heregeneric.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

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

最佳答案

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

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

关于c++ - 如何在 C++ 的模板函数中传递普通参数和模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6657026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com