定义一个类对 list 进行封装, 使得可以用下标对 list 进行操作:
- #include <list>
- #include <vector>
- #include <iostream>
- #include <string>
- using namespace std;
- class Test
- {
- public:
- Test();
- //~Test();
- Test(list<string> strList);
- string &operator[](int n); // 一般这里需要有 & 的, 可以防止对象返回时去调用构造函数 (因为 return 值, 会有一个把值拷贝下来的过程)
- public:
- list<string> m_strList;
- };
- Test::Test(list<string> strList)
- {
- m_strList = strList;
- }
- //Test::~Test() // 当定义析构函数, 而没有实现时会报错.
- //{
- //
- //}
- string& Test::operator[](int n)
- {
- list<string>::iterator i = m_strList.begin();
- vector<list<string>::iterator> vecStrIter;
- for (; i != m_strList.end(); i++)
- {
- vecStrIter.push_back(i);
- }
- return *(vecStrIter[n]);
- }
- int main()
- {
- string str[4] = {"a", "li", "ba", "ba!"};
- list<string> strList(str, str+4);
- Test test(strList);
- cout << test[1] << endl;
- return 0;
- }
来源: http://www.bubuko.com/infodetail-3285451.html