简体   繁体   中英

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]'

error: request for member 'push_back' in 'vec2', which is of non-class type 'std::vector [5]'

error: no match for 'operator*' in 'vec1[i] * vec2[i]'

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 . In this case you need not to check whether it has a negative value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM