stl中的fill算法的问题

C++语言 码拜 8年前 (2016-04-15) 1035次浏览
deque<unique_ptr<char[]>> deStr(10);
fill(deStr.begin(), deStr.end(), (unique_ptr<char[]>)new char[10]());

如上代码为什么编译不能通过?
环境vs2010

解决方案

5

unique_ptr是不能复制的,假如支持C++11可以使用emplace:

    deque<unique_ptr<char[]>> deStr;
    for (size_t i = 0; i < 10; ++i) {
        deStr.emplace_back(new char[10]());
    }

或干脆别使用unique_ptr了,换成shared_ptr?std::array?std::string?

15

fill函数的原型是这样的:

template< class ForwardIt, class T >
void fill( ForwardIt first, ForwardIt last, const T& value );

其可能的实现实现时这样的:

template< class ForwardIt, class T >
void fill(ForwardIt first, ForwardIt last, const T& value)
{
    for (; first != last; ++first) {
        *first = value;
    }
}

unique_ptr重载了operator=操作符,但是只接受右值或nullptr,如下:

// members of the primary template, unique_ptr<T>
unique_ptr& operator=( unique_ptr&& r ); 
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r ); 
unique_ptr& operator=( nullptr_t ); 
// members of the specialization for arrays, unique_ptr<T[]>
unique_ptr& operator=( unique_ptr&& r ); 
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r ); 
unique_ptr& operator=( nullptr_t );

而fill的value是const T&型,所以在你的那段代码编译会出错。你可以使用其他接口来替代,如楼上的。另外VS2010支持的C++11功能比较少,你可以参看如下链接VS2010都支持哪些C++11特性:
https://msdn.microsoft.com/en-us/library/hh567368.aspx
https://blogs.msdn.microsoft.com/vcblog/2011/09/12/c11-features-in-visual-c-11/


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明stl中的fill算法的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)