C ++如何使用指针将向量的值相乘?

C++ How to multiply values of vector using pointer?

我一直在尝试使用下面代码中所示的函数 triple3 将生成的向量中的每个值相乘时遇到困难。我想要做的是使用我命名为 array3 的向量,并使用函数 triple3(array3); 将它乘以三。但我无法弄清楚此错误消息的含义:

  indirection
  requires
  pointer
  operand
  ('vector<int>'
  invalid)
*v[i]...
^~~~~
1 warning and 1 error generated.

下面显示了正在使用的代码。

#include <iostream>
#include <vector>
#include <time.h>
#include <iomanip>

using namespace std;

void double3(int *v);
void triple3(vector<int> *v);
void displayVector3(vector<int> v);


int main() {
    srand(time(NULL));
    int size = 10;
    vector<int> array3;

    for(int i = 0; i < size; i++){
        array3.push_back(rand() % 51 + 50);
    }
//The following code is used to display the first three arrays
    cout << "Arrays after loading them with random numbers in the range [50,100]:"; 

    cout << "\nArray3:\t";
    for(int i = 0; i < array3.size(); i++){
        cout << setw(4) << left << array3[i] << "  ";
    }

//The following code displays the arrays after they have been doubled
    cout << "\n\nArrays after calling a function element by"
         << " element to double each element in the arrays:";

    cout << "\nArray3:\t";
    for(int v : array3){
        double3(&v);
        cout << setw(4) << left << v << "  ";
    }

//The following code displays the arrays after they have been tripled
    cout << "\n\nArrays after passing them to a function"
         << " to triple each element in the arrays:";

    cout << "\nArray3:\t";
        triple3(&array3);
        displayVector3(array3);

    cout << "\n\n";

    cout << "Press enter to continue...\n\n";
    cin.get();
}

void double3(int *v){
    *v *= 2;
}
void triple3(vector<int> *v){
    const int value = 3;
    for(int i = 0; i < 10; ++i){
    *v[i] *= value;}
}

void displayVector3(vector<int> vect){
    for(int i = 0; i < 10; ++i)
    cout << setw(4) << left << vect[i] << "  ";
}

我觉得 *v[i] 不对。您应该尝试将其更改为 (*v)[i].

您忘记将v设为

int的引用
for(int& v : array3){
    double3(&v);
    cout << setw(4) << left << v << "  ";
}

顺便说一句,你的 double3 最好也引用一个,所以声明为

void double3(int&);

并将其定义(即实现)为

void double3(int& i) { i *= 2; }

然后只需在 for 循环中调用 double3(v)

还有其他几个功能,例如triple3(然后你在其中编码v[i] *= value;,你的问题就解决了)

Subscript operators are evaluated before indirection (*).

因此该行的计算结果与 *(v[i]) *= value; 相同 - v[i] 将是对堆栈内存中您不想访问的某处 vector<int> 的引用,并且间接运算符 * 在应用于 vector<int> 引用时没有意义。

要修复编译错误,请明确说明您的操作顺序:

(*v)[i] *= value;

您可以只使用 std::transform 来转换 STL 容器中的元素。

std::transform(source.begin(), source.end(), destination.begin(), [](const int& param) { return param * 3; });

有关 std::transform 的更多信息,请参阅 here