6

我是 C++ 新手,恳请帮助解决问题。

我正在编写一个简单的 STL 样式函数,它应该返回序列的中间元素(向量、列表等)

这是我的函数,我尝试使用迭代器的概念

template <class It, class T> It  middle(It first, It last) 
{

    while(first!=last){
        ++first;
        --last;
    }
    return first;
}

这是我的主要内容,试图为整数向量调用中间(我省略了包含)

int main() {
    vector<int>vi;
    int x;
    cout<<"Enter vector elemets...";
    while (cin>>x)
    vi.push_back(x);
    cout<<endl;
    cin.clear();
    cout<<"the vector is:"<<endl;
    for(int i=0;i<vi.size();++i)
    cout<<vi[i]<<" ";
    cout<<endl;
    vector<int>::iterator first=vi.begin();
    vector<int>::iterator last=vi.end();
    vector<int>::iterator ii=middle(first,last);
    cout<<"The middle element of the vector is: "<<*ii<<endl;
}

使用 g++ 编译时出现以下错误:

myex21-7.cpp:79: error: no matching function for call to ‘middle(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)’

有人可以给我一些解决它的提示吗?感谢您对高级 snek 的任何帮助

4

5 回答 5

8

怎么样:

auto middle = container.begin();
std::advance(middle, container.size()/2);

如果您有可用的 C++11,std::next则可以在一行而不是两行中执行相同的操作。

另请注意,对于支持随机访问迭代器(例如,std::vectorstd::deque)的容器,这将相对有效(恒定复杂度而不是线性复杂度)。

于 2013-07-06T16:53:22.587 回答
6

这里的其他答案很有趣,但它们需要访问容器本身。要成为真正的 STL 风格,您应该使用迭代器范围。这是一个对随机访问迭代器有效的解决方案,但也适用于前向迭代器

// http://ideone.com/1MqtuG

#include <iterator>

template <typename ForwardIt>
ForwardIt DoMidpoint(ForwardIt first, ForwardIt last, std::forward_iterator_tag)
{
    ForwardIt result = first;

    // Try to increment the range by 2
    bool sawOne = false;
    // EDIT: Note improvements to this loop in the comments

    while(first != last)
    {
        ++first;
        if (sawOne)
        {
            // If that succeeded, increment the result by 1
            ++result;
            sawOne = false;
        }
        else
        {
            sawOne = true;
        }
    }

    return result;
}

template <typename RandomAccessIt>
RandomAccessIt DoMidpoint(RandomAccessIt first, RandomAccessIt last, std::random_access_iterator_tag)
{
    return first + (last - first)/2;
}

template <typename ForwardIt>
ForwardIt midpoint(ForwardIt first, ForwardIt last)
{
    return DoMidpoint(first, last, typename std::iterator_traits<ForwardIt>::iterator_category());
}
于 2013-07-06T17:34:00.610 回答
6

除非这是一个练习,否则根据std::next. 现在忽略具有偶数个元素的容器的特殊情况,您可以使用以下内容:

std::vector<SomeType> v = ....;
auto mid = std::next(v.begin(), v.size()/2);

至于你的代码的问题,你的middle函数模板有两个参数:

template <class It, class T> It  middle(It first, It last) { .... }

但是没有办法从函数参数中推导出第二个参数。由于无论如何都不需要该参数,您可以简单地删除它:

template <class It> It  middle(It first, It last) { .... } 
于 2013-07-06T16:52:47.640 回答
2

STL 中有几种迭代器,vector 具有随机访问的特征,这意味着您可以通过以下方式获取中间元素的迭代器

auto middle = v.begin() + v.size()/2;
于 2013-07-06T16:54:09.667 回答
0

这是另一种方法:

假设firstand是容器andlast的迭代器,那么:begin()end()

Iterator middle = first;
std::advance( middle, std::distance( first, last ) / 2 ); 
于 2017-02-27T21:00:10.570 回答