简体   繁体   中英

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*> . 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:

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.

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

char *wordPtr

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

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

    WordFunctions(wordPtr, a);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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