Skip to main content

For each Loop trick

· One min read
Sarthak Mohanty

taking input using for each

caution
  • vector must be declared with a size
    vector<int> v(4);

for (int &el : v)
{
cin >> el;
}
2D vector using for-each loop
    vector<vector<int>> v(k, vector<int>(n));

for (auto &el : v)
{
for (auto &el2 : el)
{
cin >> el2;
}
}

updating elements using for each

caution
  • vector must be declared with a size
    vector<int> v(4);


for (int &el : v) // using 'Reference' (&el) here
{
el = 99;
}