【问题标题】:Search function issue in linked list [closed]链表中的搜索功能问题[关闭]
【发布时间】:2017-07-14 16:26:45
【问题描述】:

我的链表类的搜索功能实现有问题。它不打印我想要的东西,事实上,即使数据在列表中,它也什么也不打印。我哪里做错了?

我的主要:

#include "DList.h"
int main(void) {
    DList<int> list;
    DList<int>::const_iterator it;

    cout << list.size() << endl;
  list.push_front(30);
    list.push_front(10);
    list.push_back(100);
    list.push_front(22);

    list.print();
    it = list.begin();
    while (it != list.end()) {
            cout << *it << endl;
            it++;
    }
    DList<int>::iterator it2 = list.begin();
    while (it2 != list.end()) {
            *it2 = *it2 + 1;
            it2++;
    }
    it = list.begin();
    while (it != list.end()) { 
            cout << *it << endl;
            it++;
    }

    list.search(11);
    list.search(100);
    cout << list.size() << endl;


    return 0;
}

链表类:

    void erase(iterator it);
    void erase(iterator first, iterator last);

    iterator search(const T& data) {

            }

当前输出:

0
22
10
30
100
22
10
30
100
23
11
31
101
4

【问题讨论】:

  • 你说它没有打印出任何东西,但你已经写出了输出。请将您的问题剥离到最相关的部分,这样人们就不必搜索代码来确定问题。 stackoverflow.com/help/mcve
  • 调试器。使用调试器。调试器将帮助您了解您的程序实际上是如何流动的。您可以单独执行每个语句,观察变量的值。很有用。比使用 StackOverflow 更有效率。

标签: c++ linked-list iterator


【解决方案1】:

iterator search(const T& data) {
        iterator it = begin();
        iterator notIt = end();
        while (it.curr_ != back_) {
                if (*it == data)
                    cout << "found it" << endl;
                        return it; <-- right here!!!!
                ++it;
        }
        cout << "not in list" << endl;
        return notIt;
}

检查return it;。尽管出现了缩进,但它不在if 的主体内,因为if 没有主体。因此,始终会到达并始终返回此 return 语句。

清理格式让这一点非常明显:

iterator search(const T& data)
{
    iterator it = begin();
    iterator notIt = end();
    while (it.curr_ != back_)
    {
        if (*it == data)
            cout << "found it" << endl;
        return it;
        ++it;
    }
    cout << "not in list" << endl;
    return notIt;
}

愚蠢的缩进对任何人都没有帮助,尤其是对程序员而言。我建议使用代码格式化程序。您的 IDE 中可能会内置一个。

解决方法是使用大括号将return 语句括起来。

【讨论】:

  • 谢谢你的好先生
猜你喜欢
  • 2016-01-26
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2016-12-25
相关资源
最近更新 更多