C++ 使用unique\u ptr插入单个链表的位置

C++ 使用unique\u ptr插入单个链表的位置,c++,visual-c++,linked-list,C++,Visual C++,Linked List,我正在尝试使用unique_ptr实现单个链表的insert position函数。我在线跟踪了一个使用shared_ptr的类似实现,但我无法使我的函数正常工作,我遇到了一个我不太理解的错误: 1>------ Build started: Project: LinkedList, Configuration: Debug Win32 ------ 1>main.cpp 1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(177

我正在尝试使用unique_ptr实现单个链表的insert position函数。我在线跟踪了一个使用shared_ptr的类似实现,但我无法使我的函数正常工作,我遇到了一个我不太理解的错误:

1>------ Build started: Project: LinkedList, Configuration: Debug Win32 ------
1>main.cpp
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(177): error C2065: 'loc': undeclared identifier
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(168): note: while compiling class template member function 'void SingleLinkedList<int>::insertPosition(int,const T &)'
1>        with
1>        [
1>            T=int
1>        ]
1>c:\dev\linkedlist\linkedlist\main.cpp(50): note: see reference to function template instantiation 'void SingleLinkedList<int>::insertPosition(int,const T &)' being compiled
1>        with
1>        [
1>            T=int
1>        ]
1>c:\dev\linkedlist\linkedlist\main.cpp(23): note: see reference to class template instantiation 'SingleLinkedList<int>' being compiled
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(186): error C2679: binary '=': no operator found which takes a right-hand operand of type 'SingleLinkedList<int>::Node *' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(1390): note: could be 'std::shared_ptr<SingleLinkedList<int>::Node> &std::shared_ptr<SingleLinkedList<int>::Node>::operator =(std::shared_ptr<SingleLinkedList<int>::Node> &&) noexcept'
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(1377): note: or       'std::shared_ptr<SingleLinkedList<int>::Node> &std::shared_ptr<SingleLinkedList<int>::Node>::operator =(const std::shared_ptr<SingleLinkedList<int>::Node> &) noexcept'
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(186): note: while trying to match the argument list '(std::shared_ptr<SingleLinkedList<int>::Node>, SingleLinkedList<int>::Node *)'
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(190): error C2664: 'std::shared_ptr<SingleLinkedList<int>::Node>::shared_ptr(std::shared_ptr<SingleLinkedList<int>::Node> &&) noexcept': cannot convert argument 1 from 'const int' to 'std::nullptr_t'
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(190): note: only a null pointer constant can be converted to nullptr_t
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(191): error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::shared_ptr<SingleLinkedList<int>::Node>' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(2309): note: could be 'std::unique_ptr<SingleLinkedList<int>::Node,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)'
1>        with
1>        [
1>            _Ty=SingleLinkedList<int>::Node
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(2247): note: or       'std::unique_ptr<SingleLinkedList<int>::Node,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(std::unique_ptr<_Ty,std::default_delete<_Ty>> &&) noexcept'
1>        with
1>        [
1>            _Ty=SingleLinkedList<int>::Node
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(2173): note: or       'std::unique_ptr<SingleLinkedList<int>::Node,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(std::nullptr_t) noexcept'
1>        with
1>        [
1>            _Ty=SingleLinkedList<int>::Node
1>        ]
1>c:\dev\linkedlist\linkedlist\singlelinkedlist.h(191): note: while trying to match the argument list '(std::unique_ptr<SingleLinkedList<int>::Node,std::default_delete<_Ty>>, std::shared_ptr<SingleLinkedList<int>::Node>)'
1>        with
1>        [
1>            _Ty=SingleLinkedList<int>::Node
1>        ]
1>Done building project "LinkedList.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
1>----已启动生成:项目:LinkedList,配置:调试Win32------
1> main.cpp
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(177):错误C2065:“loc”:未声明的标识符
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(168):注意:在编译类模板成员函数“void singlelinkedlist::insertPosition(int,const T&)”时
1> 与
1>        [
1> T=int
1>        ]
1> c:\dev\linkedlist\linkedlist\main.cpp(50):注意:请参阅正在编译的函数模板实例化“void SingleLinkedList::insertPosition(int,const T&)”的参考
1> 与
1>        [
1> T=int
1>        ]
1> c:\dev\linkedlist\linkedlist\main.cpp(23):注意:请参阅对正在编译的类模板实例化“SingleLinkedList”的引用
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(186):错误C2679:二进制“=”:未找到接受“singlelinkedlist::Node*”类型的右操作数的运算符(或没有可接受的转换)
1> c:\program files(x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(1390):注意:可以是“std::shared\u ptr&std::shared\u ptr::operator=(std::shared\u ptr&&)noexcept”
1> c:\ProgramFiles(x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(1377):注意:或“std::shared\u ptr&std::shared\u ptr::operator=(const std::shared\u ptr&)noexcept”
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(186):注意:在尝试匹配参数列表(std::shared\u ptr,singlelinkedlist::Node*)时
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(190):错误C2664:“std::shared_ptr::shared_ptr(std::shared_ptr&&&)noexcept”:无法将参数1从“const int”转换为“std::nullptr_t”
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(190):注意:只有空指针常量才能转换为nullptr\t
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(191):错误C2679:二进制“=”:未找到接受“std::shared_ptr”类型右操作数的运算符(或没有可接受的转换)
1> c:\program files(x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(2309):注意:可以是“std::unique\u ptr&std::unique\u ptr::operator=(const std::unique\u ptr&)”
1> 与
1>        [
1> _Ty=SingleLinkedList::Node
1>        ]
1> c:\ProgramFiles(x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(2247):注意:或“std::unique\u ptr&std::unique\u ptr::operator=(std::unique\u ptr&&)noexcept”
1> 与
1>        [
1> _Ty=SingleLinkedList::Node
1>        ]
1> c:\program files(x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory(2173):注意:或“std::unique\u ptr&std::unique\u ptr::operator=(std::nullptr\t)noexcept”
1> 与
1>        [
1> _Ty=SingleLinkedList::Node
1>        ]
1> c:\dev\linkedlist\linkedlist\singlelinkedlist.h(191):注意:在尝试匹配参数列表(std::unique\u ptr,std::shared\u ptr)时
1> 与
1>        [
1> _Ty=SingleLinkedList::Node
1>        ]
1> 已完成生成项目“LinkedList.vcxproj”--失败。
======生成:0成功,1失败,0最新,0跳过==========
以下是我试图实现的功能:

template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
    if (pos > getSize() || pos < 0) {
        throw std::out_of_range("The insert location is invalid.");
    }
    else {
        if (pos == 0) {
            insertHead(theData);
        }

        else if (loc == getSize()) {
            insertTail(theData);
        }

        else {
            int nodeCount = 0;
            std::shared_ptr<Node> ptr(head.get());

            while (nodeCount < pos) {
                ptr = ptr->next.get();
                nodeCount++;
            }

            std::shared_ptr<Node> newNode(new Node(theData));
            ptr->next = newNode;
        }
    }
}
模板
void SingleLinkedList::insertPosition(int pos、const T和theData){
如果(pos>getSize()| | pos<0){
抛出std::超出范围(“插入位置无效”);
}
否则{
如果(位置==0){
插入标题(数据);
}
else if(loc==getSize()){
插入尾(数据);
}
否则{
int nodeCount=0;
std::shared_ptr ptr(head.get());
while(nodeCountnext.get();
nodeCount++;
}
std::shared_ptr newNode(新节点(theData));
ptr->next=newNode;
}
}
}
以下是整个头文件:

#ifndef SingleLinkedList_h
#define SingleLinkedList_h

#include <iostream>

template <class T>
class SingleLinkedList {
private:

    struct Node {
        T data;
        std::unique_ptr<Node> next = nullptr;
        Node(T x) : data(x), next(nullptr) {}
    };
    std::unique_ptr<Node> head = nullptr;
    Node* tail = nullptr;

    // This function is for the overloaded operator << 
    void display(std::ostream &str) const {
        for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
            str << loop->data << "\t";
        }
        str << "\n";
    }

public:
    // Constructors
    SingleLinkedList() = default;                                           // empty constructor 
    SingleLinkedList(SingleLinkedList const &source);                       // copy constructor

    // Rule of 5
    SingleLinkedList(SingleLinkedList &&move) noexcept;                     // move constructor
    SingleLinkedList& operator=(SingleLinkedList &&move) noexcept;          // move assignment operator
    ~SingleLinkedList();                                    

    // Overload operators
    SingleLinkedList& operator=(SingleLinkedList const &rhs);
    friend std::ostream& operator<<(std::ostream &str, SingleLinkedList &data) {
        data.display(str);
        return str;
    }

    // Memeber functions
    void swap(SingleLinkedList &other) noexcept;
    bool empty() const { return head.get() == nullptr; }
    int getSize() const;
    void push(const T &theData);                            
    void push(T &&theData);
    void display() const;
    void insertHead(const T &theData);
    void insertTail(const T &theData);
    void insertPosition(int pos, const T &theData);
    void deleteHead();
    void deleteTail();
    void deletePosition(int pos);
    bool search(const T &x);
};

template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T> const &source) {
    for(Node* loop = source->head.get(); loop != nullptr; loop = loop->next.get()) {
        push(loop->data);
    }
}

template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T>&& move) noexcept {
    move.swap(*this);
}

template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList<T> &&move) noexcept {
    move.swap(*this);
    return *this;
}

template <class T>
SingleLinkedList<T>::~SingleLinkedList() {
    while (head != nullptr) {
        deleteHead();
    }
}

template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList const &rhs) {
    SingleLinkedList copy{ rhs };
    swap(copy);
    return *this;
}

template <class T>
void SingleLinkedList<T>::swap(SingleLinkedList &other) noexcept {
    using std::swap;
    swap(head, other.head);
    swap(tail, other.tail);
}

template <class T>
int SingleLinkedList<T>::getSize() const {
    int size = 0;
    for (auto current = head.get(); current != nullptr; current = current->next.get()) {
        size++;
    }
    return size;
}

template <class T>
void SingleLinkedList<T>::push(const T &theData) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);

    if (head == nullptr) {
        head = std::move(newNode);
        tail = head.get();
    }

    else {
        tail->next = std::move(newNode);
        tail = tail->next.get();
    }
}

