来自键盘输入的c ++通用数据

时间:2014-08-16 23:37:32

标签: c++ generics linked-list

有没有办法从键盘获取通用数据T而无需进入方法调用?

类似的东西:

        T data;
        std::cout << "Please enter the data that you would like to delete: ";
        std::cin >> data;
        list.deleteAll(data);

除非我进入deleteAll方法,否则我实际上无法将变量数据创建为T.只是想知道是否有办法执行此操作。

LinkedList<int> list;

deleteAll:

void deleteAll(T data) {
    int i = 0;
    Node *curr = this->head, *prev;
    while(i < this->size){
        if(data == this[i].data && i == 0){
            this->head = curr->next;
            std::cout << curr->data << endl;
            delete curr;
        }
        else if(data == this[i].data){
            prev = curr;
            prev->next = curr->next;
            std::cout << curr->data << endl;
            delete curr;
            i++;
        }
        else{
            i++;
        }
        this->size--;
    }
}; //delete all

1 个答案:

答案 0 :(得分:1)

您可以使用模板功能执行此操作:

template <class T>
void promptAndDelete(LinkedList<T> list) {
    T data;
    std::cout << "Please enter the data that you would like to delete: ";
    std::cin >> data;
    list.deleteAll(data);
}