简体   繁体   English

带指针的C ++向量

[英]C++ vector with pointer

I am stuck on a homework assignment. 我被困在家庭作业上。 I have to read text from a file, allocate each word to memory, then user a pointer to send it to a vector<string*> . 我必须从文件中读取文本,将每个单词分配给内存,然后使用指针将其发送到vector<string*> My program keeps overwriting the vector with the new word from the file instead of just adding it. 我的程序会使用文件中的新单词覆盖向量,而不是仅添加它。 I can't figure out why this is happening. 我无法弄清楚为什么会这样。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;


void WordFunctions(string *pstr, vector<string*> &words)
{
    words.push_back(pstr);
}
int main(){
    ifstream file;
    vector<string*> a;
    string word;
    int w =0;
    file.open("word.txt");
    while (!file.eof())
    {
        w++;
        file >> word;

        WordFunctions(&word, a);
    }
    file.close();

     for (int i=0;i<10;i++){
        cout<<(*a[i])<<" ";
        delete a[i];
    }

     system ("pause");
}

Either use a vector<string> or allocate the new string on the heap: 使用vector<string>或在堆上分配新字符串:

void WordFunctions(string *pstr, vector<string*> &words)
{
    words.push_back(new string(*pstr));
}

You are pushing the same element into vector which is the address of word. 您正在将相同的元素推送到向量中,该向量是单词的地址。 I massage a bit on your code 我在你的代码上按了一下

// pass reference to eliminate copy
void WordFunctions(string &str, vector<string> &words)
{
    words.push_back(str);
}
int main(){
    ifstream file;
    vector<string> a;  // you want to store string not the address of the string
    string word;
    int w =0;
    file.open("words.txt");
    while (!file.eof())
    {
        w++;
        word.clear();   // clear the content before store something into it
        file >> word;
        WordFunctions(word, a);
    }
    file.close();

     for (size_t i=0;i<a.size();i++){  // use size instead of hard code magic number
        cout<<(a.at(i))<<" ";  // use at function instead of []
    }

     system ("pause");
}

your word string has always the same address in memory, so in the loop you are changing the value of the string, but then you call WordFunctions passing to him always the same address. 你的word字符串在内存中总是具有相同的地址,所以在循环中你改变了字符串的值,但是你调用WordFunctions总是传递给他相同的地址。

If it's a constraint to use vector<string*> instead of vector<string> , you will likely need to allocate memory for new strings in the loop, copy there your word and then pass the new reference to WordFunctions 如果使用vector<string*>而不是vector<string>是一个约束,你可能需要为循环中的新字符串分配内存,复制你的单词然后将新的引用传递给WordFunctions

char *wordPtr

while (!file.eof())
{
    w++;
    file >> word;

    wordPtr = (char *)malloc((strlen(word)+1)*sizeof(char));
    strcpy(wordPtr, *word);

    WordFunctions(wordPtr, a);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM