gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:33:34 26 4
gpt4 key购买 nike

我一直在尝试使用下面代码中所示的函数 triple3 将生成的 vector 中的每个值相乘时遇到困难。我想要做的是使用我命名为 array3 的 vector ,并使用函数 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] << " ";
}

最佳答案

Subscript operators are evaluated before indirection (*) .

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

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

(*v)[i] *= value;

关于C++如何使用指针将 vector 的值相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28292668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com