[英]C++ Vectors: Error in calling push_back
I am executing the following code, but I am getting the following error messages: 我正在执行以下代码,但收到以下错误消息:
error: request for member 'push_back' in 'vec1', which is of non-class type 'std::vector [5]' 错误:请求'vec1'中的成员'push_back',该成员属于非类类型'std :: vector [5]'
error: request for member 'push_back' in 'vec2', which is of non-class type 'std::vector [5]' 错误:请求“ vec2”中的成员“ push_back”,该成员属于非类类型“ std :: vector [5]”
error: no match for 'operator*' in 'vec1[i] * vec2[i]' 错误:“ vec1 [i] * vec2 [i]”中的“ operator *”不匹配
I am trying to multiply two vectors(by dynamically taking input) and storing the result in an array using pointer notation. 我试图乘以两个向量(通过动态获取输入)并将结果存储在使用指针表示法的数组中。 Please help me out? 请帮帮我吗? Thank you! 谢谢!
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int value1, value2;
int length;
cout << "Please enter the size of the vectors" << endl;
cin >> length;
vector<int> vec1[5];
vector<int> vec2[5];
cout << "Please enter the values for vector 1" << endl;
for(int i = 0; i < length; i++){
cin >> value1;
vec1.push_back(value1);
}
cout << "Please enter the values for vector 2" << endl;
for(int i = 0; i < length; i++){
cin >> value2;
vec2.push_back(value2);
}
int *ptr = new int[length];
for(int i = 0; i < length; i++){
ptr[i] = vec1[i] * vec2[i];
}
for(int i = 0; i < length; i++){
cout << *(ptr + i) << " ";
}
}
For your purpose you should use:- 为了您的目的,您应该使用:-
vector<int> vec1;
vector<int> vec2;
then reserve whatever amount you want 然后保留您想要的任何数量
vec1.reserve(5);
vec2.reserve(5);
The vectors have to be defined like 向量必须像
vector<int> vec1;
vector<int> vec2;
instead of 代替
vector<int> vec1[5];
vector<int> vec2[5];
Also after the definitions of the vectors you could reserve memory for their potential elements: 同样,在向量定义之后,您可以为它们的潜在元素保留内存:
vec1.reserve( length );
vec2.reserve( length );
And do not forget to delete the allocated dynamically array 并且不要忘记删除分配的动态数组
delete [] ptr;
Also it would be better if length would be declared as having type size_t
instead of int
. 同样,如果将length声明为具有size_t
类型而不是int
类型,则更好。 In this case you need not to check whether it has a negative value. 在这种情况下,您无需检查它是否具有负值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.