#include使用问题

O_T 2012-09-16 01:43:11
#include <iostream>
#include <stack>
using namespace std;
struct elem { char name[20]; };
istream &operator >> (istream &in, elem &e)
{ return in >> e.name; }

ostream &operator << (ostream &out, const elem &e)
{ return out << e.name; }

int main(int argc,char* argv[])
{
elem e;
stack<elem> s;

for (int i = 0; i < 3; i++)
{
cin >> e;
s.push(e);
}

for (;!s.empty();s.pop())
cout << s.top() << endl;

return 0;
}
在使用栈的功能时,由于在自己编各个函数很麻烦,所以找人问了<stack>的用法,如果是多组的字符串输入又没办法一个一个定义变量,上面是别人交的,是能使一次输入多组字符串,由于C++没学多少,上面对于输入,出的流重载那段能解释下吗,还有这样被重载后在输入例如字符串的数据有影响吗,如果大家还有其他能解决<stack>这种多组字符串输入的方法希望能教下。
...全文
491 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mr_defy_L 2012-09-16
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
string str[3];
cout<<"a example of string:";
for(int i=0; i<3; ++i)
cin>>str[i];

for(i=0; i<3; ++i)
cout<<str[i]<<endl;

vector<string> vec;

cout<<"a emp of vector:";
string temp;
while(cin>>temp) //ctrl+z终止
vec.push_back(temp); //向vector容器中加入数据

for(vector<string>::iterator it = vec.begin(); it!=vec.end(); ++it) //标准库迭代器
cout<<*it<<endl;

return 0;
}


如果是你是用到栈,而且是对字符串的处理,stack<string> stk;
O_T 2012-09-16
  • 打赏
  • 举报
回复
#include<stack>中的pop().push()不就是专门用来完成出栈入栈的,你说的怎么实现,我对这些模板库中的不懂呀
Mr_defy_L 2012-09-16
  • 打赏
  • 举报
回复
重载<<,>>就是使自定义对象相当于内置对象一样进行输入输出,这个还是看看书比较好,还是用stack不是好的方法,因为栈是先进后出,可以用string数组或者vector<string>

64,642

社区成员

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

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