C矢量与指针
发布时间:2020-12-16 05:02:06 所属栏目:百科 来源:网络整理
导读:我被困在家庭作业上.我必须从文件中读取文本,将每个单词分配给内存,然后使用指针将其发送到向量 string *.我的程序会使用文件中的新单词覆盖向量,而不是仅添加它.我无法弄清楚为什么会这样. #include iostream#include fstream#include vector#include strin
我被困在家庭作业上.我必须从文件中读取文本,将每个单词分配给内存,然后使用指针将其发送到向量< 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)); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |