C++ STL遇到的几个问题

来源:互联网 发布:程序员必看书籍 编辑:程序博客网 时间:2024/06/05 06:39

1.vector与list的使用

vector中遍历的效果比list效果要好,但是插入数据的时候vector在开头和末尾比较简单,在中间位置插入或者删除时需要移动其他的数据,如果数据量大的话,而且频繁的插入或者删除的话,效率会很低。而list插入和删除只需要移动要插入的位置数据,因此效率会很高。

2.关于迭代器的使用

vector中迭代器不仅可以++和--,而且可以进行算数运算,比iter=iter+2。

但是list中,迭代器只能自增和自减,不能使用算术运算。

3.关于map中使用struct做为key的话产生的问题。

必须要进行<操作符重载

例如

typedef struct micro_be_x
{
        int request_code;
        int response_code;
        int response_code_exit;
        bool operator <(const micro_be_x& other) const
        {
                if( request_code == other.request_code )
                {
                        if( response_code == other.response_code )
                        {
                                return response_code_exit < other.response_code_exit;
                        }
                        else
                        {
                                return response_code < other.response_code;
                        }
                }
                else
                {
                        return request_code < other.request_code;
                }
        }
}micro_code_condition_t;

如果没有使用进行<重载的话,map进行查找的时候会报错

4.map中删除earse(pos)函数,无返回值,并且当前的迭代器也失效

所以正确的写法是map.earse(pos++);


0 0