Please help with C++

I have just started learning C++ and i want to know how i can append values to an array.
say I have to append the squares of first N natural numbers, in python i would do

for i in range(N):
    arr.append(i**k)

how do i do this in C++?

i know i’ll first define

int arr[n];

and also for raised to power i will use

pow(i,2);

Array is static size fixed u will have to use vector

you can use dynamic arrays in C++
example

vector<int> arr;

this will declare a dynamic array named arr, in order to insert something in this array you will have to use push_back() function

arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);

now array will contain 4 elements [1, 2, 3, 4]

similarly to insert square of natural number you can do the following

vector<int> arr;
for(int i = 1; i <= N; i++) {
    arr.push_back(pow(i, 2));
}

for more information about vectors refer to https://en.cppreference.com/w/cpp/container/vector

2 Likes

thanks a ton!!!

either use STL vector or list.
c++ stl list has many functions like push_back(),pop_back(),push_front(),pop_front(),reverse() etc.most of operations on python list can be done here in c++ list

cannot convert ‘std::vector’ to ‘int*’ for argument ‘1’
how to fix this error?

can you share the code?

prog.cpp: In function ‘int main()’:
prog.cpp:46:25: error: cannot convert ‘std::vector<int>’ to ‘int*’ for argument ‘1’ to ‘int findbit(int*, int, int)’
      findbit(list_,n,sum);

this is the error…i would prefer not to share code if possible :point_right: :point_left:

If your talking about inserting elements in an array then you can simply use a for loop

for(int i;i<n;i++)
{
cin>>a[i];
}

not taken as input…

it seems like you are passing a std::vector to an int*
you should change your function header int findbit(int*, int, int) to int findbit(std::vector<int>, int, int)

1 Like

Ok change int* to vector<int>&. Next problem is do not use pow to compute integer values, it is not meant for that. Use 1<<k instead.

2 Likes

thanks @ayaan_mustafa and @everule1