【问题标题】:Accessing a vector of pointers访问指针向量
【发布时间】:2016-05-06 20:21:00
【问题描述】:

这是针对 CS 作业的。我查看了类似的问题/问题,但似乎无法找到答案。

一些背景信息: 我们需要对列表中的 c 字符串进行排序,并计算每个单词出现的次数。问题所需:编写一个程序 Problem2_A.cpp,从键盘输入几行文本作为 C 字符串,并打印文本中每个单词的字母列表以及它出现的次数。为此,请在指针数组中保留一个指向每个单词的指针。使用 qsort() 函数对指针数组进行排序,然后计算每个单词的出现次数。通过从键盘发出文件结束信号来终止输入。忽略任何大小写差异(例如,“Cat”和“cat”是同一个词)。作为最低要求,您可能会假设没有标点符号,并且输入行中的单词恰好用一个空格分隔。您可以将此限制作为扩展删除。

编辑-我知道我需要让用户输入一行包含一堆单词。现在,我将只手动输入每个单词,因为我更关心访问向量并检索我想要检索的内容。

这是我目前所拥有的

Word.H

#pragma once
#ifndef __WORD_H__
#define __WORD_H__
#define _CRT_SECURE_NO_WARNINGS

class Word {
public:
    Word(char * word);

    ~Word();

    /* Returns the inputted word */
    const char* getWord();

private:
    char word[51];
};

#endif

Word.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Word.h"

Word::Word(char * word) {
    strcpy(this->word, word);
}

Word::~Word() {

}

const char* Word::getWord() {
    char* clone = new char[50];
    strcpy(clone, word);
    return clone;
}

问题2.cpp

#include <iostream>
#include <vector>
#include "Word.h"

using namespace std;

const int MAX_WORDS = 2;
const int MAX_WORD_LENGTH = 15;

char* promptWord();


int main() {
    char inputWord[MAX_WORD_LENGTH];
    vector<Word*> pWordList;
    pWordList.reserve(MAX_WORDS);

    cout << "Please type each word and press enter: ";

    for (int i = 0; i < MAX_WORDS; i++) {
        Word* newWord = new Word(promptWord());
        pWordList.push_back(newWord);
    }

    cout << "Printing &pWordList[i]" << endl;
    for (size_t i = 0; i < pWordList.size(); i++) {
        cout << &pWordList[i] << endl;
    }

    cout << "Printing (void*)pWordList[i]->getWord()" << endl;
    for (size_t i = 0; i < pWordList.size(); i++) {
        cout << (void*)pWordList[i]->getWord() << endl;
    }

    cout << "Printing pWordList[i]->getWord()" << endl;
    for (size_t i = 0; i < pWordList.size(); i++) {
        cout << pWordList[i]->getWord() << endl;
    }

    cout << "Printing (*pWordList[i]).getWord()" << endl;
    for (size_t i = 0; i < pWordList.size(); i++) {
        cout << (*pWordList[i]).getWord() << endl;
    }

    /* Delete our dynamic objects */
    while (!pWordList.empty()) {
        delete pWordList.back();
        pWordList.pop_back();
    }




    system("pause");
    return 0;
}

/*
Ask the user to enter their desired word
@params inputWord[MAX_WORD_LENGTH] -> Desired word to be inputted
@return Returns the user's inputted word
*/
char* promptWord() {
    char inputWord[MAX_WORD_LENGTH];
    cin.getline(inputWord, MAX_WORD_LENGTH);
    return inputWord;
}

我从来都不擅长使用指针,但如果我理解正确的话,我目前拥有的是一个指针向量,指向我动态分配的 Word 对象的位置。

我的部分困惑可能来自这个问题——我需要将对象放入指针向量中吗?还是我要创建指向对象的指针并将这些指针放在指针向量中?

无论如何,如您所见,我正在尝试找出输出单词的正确方法。当我称它为

cout << &pWordList[i] << endl;

这会输出每个单词的位置地址(单词指针?)。 使用

cout << (void*)pWordList[i]->getWord() << endl;

会输出不同的位置(指向向量索引的指针?)

并使用

cout << pWordList[i]->getWord() << endl;

cout << (*pWordList[i]).getWord() << endl;

将打印出相同的垃圾。

我很可能做错了,因为

pWordList[i]->getWord()

应该打印出有问题的c字符串,但我认为它在传输过程中丢失了,指针位置变得无效。真的会提供任何建议或意见。

Edit2-- 正如 Colin Basnett 和 T33C 所指出的,我已将函数更改为

/*
Ask the user to enter their desired word
@return Returns new dynamic char containing inputted word
*/
char* promptWord() {
    char* inputWord = new char[MAX_WORD_LENGTH];
    cin.getline(inputWord, MAX_WORD_LENGTH);
    return inputWord;
}

我现在可以输出正确的东西了。仍然想知道这两个不同的地点来自 &p单词列表[i] 和 (void*)pWordList[i]->getWord()

Edit3-- 这是我的方法,其中包含我的非工作地图。它应该对向量进行排序并使用单词(实际上是指向单词的指针)和它出现的次数创建一个映射。但是,它只是对其进行排序。即使多次输入同一个单词,它也会打印出出现次数为 1 的每个单词。这是因为它实际上是将指向单词的指针而不是单词本身插入到关键部分。

void measureVector(vector<Word*> ourVector, int numOfElements) {
    int count = 0;
    bool isDone = false;
    qsort(&ourVector[0], ourVector.size(), sizeof(Word*), wordCompare);

    map<Word*, int> wordCount;
    for (int i = 0; i < ourVector.size(); i++) {
        wordCount[ourVector[i]]++;
    }

    for (auto const& wc : wordCount) {
        cout << wc.first->getWord() << " appears " << wc.second << " times." << endl;
    }

}

我尝试过改变

for (int i = 0; i < ourVector.size(); i++) {
    wordCount[ourVector[i]]++;
}

for (int i = 0; i < ourVector.size(); i++) {
    wordCount[ourVector[i]->getWord()]++;
}

但是,这给出了一个错误说明

'[': no operator found which takes a right-hand operand of type 'const char *' (or there is no acceptable conversion)

Edit4-- 我再次给我的教授发了电子邮件,看看是否可以创建字符串映射并将 char* 转换为字符串,他说我可以,所以这是更新后的 measureVector 方法,以防其他人关注此方法。

/*
    Sorts our vector of pointers and puts all words into a map and
    keeps track of each word's occurrence.
    @params inputVector -> The vector of pointers to utilize.

*/
void measureVector(vector<Word*> inputVector) {
    /* Sort our vector of pointers */
    qsort(&inputVector[0], inputVector.size(), sizeof(Word*), wordCompare);
    map<string, int> wordCount;
    string ourString;

    /* For each word in our vector, insert it into our map. */
    for (auto word : inputVector) {
        ourString = word->getWord();
        wordCount[ourString]++;
    }

    /* For each unique word in our map, print out the word and how many times it occurred.*/
    for (const auto &p : wordCount) {
        cout << p.first << " appears " << p.second << " time" << (p.second > 1 ? "s." : ".") << endl;
    }
}

谢谢大家的指导!

【问题讨论】:

  • 您误解了要求。用户应该能够输入包含多个单词的任意长度的字符串,而不是一次输入一个单词。先解决这个问题,然后你才能处理代码中的无数其他问题。
  • 我以后会担心的。现在,我的主要问题是关于向量的访问,因为当我稍后切断 c 字符串时,它们最终仍将被放入向量中。为了简单起见,我将它们作为单个作品输入。
  • 您的promptWord 函数正在返回一个指向堆栈位置的指针,因此一旦堆栈展开,该值就会变成垃圾。您需要从该函数返回一个 new'd char 数组。
  • 谢谢,成功了。现在给出这个,为什么&amp;pWordList[i](void*)pWordList[i]-&gt;getWord() 输出两个不同的地址,而(*pWordList[i]).getWord()pWordList[i]-&gt;getWord() 返回同一个词?

标签: c++ pointers vector


【解决方案1】:

这段代码有很多问题,但您问题的关键是您正在返回一个指向堆栈上缓冲区的指针,该缓冲区在函数返回后不再存在。函数返回展开其堆栈帧。

char* promptWord() {
    char inputWord[MAX_WORD_LENGTH];
    cin.getline(inputWord, MAX_WORD_LENGTH);
    return inputWord;
}

我不愿说在堆上声明缓冲区并返回一个指向该缓冲区的指针,因为整个代码与现代 C++ 的位置相去甚远。

我推荐使用:

  1. std::string 并返回它而不是 char*
  2. 切勿在智能指针之外使用 new (或保证调用 delete 的东西),请参阅 std::unique_ptr 但 std::string 在您的情况下将是更好的选择。

祝你学习顺利。

【讨论】:

  • 谢谢。 Colin Basnett 指出了这一点,我让它正确输出了这个词。我不能使用 std::string 因为单词必须是要求授予的 c 字符串。我知道代码是“原始的”,但我正在做到目前为止我们在课程中学到的一切。请记住,这是第一级 C++ 课程。我从做研究中学到了一些东西,但大部分都是教给我们的
  • @Carousser - 欢迎您,感谢您接受我的回答。您可以通过调用返回 const char* 的 c_str() 方法从 std::string 获取指向 C 字符串的指针。 C++ 最近发生了许多变化,使其成为一种更安全、更容易编程的语言。我强烈推荐阅读 Scott Meyers 和 Bjarne Stroustrup 的最新书籍并在竞争中保持领先! :)
  • 我给我的教授发了电子邮件,询问我是否可以这样做,他说我们不能。但是,我完成了所有工作并对指针向量进行了排序。我的最后一件事是计算出现次数,我查看了地图,但我很难计算单词的实际出现次数,而不仅仅是指针。我将更新主线程。如果你有时间,你能提供更多的见解吗?我一定会把那本书添加到我的清单中!
  • @Carousser - 将出现次数存储在地图的值中。如果指针是排序的,那么为什么不遍历向量并计算有多少连续的单词是相同的呢?
猜你喜欢
  • 2021-12-10
  • 2012-06-07
  • 2018-12-16
  • 2023-03-23
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多