C矢量与指针

前端之家收集整理的这篇文章主要介绍了C矢量与指针前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我被困在家庭作业上.我必须从文件中读取文本,将每个单词分配给内存,然后使用指针将其发送到向量< string *>.我的程序会使用文件中的新单词覆盖向量,而不是仅添加它.我无法弄清楚为什么会这样.
#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");
}

解决方法

使用向量< string>或者在堆上分配新字符串:
void WordFunctions(string *pstr,vector<string*> &words)
{
    words.push_back(new string(*pstr));
}

猜你在找的C&C++相关文章