Back
Close

C++ Runnable Snippets

Marchete
17.5K views
Previous: Passing a function as parameter Next: Sorting a vector

Filling an array with some initial value

  • Filling an static int array
#include <bits/stdc++.h>
using namespace std;
int staticArray[3000];
const int InitValue = 9990;
int main()
{
cout << "Uninitialized Array:"<<staticArray[3000-1] << endl;
std::fill(staticArray,staticArray+(end(staticArray) - begin(staticArray)),InitValue);
cout << "Array filled with:"<<staticArray[3000-1] << endl;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • Filling a vector array
#include <bits/stdc++.h>
using namespace std;
vector<int> dynArray;
const int InitValue = 9990;
int main()
{
dynArray.resize(3000);
cout << "Uninitialized Array:"<<dynArray.back() << endl;
std::fill(dynArray.begin(),dynArray.end(),InitValue);
cout << "Array filled with:"<<dynArray.back() << endl;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • Filling a vector array

The object for initialization is a complex one. std::fill works exactly the same.

Avoid memset as much as possible:

#include <bits/stdc++.h>
using namespace std;
class Pod{
public:
float x,y;
float vx,vy;
Pod(){ } //No initialization
Pod(float _x,float _y, float _vx, float _vy){
x=_x;y=_y;vx=_vx;vy=_vy;
}
};
vector<Pod> dynArray;
const Pod InitValue(0.6f,11.2f,0.45f,0.99f);
int main()
{
dynArray.resize(3000);
cout << "Uninitialized Vector:"<<dynArray.back().x<<","<<dynArray.back().y<< endl;
std::fill(dynArray.begin(),dynArray.end(),InitValue);
cout << "Array filled with:"<<dynArray.back().x<<","<<dynArray.back().y<< endl;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Check http://en.cppreference.com/w/cpp/algorithm/fill for more info

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants