A vector is different from an array. The array itself is similar to a pointer, so what is passed in is a pointer. But vector is not so
Three ways of vector parameter passing:
- void func1(vector vet); //Transfer value
- void func2(vector &vet); //reference
- void func3(vector *vet); //Pointer
The effects of these three methods:
- Call the copy constructor, the formal parameter changes will not affect the actual parameters
- Do not call the copy constructor, the formal parameter changes affect the actual parameters
- Do not call the copy constructor, the formal parameter changes affect the actual parameters
code show as below:
void func1(vector<int> vet) {
vet.emplace_back(1);
}
void func2(vector<int> &vet) {
vet.emplace_back(2);
}
void func3(vector<int> *vet) {
vet->emplace_back(3); //指针用 ->
}
int main() {
vector<int> vet;
func1(vet);
cout << vet[0] << endl; //!!!报错,因为实参不会改变(想正常运行可注释掉这句)
vector<int> vet2;
func2(vet2);
cout << vet2[0] << endl; //输出 2
vector<int> vet3;
func3(&vet3); //这里取得是指针
cout << vet3[0] << endl; //输出 3
//system("pause");
return 0;
}
end:
vector best use references or pointers of mass participation , because if the large amount of data when the copy will be very slow; If you just do not want data to be modified, can be added before the vector const .