Passing vector by reference

后端 未结 5 2162
既然无缘
既然无缘 2020-12-13 14:21

Using normal C arrays I\'d do something like that:

void do_something(int el, int **arr)
{
   *arr[0] = el;
   // do something else
}

Now, I

相关标签:
5条回答
  • 2020-12-13 14:58

    You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector does not have a push_front member function. You can use the insert() member function on vector for O(n) insertion:

    void do_something(int el, std::vector<int> &arr){
        arr.insert(arr.begin(), el);
    }
    

    Or use std::deque instead for amortised O(1) insertion:

    void do_something(int el, std::deque<int> &arr){
        arr.push_front(el);
    }
    
    0 讨论(0)
  • 2020-12-13 15:02

    You can pass vector by reference just like this:

    void do_something(int el, std::vector<int> &arr){
        arr.push_back(el);
    }
    

    However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).

    In order to achieve exactly the same result you should write:

    void do_something(int el, std::vector<int> &arr){
        if (arr.size() == 0) { // can't modify value of non-existent element
            arr.push_back(el);
        } else {
            arr[0] = el;
        }
    }
    

    In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).

    0 讨论(0)
  • 2020-12-13 15:08

    If you define your function to take argument of std::vector<int>& arr and integer value, then you can use push_back inside that function:

    void do_something(int el, std::vector<int>& arr)
    {
        arr.push_back(el);
        //....
    }
    

    usage:

    std::vector<int> arr;
    do_something(1, arr); 
    
    0 讨论(0)
  • 2020-12-13 15:08

    You don't need to use **arr, you can either use:

    void do_something(int el, std::vector<int> *arr){
        arr->push_back(el);
    }
    

    or:

     void do_something(int el, std::vector<int> &arr){
        arr.push_back(el);
    }
    

    **arr makes no sense but if you insist using it, do it this way:

    void do_something(int el, std::vector<int> **arr){
        (*arr)->push_back(el);
    }
    

    but again there is no reason to do so...

    0 讨论(0)
  • 2020-12-13 15:14
    void do_something(int el, std::vector<int> **arr)
    

    should be

    void do_something(int el, std::vector<int>& arr)
    {
        arr.push_back(el);
    }
    

    Pass by reference has been simplified to use the & in C++.

    0 讨论(0)
提交回复
热议问题