这样的vector如何压指定指针进去 请大家指教 多谢

power0811 2009-02-16 04:21:30
请帮忙看下如下代码 我的目的就是想把sp所指向的字符串压入vector.然后输出vector中的元素


#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
vector<string> **pvec = new vector<string>*[10];
char *sp = "hello";
char *arr[10];
char **arr2[10];
arr2[0]=&sp;
arr[0]=sp;
pvec.push_back(&sp); 这样做不对 该怎么做 将sp的地址保存在另外两个指针数组中
pvec.push_back(sp); 这样也不对
cout<<sp<<endl;
cout<<*arr2[0]<<endl;
return 0;
}
...全文
117 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
逸学堂 2009-02-16
  • 打赏
  • 举报
回复
给lz一个简单代码吧,另外说一下,既然用vector为啥不用string哪?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
vector<string> pvec;
string sp = "hello";
pvec.push_back(sp);
cout<<sp<<endl;
cout<<pvec[0]<<endl;
return 0;
}

power0811 2009-02-16
  • 打赏
  • 举报
回复
我就是被自己绕晕了 自己实验的代码 定义竟然能通过 然后就是不知道怎么使用 呵呵
多谢各位 我试一下
InfidelX 2009-02-16
  • 打赏
  • 举报
回复
楼主写的很麻烦,char * 和string是两种不同的类型,这个要注意,给你个简单的例子,vc 2005下通过:
=================
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
vector<string> * strVect = new vector<string>();
string test("this is a string");
strVect->push_back(test);
cout<<strVect->front()<<endl;
strVect->push_back(string("Leo"));
strVect->push_back(string("Java"));
copy(strVect->begin(),strVect->end(),ostream_iterator<string> (cout,"\n"));
system("pause");
return 0;
}
waizqfor 2009-02-16
  • 打赏
  • 举报
回复
[Quote=引用楼主 power0811 的帖子:]
请帮忙看下如下代码 我的目的就是想把sp所指向的字符串压入vector.然后输出vector中的元素


C/C++ code
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
vector<string> **pvec = new vector<string>*[10];
char *sp = "hello";
char *arr[10];
char **arr2[10];
arr2[0]=&sp;
arr[0]=sp;
pvec.push_back(&sp); 这样做不…
[/Quote]
LZ定义的变量类型存在问题啊 也不至于弄那么麻烦
vector<string> **pvec = new vector<string>*[10];//可以这样吗?
======>
vector<string> pvec[n] =new vector<string>;
pvec[n]->push_back(sp);直接压就可以

tangshuiling 2009-02-16
  • 打赏
  • 举报
回复

本来简单的问题,楼主自己被自己绕晕了!
pvec.push_back(&sp); //pvec是什么型别,&sp又是什么型别,难道楼主写代码都不看类型的吗?
vector<string> pvec;
char* sp="hello";
pvec.push_back(sp);
cout<<pvec[0]<<endl;
简单的几句代码被楼主的指针的指针的指针...搞晕了!
a_rockboy 2009-02-16
  • 打赏
  • 举报
回复

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
vector<char **> vec;
char *sp = "hello";

char *arr[10];
char **arr2[10];

arr[0]= sp;
arr2[0]=&arr[0];

vec.push_back(&sp);
cout<<sp<<endl;
cout<<*arr2[0]<<endl;
return 0;
}



试试这个
hai040 2009-02-16
  • 打赏
  • 举报
回复
vector<string> **pvec
这个是什么?

pvec[0] = new vector<string>;
pvec[0]->push_back(sp);

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