c++ - 未知容器、 vector 或数组的大小 c++

标签 c++ arrays vector

我尝试构建一个模板函数,它获取 vectorarray 的 2 个迭代器(beginend) (这必须是传递给函数的未知容器)。

  1. 我希望该函数检查传递给它的容器的大小。 我的问题是:如果 begin iterator 等于 end iterator 是否意味着容器内有 0 个或 1 个元素? 我怎样才能标定一些通用尺寸类型?

  2. 如果我想通过将迭代器传递给排序函数来对未知容器进行排序,这会成为一个问题吗?我有种感觉,它行不通。

这是我的模板函数草稿:

    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

    }

最佳答案

  1. 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 为此。

  1. 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/

相关文章:

java - 需要帮助处理 json 格式的字符串。 ( java )

java - 当我使用 String 类型参数枚举 vector 时,我得到 ClassCastexception,但使用 Integer 作为类型参数也不异常(exception)

c++ - 'list::list' 命名构造函数,而不是类型

c++ - 使用字符串数组 : arrays of pointers - Are they like multidimensional arrays?

java - 在数组中搜索特定数字并打印出所有相应的变量

c++ - 为什么我的数组元素检索函数返回随机值?

c++ - 在 C++ 的头文件中编写函数定义

c++ - 读取大量ASCII码并以二进制形式写入

c++ - 初始化 vector 迭代器

java - 如何从数组中获取 5 个数字的序列