【发布时间】:2016-08-16 18:15:31
【问题描述】:
这是我第一次尝试通过向量传递引用。我以为我做对了,但我在尝试分配 a[0] = 5 的行上得到了 error: no viable overloaded '='
void BubbleSort(vector<int> *a) {
int n = a->size(), numberOfSwaps = 0;
if (n > 0)
a[0]= 5;
}
int main(){
// input size and array
int n;
cin >> n;
vector<int> a(n);
for(int a_i = 0;a_i < n;a_i++){
cin >> a[a_i];
}
// sort
BubbleSort(&a);
// print
for (auto i = a.begin(); i != a.end(); ++i)
cout << *i << ' ';
return 0;
}
编辑:
既然我被告知我实际上是通过指针传递的,我的问题是,我应该通过引用还是通过指针传递向量,还是无关紧要?
【问题讨论】:
-
在
BubbleSort中,您的参数a的类型为vector<int>*,将其更改为vector<int>&或在使用operator[]之前取消引用指针,如下所示:(*a)[0] = 5;。
标签: c++ vector compiler-errors pass-by-reference