STL 编译问题
我在vstudio 2003里面编译成功的一个程序,到linux下面就报错了。下面是我的小程序,其中有一行是这个map_itr = second.erase(tmp_map_itr); 在linux下编译时(gcc/g++ 3.3.1),报错说没有定义map的operator=操作,请问一下为什么?
《c++ primer plus》这本书上作者说程序在vstudio 2003和linux gcc/g++ 3.3.1上都测试过,为什么我的不行呢?
急啊,谢谢大家先!
帮我看一下代码:
#include <iostream>
#include <iterator>
#include <list>
#include <map>
using namespace std;
struct data{
int i;
double j;
data(int a, double b):i(a), j(b){}
};
int _tmain(int argc, _TCHAR* argv[])
{
typedef map <int, struct data> maptype;
ostream_iterator <int, char> out(cout, " ");
maptype first;
int i;
typedef pair <int, struct data> data_pair;
for (i = 0; i < 5; i++) {
first.insert(data_pair(i,data(i,i+1)));
}
maptype second(first);
maptype::iterator map_itr;
for (map_itr = second.begin(); map_itr != second.end(); map_itr++) {
if (map_itr-> first == 3 || map_itr-> first == 2) {
maptype::iterator tmp_map_itr;
tmp_map_itr = map_itr;
map_itr = second.erase(tmp_map_itr);
map_itr--;
}
}
return 0;
}
[解决办法]
map_itr = second.erase(tmp_map_itr);
是这句错。
map的erase根据C++标准,无返回值。你这个代码太老了,还是C++标准制定前的代码了。
你那个书该换了。换C++ Primer吧,不要浪费生命了。
[解决办法]
second.erase(tmp_map_itr);
=============
erase不返回迭代器,无效位置
[解决办法]
erase
Syntax:
#include <map>
void erase( iterator pos );
void erase( iterator start, iterator end );
size_type erase( const key_type& key );
The erase function() either erases the element at pos, erases the elements between start and end, or erases all elements that have the value of key.
For example, the following code uses erase() in a while loop to incrementally clear a map and display its contents in order:
struct strCmp {
bool operator()( const char* s1, const char* s2 ) const {
return strcmp( s1, s2 ) < 0;
}
};
...
map <const char*, int, strCmp> ages;
ages[ "Homer "] = 38;
ages[ "Marge "] = 37;
ages[ "Lisa "] = 8;
ages[ "Maggie "] = 1;
ages[ "Bart "] = 11;
while( !ages.empty() ) {
cout < < "Erasing: " < < (*ages.begin()).first < < ", " < < (*ages.begin()).second < < endl;
ages.erase( ages.begin() );
}
When run, the above code displays:
Erasing: Bart, 11
Erasing: Homer, 38
Erasing: Lisa, 8
Erasing: Maggie, 1
Erasing: Marge, 37
[解决办法]
void erase( iterator pos );
void erase( iterator start, iterator end );
size_type erase( const key_type& key );
没有返回 迭代器 的erase版本 ...