首页 > 代码库 > 把vector中的string对象导入到字符指针数组中

把vector中的string对象导入到字符指针数组中

#include <iostream>
#include <string>
#include <vector>
//#include <cctype>
#include <cstring>
//#include "Sales_item.h"

using namespace std;

//把vector中的string对象导入到字符指针数组中
int main()
{
vector<string> svec;
string str;
cout << " Enter string to svector,( ctrl + z to end)" << endl;
while (cin>>str)
{
svec.push_back(str);
}

char **parr = new char*[svec.size()];
size_t ix = 0;

for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); ++iter){
char *cp = new char[(*iter).size() + 1];
strcpy(cp, (*iter).c_str());
parr[ix] = cp;
++ix;
}
//输出vector内容
for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); ++iter)
cout << *iter << " ";
cout << endl;
//输出数组内容
for (size_t i = 0; i < svec.size(); i++)
cout << parr[i] << " ";
//释放各个字符数组
for (ix = 0; ix !=svec.size(); ix++)
{
delete[] parr[ix];
}
//释放指针数组
delete[] parr;


cout << endl;
system("pause");
return 0;
}

把vector中的string对象导入到字符指针数组中