通过引用传递向量 [英] Passing vector by reference
本文介绍了通过引用传递向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用正常的C数组我会这样做:
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 want to replace standard array with vector, and achieve the same results here:
void do_something(int el, std::vector<int> **arr)
{
*arr.push_front(el); // this is what the function above does
}
但它显示类类型。如何正确地这样做?
But it displays "expression must have class type". How to do this properly?
推荐答案
您可以通过引用传递容器,以便在函数中修改它。还没有解决的其他答案是 std :: vector
没有成员函数 push_front
。您可以在向量
上使用 insert()
成员函数进行O(n)插入:
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);
}
或使用 std :: deque
代替分摊的O(1)插入:
Or use std::deque
instead for amortised O(1) insertion:
void do_something(int el, std::deque<int> &arr){
arr.push_front(el);
}
这篇关于通过引用传递向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文