问题:
ubuntu下编写测试下标运算符[]重载的程序。
使用while (cin >> buf)将接收到的字符串存储到string buf中,不知道该怎样结束cin的输入操作;
解决办法:
1. 放狗搜,结论是linux下使用Ctrl+d,windows下使用Ctrl+z来结束键盘输入。
源程序如下:
#include <iostream>#include <vector>using namespace std;class Assoc { struct Pair { string name; double val; Pair (string n = "", double v=0) : name(n),val(v) {} }; vector<Pair> vec; Assoc(const Assoc&); Assoc& operator=(const Assoc&);public: Assoc() { // vector<Pair> vec(1); } Assoc(int i) { for (int cj=0; cj<i; ++cj) { // vector<Pair> vec(i); vec.push_back(Pair("", cj)); } } double& operator[] (string&); void print_all() const; const int size() const;};double& Assoc::operator[](string& s) { // Search s; return its value if found, else return a new pair for (vector<Pair>::const_iterator p = vec.begin(); p != vec.end(); ++p) { if (s == p->name) { return (double&)p->val; } else { } } vec.push_back(Pair(s, 0)); return vec.back().val;}void Assoc::print_all() const { for (vector<Pair>::const_iterator p=vec.begin(); p != vec.end(); ++p) { cout << p->name << " : " << p->val << endl; }}const int Assoc::size() const { return vec.size();}int main(){ string buf; Assoc v1; while(cin >> buf) { v1[buf]++; } cout << "v1 size: " << v1.size() << endl; v1.print_all(); return 0;}
编译完成,运行程序。
程序的功能是从键盘接受输入的字符串,统计不同字符串的输入次数。
david@ubuntu:~/wrk/tmp/cpp_exer$ ./test_subscriptor_reloadboyboyboycatcatdogv1 size: 3boy : 3cat : 2dog : 1
使用Ctrl+D的方式结束从cin继续输入字符串。
至此,问题解决。
悠然享受和大自然融合之乐。