我一直在试图使用下面代码中显示的函数triple3来乘以生成的向量中的每个值。我想要做的是使用我命名为array3的向量,并使用函数triple3(array3)将其乘以3;但我无法弄清楚这个错误信息的含义:
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] << " ";
}
答案 0 :(得分:2)
您可以使用std::transform
转换STL容器中的元素。
std::transform(source.begin(), source.end(), destination.begin(), [](const int& param) { return param * 3; });
有关std :: transform的更多信息,请参阅here
答案 1 :(得分:1)
我觉得* v [i]不对。您应该尝试将其更改为(* v)[i]。
答案 2 :(得分:1)
您忘了将v
引用提交给<{p>}中的int
for(int& v : array3){
double3(&v);
cout << setw(4) << left << v << " ";
}
顺便说一句,你的double3
最好也应该参考,所以声明为
void double3(int&);
并将其定义(即实施)为
void double3(int& i) { i *= 2; }
然后只需在double3(v)
循环中调用for
同样适用于其他几个功能,例如: triple3
(然后您将在其中编码v[i] *= value;
,您的问题就会得到解决)
答案 3 :(得分:1)
Subscript operators are evaluated before indirection (*)
因此该行评估与*(v[i]) *= value;
相同 - v[i]
将引用您不想访问的堆栈内存中的vector<int>
,以及间接运算符*
在应用于vector<int>
引用时无意义。
要修复编译错误,请明确您的操作顺序:
(*v)[i] *= value;