Home > Net >  C Reimplementing assignable "at()" function of vector
C Reimplementing assignable "at()" function of vector

Time:09-30

What i discovered

I discover that C vector::at() is an assignable function, how is it possible?

I mean I can call at() function to get the value of vector at certain position, and i can assign a value to a certain position of the vector.

    std::vector<int> vec;
    vec.push_back(4);
    vec.push_back(5);
    vec.push_back(6);

    //get val at position
    cout << vec.at(0)<<endl; //it print 4

    //set val at position
    vec.at(0) = 89;
    std::cout << vec.at(0)<<endl; //it print 89

What I want to do

I want to reimplement in my own vector class without inherit it or copy the original class; how can i do it?

class myIntVector
{
    int arraye[50] = {0};
    
    //other class function and constructor
public:
    int at(int index)
    {
        //some code
    }
};

CodePudding user response:

I want to reimplement in my own vector class without inherit it or copy the original class; how can i do it?

Not trying to sound too snarky but you could read the documentation:

Return value

Reference to the requested element.

Therefore something like this:

class myIntVector
{
    int arraye[50] = {0};
    
    //other class function and constructor
public:
    int& at(int index)
    {
        return arraye[index];
    }
};

Also your indices should be std::size_t, and std::array is preferred to C-style arrays.

  • Related