【问题标题】:Converting the contents of a linked list to string (using stringstream) but cannot figure out how to iterate through list c++将链表的内容转换为字符串(使用 stringstream),但无法弄清楚如何遍历列表 c++
【发布时间】:2016-02-06 22:08:50
【问题描述】:

我目前正在尝试编写一个函数,该函数将使用 stringstream 将链表中的数据转换为字符串。我不知道该怎么做,但已经以最少的功能启动了该功能。我怎样才能更好地编写我的函数来实现这一点?

SList.cpp:

/*
 * SList.cpp
 *
 * written by Carlos D. Escobedo
 * created on 26 Oct
 *
 * References: programmingforums.org (printing linked lists), stackoverflow
 *             (.h file linking issues)
 */

#include "SList.h"


SList::SList() {
    head = NULL;
    size = 0;
}

SList::~SList() {
    SList::clear();
    delete head;
}

void SList::insertHead(int value) {
    if(head == NULL) {
        head = new SLNode(value);
    } else {
        SLNode* temp = new SLNode(value);
        temp->setNextNode(head);
        head = temp;
    }
    size++;
}

void SList::removeHead() {
    if (head != NULL) {
        head = NULL;  
        size--;
    }
}

void SList::clear() {
    head = NULL;
}

unsigned int SList::getSize() const {
    return size;
}

string SList::toString() const {
    stringstream ss;
    if (head != NULL) {
        ss.str("");
    } else {
        int i = 1;
        for (SLNode* n = head; n != NULL; n->getNextNode()) {
            if  (i < (size - 1))
                ss << n->getContents() << ", ";
            ss << n->getContents();
            i++;
        }
    }
    return ss.str();
}

【问题讨论】:

  • 假设一切都正确实现,我的假设是正确的,并且getNextNode()for 中返回指向下一个节点的指针(如果它是列表的末尾,则返回 NULL)您可以将n-&gt;getNextNode() 更改为n = n-&gt;getNextNode()
  • if (head != NULL) { 不应该是if (head == NULL) { 吗? (toString 的第 2 行)
  • 你为什么不使用std::list?迭代标准容器始终遵循相同的语法,无论是 std::liststd::vector 还是任何其他标准容器。
  • @Johny Mopp 是的!那应该是!很好,谢谢。
  • ^ 因为这是家庭作业/作业。

标签: c++ linked-list iteration tostring


【解决方案1】:

如果这不是家庭作业,您应该删除自制列表并使用标准容器,如矢量或列表。

向量示例

// vector of string
std::vector<std::string> stringVector;

// add strings
stringVector.push_back("text");
stringVector.push_back("more text");

// iterate all
for (auto& str : stringVector)
{
    // do something with str
    // example:
    std::cout << str;
}

c++ 中有许多标准容器,例如向量、列表、双端队列、数组。每个都有不同的优点和缺点。你需要学习他们写c++

【讨论】:

  • 两周前的作业。我不能再上交了,但我仍然想学习如何创建和操作自制的链表。
  • 在这种情况下,您应该根据模板编写一个列表,而忘记从字符串流开始。列表具有一些基本功能,例如添加和删除元素、检索元素、迭代列表等,这些功能应该在不知道元素类型的情况下实现。首先使用模板执行此操作。
猜你喜欢
  • 2023-03-25
  • 2013-11-05
  • 2012-11-14
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多