使用普通的 C 数组我会做这样的事情:
void do_something(int el, int **arr)
{
*arr[0] = el;
// do something else
}
现在,我想用 vector 替换标准数组,并在这里达到相同的结果:
void do_something(int el, std::vector<int> **arr)
{
*arr.push_front(el); // this is what the function above does
}
但它显示“表达式必须具有类类型”。如何正确执行此操作?
最佳答案
您可以通过引用传递容器,以便在函数中对其进行修改。其他答案没有解决的是 std::vector
没有 push_front
成员函数。您可以使用 vector
上的 insert()
成员函数进行 O(n) 插入:
void do_something(int el, std::vector<int> &arr){
arr.insert(arr.begin(), el);
}
或者使用 std::deque
代替分期 O(1) 插入:
void do_something(int el, std::deque<int> &arr){
arr.push_front(el);
}
关于c++ - 通过引用传递 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15890427/