C++中vector::data()使用心得和对自定义类型指针运算符的默认重载

博客 分享
0 222
优雅殿下
优雅殿下 2022-03-19 17:56:56
悬赏:0 积分 收藏

C++中vector::data()使用心得和对自定义类型指针运算符的默认重载

一、C++ vector::data()函数

返回值类型:vector的基类
返回值:Returns a pointer such that [data(), data() + size()] is a valid
range. For a non-empty %vector, data() == &front().
等价于:&vector::front()

例子

//基类型定义class Token {private:    int lineshow; //记录该单词在原程序中的行数    string lex;    string sem;public:    Token(int, string, string);    ~Token();    int getLineShow() {        return this->lineshow;    }    string getLex() {        return this->lex;    };    string getSem() {        return this->sem;    }};//主函数int main() {    // initialising vector     vector<Token> vec;    vec.push_back(Token(1, "lex","word"));    vec.push_back(Token(2, "lex","word"));    // memory pointer pointing to the     // first element     Token* pos = vec.data();	//Token* pos = &vec.front();    // prints the vector     cout << "The vector elements are: ";    for (int i = 0; i < vec.size(); ++i) {        cout <<pos->getLineShow()<< pos->getLex()<<pos->getSem()<<endl;        pos++;//为什么pos++可以定位到下一个数组?    }        return 0;}output:The vector elements are:1lexword2lexword

在例子中通过data()获得该数组对应类型的指针,指向该数组的首元素
其作用等价于 Token* pos = &vec.front();
并通过该指针对数组进行了遍历

在过程中有一个困惑 为什么pos++ 可以定位到数组中的下一个元素?

于是对代码进行了调试并查看pos++执行前后指针的内容
image

image
可见pos++不等价于pos+=1
而等价于 pos+=基类型的大小
由此引出下一个标题

C++对于++运算符的默认重载

直接上源码(节选)

json.h:  Value::ObjectValues::iterator current_;    SelfType& operator++() {    increment();    return *this;  }  jsoncpp.cpp:  void ValueIteratorBase::increment() {#ifndef JSON_VALUE_USE_INTERNAL_MAP  ++current_;#else  if (isArray_)    ValueInternalArray::increment(iterator_.array_);  ValueInternalMap::increment(iterator_.map_);#endif}

核心函数是incrument()
在其中是对current自增 而在json.h中定义了current是迭代器
在对基类型取值的时候调用的是类型的迭代器
而迭代器的自增则是增加基类的大小

总结:

基类型指针的++运算符的作用
不是使这个指针指向地址自增1
而是使这个指针指向的对象的迭代器自增

posted @ 2022-03-19 17:10 wang200010 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员