template <class T>
void SingleLinkedList<T>::push(T &&thedata) {
    std::unique_ptr<Node> newnode = std::make_unique<Node>(std::move(thedata));

    if (head == nullptr) {
        head = std::move(newnode);
        tail = head.get();
    }

    else {
        tail->next = std::move(newnode);
        tail = tail->next.get();
    }
}


template <class T>
void SingleLinkedList<T>::display() const {
    Node* newNode = head.get();
    while (newNode != nullptr) {
        std::cout << newNode->data << "\t";
        newNode = newNode->next;
    }
}

template <class T>
void SingleLinkedList<T>::insertHead(const T &theData) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
    newNode->next = std::move(head);
    head = std::move(newNode);
}

template <class T>
void SingleLinkedList<T>::insertTail(const T &theData) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
    tail->next = std::move(newNode);
    tail = tail->next.get(); 
}

template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
    if (pos > getSize() || pos < 0) {
        throw std::out_of_range("The insert location is invalid.");
    }
    else {
        if (pos == 0) {
            insertHead(theData);
        }

        else if (loc == getSize()) {
            insertTail(theData);
        }

        else {
            int nodeCount = 0;
            std::shared_ptr<Node> ptr(head.get());

            while (nodeCount < pos) {
                ptr = ptr->next.get();
                nodeCount++;
            }

            std::shared_ptr<Node> newNode(new Node(theData));
            ptr->next = newNode;
        }
    }
}

