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

在例子中通過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
而是使這個指針指向的對象的迭代器自增


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM