Passing vector by reference

后端 未结 5 2161
既然无缘
既然无缘 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 &arr){
        arr.insert(arr.begin(), el);
    }
    

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

    void do_something(int el, std::deque &arr){
        arr.push_front(el);
    }
    

提交回复
热议问题