template <class T>
void SingleLinkedList<T>::deleteHead() {
    Node* old = head.get();
    auto next = std::move(old->next);
    head = std::move(next);
}

template <class T>
void SingleLinkedList<T>::deleteTail() {

}

template <class T>
void SingleLinkedList<T>::deletePosition(int pos) {

}

template <class T>
bool SingleLinkedList<T>::search(const T &x) {

}




#endif /* SingleLinkedList_h*/
\ifndef SingleLinkedList\u h
#定义SingleLinkedList_h
#包括
模板
类SingleLinkedList{
私人:
结构节点{
T数据;
std::unique_ptr next=nullptr;
Node(tx):数据(x),next(nullptr){
};
std::unique_ptr head=nullptr;
节点*tail=nullptr;
//此函数用于重载运算符next.get()){
str data next.get()){
大小++;
}
返回大小;
}
模板
void SingleLinkedList::push(常量T和数据){
std::unique\u ptr newNode=std::make_unique(数据);
if(head==nullptr){
头=标准::移动(新节点);
tail=head.get();
}
否则{
tail->next=std::move(newNode);
tail=tail->next.get();
}
}
模板
void SingleLinkedList::push(T&&thedata){
std::unique_ptr newnode=std::make_unique(std::move(thedata));
if(head==nullptr){
头=标准::移动(新节点);
tail=head.get();
}
否则{
tail->next=std::move(newnode);
tail=tail->next.get();
}
}
模板
void SingleLinkedList::display()常量{
Node*newNode=head.get();
while(newNode!=nullptr){
std::cout数据下一步;
}
}
模板
void SingleLinkedList::insertHead(常量T和数据){
std::unique\u ptr newNode=std::make_unique(数据);
newNode->next=std::move(head);
头=标准::移动(新节点);
}
模板
void SingleLinkedList::insertTail(常量T和数据){
std::unique\u ptr newNode=std::make_unique(数据);
tail->next=std::move(newNode);
tail=tail->next.get();
}
模板
void SingleLinkedList::insertPosition(int pos,const
#include <algorithm>
#include <cassert>
#include <iostream>
#include <ostream>
#include <iosfwd>
#include "SingleLinkedList.h"


int main(int argc, const char * argv[]) {


    ///////////////////////////////////////////////////////////////////////
    ///////////////////////////// Single Linked List //////////////////////
    ///////////////////////////////////////////////////////////////////////
    SingleLinkedList<int> obj;
    obj.push(2);
    obj.push(4);
    obj.push(6);
    obj.push(8);
    obj.push(10);
    std::cout<<"\n--------------------------------------------------\n";
    std::cout<<"---------------displaying all nodes---------------";
    std::cout<<"\n--------------------------------------------------\n";
    std::cout << obj << std::endl;


    std::cout<<"\n--------------------------------------------------\n";
    std::cout<<"-----------------Inserting At End-----------------";
    std::cout<<"\n--------------------------------------------------\n";
    obj.insertTail(20);
    std::cout << obj << std::endl;

    std::cout<<"\n--------------------------------------------------\n";
    std::cout<<"----------------Inserting At Start----------------";
    std::cout<<"\n--------------------------------------------------\n";
    obj.insertHead(50);
    std::cout << obj << std::endl;

    std::cout<<"\n--------------------------------------------------\n";
    std::cout<<"-------------inserting at particular--------------";
    std::cout<<"\n--------------------------------------------------\n";
    obj.insertPosition(5,60);
    std::cout << obj << std::endl;

    std::cout << "\n--------------------------------------------------\n";
    std::cout << "-------------Get current size ---=--------------------";
    std::cout << "\n--------------------------------------------------\n";
    std::cout << obj.getSize() << std::endl;

    //    std::cout<<"\n--------------------------------------------------\n";
    //    std::cout<<"----------------Deleting At Start-----------------";
    //    std::cout<<"\n--------------------------------------------------\n";
    //    obj.deleteHead();
    //    std::cout << obj << std::endl;
    //
    //    std::cout<<"\n--------------------------------------------------\n";
    //    std::cout<<"----------------Deleting At End-----------------";
    //    std::cout<<"\n--------------------------------------------------\n";
    //    obj.deleteTail();
    //    std::cout << obj << std::endl;
    //
    //
    //    std::cout<<"\n--------------------------------------------------\n";
    //    std::cout<<"--------------Deleting At Particular--------------";
    //    std::cout<<"\n--------------------------------------------------\n";
    //    obj.deletePosition(4);
    //    std::cout << obj << std::endl;
    //    std::cout << std::endl;
    //
    //    obj.search(8) ? printf("Yes"):printf("No");







    std::cin.get();
}
template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
    if (pos > getSize() || pos < 0) {
        throw std::out_of_range("The insert location is invalid.");
    }
    auto node = head.get();
    int i = 0;

    for (; node && node->next && i < pos; node = node->next.get(), i++);

    if (i != pos) {
        throw std::out_of_range("Parameter 'pos' is out of range.");
    }

    auto newNode = std::make_unique<Node>(theData);


    if (node) {
        newNode->next = std::move(node->next);
        node->next = std::move(newNode);
    }
    else {
        head = std::move(newNode);
    }
}