Means the below function

int minMeetingRooms(vector& intervals)
vector<pair<int, int>> changes;
for (auto i : intervals) {
changes.push_back({i.start, 1});
changes.push_back({i.end, -1});
sort(begin(changes), end(changes));

I can not understand for loop using auto i…Please help me to understand and simplify this loop.

what i feel is that this “auto i” will iterate over all the elements/arrays/things in vector, with working as below-

let intervals be { [2,1],[1],[3,4,5]}

In first iteration, I would be [2,1], in next it would be [1], in next it would be [3,4,5].

And we can use this value of I easily to perform functions.

And I feel its access by value, (afaik access by reference is something on liens of “auto&& i” )

So, yeah, that’s what I feel. Would love if anyone can verify it though :slight_smile:

It is a for each loop and simplified syntax of primitive for loop. In your case

for (auto i : intervals){

(auto is from C++, Details on auto)
is same as

for (int i=0;  i<intervals.size(); i++){

(In Java)

Further, For each for same thing in Java

 for (Interval i : intervals){
1 Like

Auto is a specifier which is a new feature of C++11.It means that the type is deduced from the initializer.In simple words it simply means that the type of an object/variable is obtained from its initializer. Since C++ is a statically typed language, thus we need to associate type while declaring variables/objects. Auto comes to rescue in scenario where type can be deduced from the declaration.

Ex: auto x=3 // similar to int x=3
auto i //error type cant be dedeuced
auto i: intervals //Intervals is a vector of pair<int,int> thus i becomes vector<pair<int,int>>::iterator
You can now feel that auto saved us from writing the long type(vector<pair<int,int>>::iterator).

Auto,decltype is quite handy while dealing with lamdda functions/ anonymous functions where type is too long and difficult to trace.
auto l = [] (int x) -> bool { // l has the type of a lambda taking an int and returning a bool
You can now appreciate auto.
for(auto i:intervals) this is called range based for loop which is a new feature of C++ again.This is inspired by Java( for(int i:arr)), Python (for i in arr). Thus range based for loop feature was added in C++ 11.
Thus, for(auto i :intervals) simply means for(int i=0;i<interval.size();i++)
So now I think you can appreciate these new constructs and I would suggest to get acquianted with C++11.
Hope it helps.