设为首页 加入收藏

TOP

C++ vector::erase和无参构造函数的调用(代码教程)
2018-02-13 12:56:08 】 浏览:192
Tags:vector::erase 构造 函数 调用 代码 教程

vector::erase

C++ vector的元素删除,源码是这样的:

template <class _Tp, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
typename vector<_Tp, _Allocator>::iterator
vector<_Tp, _Allocator>::erase(const_iterator __position)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
    _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__position) == this,
        "vector::erase(iterator) called with an iterator not"
        " referring to this vector");
#endif
    _LIBCPP_ASSERT(__position != end(),
        "vector::erase(iterator) called with a non-dereferenceable iterator");
    difference_type __ps = __position - cbegin();
    pointer __p = this->__begin_ + __ps;
    this->__destruct_at_end(_VSTD::move(__p + 1, this->__end_, __p));
    this->__invalidate_iterators_past(__p-1);
    iterator __r = __make_iter(__p);
    return __r;
}

可知,C++将被删除部分的后面所有元素作为一个集合向前移动了。

所以,假设我们需要清空元素,不要这样写:

int main()
{
    vector<int> v_int;
    for(int i=0;i<10;i++){
        v_int.push_back(i+1);
    }
    int size = v_int.size();
    vector<int>::iterator it = v_int.begin();
    while(size--) {
        cout<<*it<<" ";
        v_int.erase(it++);   // attention !
        cout<<"size: "<<v_int.size()<<endl;
    }
    return 0;
}

它得到结果是这样的:

1 size: 9
3 size: 8
5 size: 7
7 size: 6
9 size: 5

将例子中的it++改成it即可,那样才能清空所有的元素。

无参构造函数的调用

形如Base instance()会调用类的无参构造函数吗?

答案是否定的,C++会将其解释成返回Base对象的函数。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Base{
public:
    Base(){ cout<<"Base()..\n"; }
    Base(string str){ cout<<str<<endl; }
    ~Base(){ cout<<"~Base().. \n"; }
};

int main()
{
    //Base ins(); //empty parentheses interpreted as a function declaration
    Base ins;     //ok
    Base ins2("hello world");  //ok
    return 0;
}

不过有意思的是,有参构造函数却是可以被这样调用的。

有时,我们会遇到这样的函数:

void show(const Base &b){
    //...
}

需要给该函数传递一个存储在栈中的变量,要构造这样的变量,我们可以简单地这样写Base(). 它等价于Base b.

即:

    //show(Base("hello"));  //ok. output: hello     it's equal to 'Base b("hello"); show(b);'
    //show(Base());         //ok. output: Base()..  it's equal to 'Base b; show(b);'
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++面向对象程序设计详情 下一篇c++四个强制转换实例讲解

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目