The keyword auto comes from the C ++ 98 standard. In C ++ 98, it does not play any role. In C ++ 0x, "borrow" it as an automatic type deduction (automatic type deduction ). When auto appears in the declaration, it indicates "Please use initializing my expression type as my type ". For example, the following code:
C:/temp> type autocat. cpp
# Include
# Include
# Include
# Include
# Include
Using
Namespace STD;
Using
Namespace STD: tr1;
Int main (){
Map m;
Const RegEx R ("(// W
+) (// W +)
");
For (string s; Getline (CIN, S );){
Smatch results;
If (regex_match (S, results, R )){
M [Results [1] = Results [2];
}
}
For (Auto
I = M. Begin (); I! = M. End (); ++ I ){
Cout <I-> second <"are" <I-> first <Endl;
}
}
Running result:
Cute kittens
Uugly puppies
Edevil gobloud
^ Z
Kittens are cute
Gobvil are edevil
Puppies are uugly
In the above example, the I type is deduced as map: iterator during compilation. With the auto keyword, you no longer need to write long and annoying code.
(Note that M. the begin () return type is iterator, not const_iterator, because M is not Const. the cbegin () in C ++ 0x can solve this problem. It returns the const iterator of the non-const container .)
Lambda expressions and auto
As mentioned in the previous article, tr1: functions is used to store lambda expressions. However, we do not recommend that you do this unless you have to because of the overhead of tr1: functions.
If you need to reuse a Lambda expression or give it a name, auto is a better choice.
C:/temp> type autolambdakitty. cpp
# Include
# Include
# Include
# Include
Using namespace STD;
Template void keep_if (vector & V, predicate Pred ){
Auto notpred = [&] (const T & T ){
Return! PRED (t );
};
V. Erase (remove_if (V. Begin (), V. End (),Notpred
), V. End ());
}
Template void print (const container & C ){
For_each (C. Begin (), C. End (), [] (const typename container: value_type & E) {cout <e <"";});
Cout <Endl;
}
Int main (){
Vector;
For (INT I = 0; I <100; ++ I ){
A. push_back (I );
}
Vector B;
For (INT I = 100; I <200; ++ I ){
B. push_back (I );
}
Auto prime = [] (const int N)-> bool {
If (n <2 ){
Return false;
}
For (INT I = 2; I <= N/I; ++ I ){
If (N % I = 0 ){
Return false;
}
}
Return true;
};
Keep_if (,Prime
);
Keep_if (B,Prime
);
Print ();
Print (B );
}
Running result:
2 3 5 7 11 13 17 19 23 29 31 37 43 47 53 59 61 67 71 73 79 83 89 97
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
In the code above, notpred is the negative expression of a Lambda expression. In this example, we cannot use not1 () of C ++ 98, because not1 requires that your predicate be derived from unary_function, but Lambda does not require this, therefore, lambda is more flexible in many cases.