简体   繁体   English

未知容器,矢量或数组c ++的大小

[英]Size of unknown container, vector or array c++

I try to build a template function that gets 2 iterators( begin and end ) of either a vector or an array (this must be unknown container passed to function). 我尝试构建一个模板函数,它获取vectorarray 2个迭代器( beginend )(这必须是传递给函数的未知容器)。

  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? 我的问题是:如果begin iterator等于end iterator它是否意味着容器内的0或1个元素? How can I decalare some universal size type ? 我怎样才能改变一些通用尺寸类型?

  2. If I want to sort the unknown container by passing iterators to sort function is that becomes a problem? 如果我想通过将迭代器传递给sort函数来对未知容器进行排序,这会成为一个问题吗? I have some feeling that it won't work. 我有一些感觉它不会起作用。

This is my draft of the template function: 这是我的模板功能草案:

    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? 我的问题是:如果开始迭代器等于结束迭代器它是否意味着容器内的0或1个元素? How can I decalare some universal size type ? 我怎样才能改变一些通用尺寸类型?

You should use std::distance for that. 你应该使用std::distance

  1. If I want to sort the unknown container by passing iterators to sort function is that becomes a problem? 如果我想通过将迭代器传递给sort函数来对未知容器进行排序,这会成为一个问题吗? I have some feeling that it won't work. 我有一些感觉它不会起作用。

It would work, provided the iterators are RandomAccessIterators and the value type is swappable 如果迭代器是RandomAccessIterators并且值类型是可交换的 ,它将工作


So, your code could be: 所以,你的代码可能是:

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 ...;
}

If my guess is correct, that the template parameter T is supposed to be the value type of the iterator, you can obtain it using std::iterator_traits<T>::value_type 如果我的猜测是正确的,模板参数T应该是迭代器的值类型,你可以使用std::iterator_traits<T>::value_type来获取它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM