簡體   English   中英

訪問指針向量

[英]Accessing a vector of pointers

這是用於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;
}

Problem2.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;
}

現在我可以輸出正確的內容。 仍然想知道來自&pWordList [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;
    }
}

謝謝大家的指導!

這段代碼中有很多問題,但問題的關鍵在於,您正在返回一個指向堆棧緩沖區的指針,該緩沖區在函數返回后不再存在。 函數返回展開其堆棧幀。

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

我會猶豫地說,在堆上聲明緩沖區並返回指向該緩沖區的指針,因為整個代碼與現代C ++的位置相去甚遠。

我建議使用:

  1. std :: string並返回它而不是char *
  2. 切勿在智能指針(或保證調用delete的東西)之外使用new,請參閱std :: unique_ptr,但在您的情況下,std :: string是更好的選擇。

一切順利。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM