通过值引用传递向量不会改变传递的原始向量?

Passing a vector by reference by the values are not changing in original vector which is passed?

我正在练习 C++ 中的函数指针。我写了下面的代码。我已经声明了一个整数向量并为其添加了值。之后,我通过引用将 vector 的值传递给函数。我将值添加到向量的每个值。之后,当我显示原始向量的内容时,值不会改变。以下是代码。

void printValues (int val) {

    cout << val << " ";

}

void ForEach (vector<int> values, void (* func )(int), int inc) {

    for (int value : values) {
        value = value + inc;
        func (value);
    }
}

int main() 
{   
    vector<int> v1;
    cout << "Please enter the values in vector";
    for (int i = 0; i < 5; i++) {
        int val = 0;
        cin >> val;
        v1.push_back(val);
    }



    cout << "value stored in vector :" ;
        ForEach(v1, printValues,8);

    cout << "\nThe content of original vector:";
    for (int i = 0; i < v1.size(); i++) {
        cout << " " << v1[i];
    }



}

我预计输出为 58,68,78,88,98,但实际输出为 50,60,70,80,90。

vector<int> values 不是按引用传递参数,而是按值传递。循环的相同问题(使用 int value 您也将制作副本)。使用 &:

void ForEach (vector<int> &values, void (* func )(int), int inc) { // reference for the parameter

    for (int & value : values) {  // reference for the loop
        value += inc;
        func (value);
    }
}

旁白:

  • 不要使用 using namespace std。到处使用 std::vector 而不是
  • 每次看到 void ForEach (std::vector<int> values, 中的函数参数时,想知道数据是 "input" 还是 "output"。如果是"input",使用常量引用const std::vector<int> &values来避免复制,同时防止修改,如果是"output",则使用std::vector<int> &values传递可写引用。
  • 在你的循环中你可以使用 auto: for (auto & value : values)(也会适应 const)所以如果类型改变,你不必改变你的循环。