1
#include <iostream>
#include <array>
using namespace std;
int main(){
    int a = [];
    int b = 10;
    std::fill(a);
    cout<<a<<endl;
}

I have an array "a" and want to fill it with an integer "b". As I remember in python its simply uses apppend, does someone know solution?

5
  • 4
    Decide size of the array a first, or use std::vector. Commented Jul 22, 2020 at 13:21
  • 4
    int a = []; is not valid C++. Commented Jul 22, 2020 at 13:24
  • 4
    C++ is not Python. Commented Jul 22, 2020 at 13:27
  • Seems like declaring a as a std:array would let you use std::array::fill() -- en.cppreference.com/w/cpp/container/array/fill Commented Jul 22, 2020 at 13:29
  • The std::fill takes 3 parameters: starting address, one past end, and fill value. Commented Jul 22, 2020 at 15:07

4 Answers 4

3

Here one solution how to use your array header.

int b = 10;
std::array<int, 3> a;
std::fill(begin(a), end(a), b);
Sign up to request clarification or add additional context in comments.

Comments

3

I have an array "a"

int a = [];

What you have is a syntax error.

As I remember in python its simply uses apppend

A major difference between a C++ array and python list is that the size of C++ array cannot change, and thus nothing can be appended into it.

How to fill array in C++?

There is indeed a standard algorithm for this purpose:

int a[4];
int b = 10;
std::fill_n(a, std::size(a), b);

Comments

0

Decide the size for a, as it is an array not a list. For example:

int a[10];

Then use index values to fill in the array like:

a[0] = 1;
a[1] = 4;

etc.

If you want a dynamic array use std::vector instead

Here is how its done with vectors:

std::vector<int> myvector;
int myint = 3;

myvector.push_back (myint);

5 Comments

Why not using std:array if he included it?
@akirahinoshiro ok I edited my answer to include how its done with vectors
Author asked about "how to fill" an array, so I guess it is worth mentioning std::fill(std::begin(a), std::end(a), some_value);
@pptaszni I thought he was talking about appending integers to the array
The problem with this solution of 'int a[10]' what happens if you access the 11th member of your array?
-2

Following zohaib's answer: If your array is of fixed length: You can use the array's 'fill' member function like this: a.fill(b); If your array can change it's size you can use the std's fill function like this: std::fill(a.begin(), a.end(), b);

1 Comment

arrays are always of fixed size and a.fill(b); and std::fill(a.begin(),a.end(),b) are doing the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.