有关C++ STL的问题,请高手指点下
#include <vector>
#include <iostream>
#include <map>
using namespace std;
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
int main()
{
map<const char*, int, ltstr> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
cout << "june -> " << months["june"] << endl;
map<const char*, int, ltstr>::iterator cur = months.find("june");
cout << (*cur).first ;
map<const char*, int, ltstr>::iterator prev = cur;
map<const char*, int, ltstr>::iterator next = cur;
++next;//为什么把++next 改成 next = next + 1; 编译不通过我用的是vc 6.0
--prev;
cout << "Previous (in alphabetical order) is " << (*prev).first << endl;
cout << "Next (in alphabetical order) is " << (*next).first << endl;
}
为什么把++next 改成 next = next + 1; 编译不通过我用的是vc 6.0
参考答案:应为next是一个图的迭代器,由于图只对++运算符作了个重载,没有对=赋值运算符做重载,所以会通不过变异的。
如果你只要移动两个单元的话,只要连续输入两句++next;不就行了,至于迭代器只有++next和next++这两种形式,对于next = next + ?和 next += ? 都不支持的。
补充:帮你改好了,在main()函数上加个运算符重载函数。
map<const char*, int, ltstr>::iterator
operator +( map<const char*, int, ltstr>::iterator p_iter, int N ) {
int i;
map<const char*, int, ltstr>::iterator p_ret = p_iter;
for(i = 0; i < N; i++)
p_ret++;
return p_ret;
}
这样next就可以next = next + 2;了。