我尝试构建一个模板函数,它获取 vector
或 array 的 2 个迭代器(
(这必须是传递给函数的未知容器)。begin
和 end
)
我希望该函数检查传递给它的容器的大小。 我的问题是:如果
begin iterator
等于end iterator
是否意味着容器内有 0 个或 1 个元素? 我怎样才能标定一些通用尺寸类型?如果我想通过将迭代器传递给排序函数来对未知容器进行排序,这会成为一个问题吗?我有种感觉,它行不通。
这是我的模板函数草稿:
template<class P, class T>
T my_func(P beg, P end)
{
typedef typename ??? container_size;
if (beg == end)//first problem to determine if contains 0 or 1
elements
throw domain_error("some message if 0 elements");
sort(beg, end);// scond problem
}
最佳答案
- I want that the function will check for the size of the container passed to it. My problems are: if begin iterator equals end iterator does it mean 0 or 1 elements inside container? How can I decalare some universal size type ?
你应该使用 std::distance
为此。
- If I want to sort the unknown container by passing iterators to sort function is that becomes a problem? I have some feeling that it won't work.
只要迭代器是 RandomAccessIterators 就可以了值类型为 swappable
因此,您的代码可能是:
template<class P, class T>
T my_func(P first, P last)
{
if(first == last) // No elements within the range
throw domain_error("some message if 0 elements");
//Number of Elements within the range
auto container_size = std::distance(first, last);
std::sort(first, last);
return ...;
}
如果我的猜测是正确的,那么模板参数T
应该是迭代器的值类型,你可以使用 std::iterator_traits<T>::value_type
获取它
关于c++ - 未知容器、 vector 或数组的大小 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194010/