• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、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:
1lexword
2lexword

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

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

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


可见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
而是使这个指针指向的对象的迭代器自增


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c++中的引用与指针的区别发布时间:2022-07-13
下一篇:
C语言程序设计100例之(5):分解质因数 - aTeacher发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap