Use the auto keyword in C++ STL

后端 未结 6 1698
野趣味
野趣味 2020-12-23 00:10

I have seen code which use vector,

vectors;
s.push_back(11);
s.push_back(22);
s.push_back(33);
s.push_back(55);
for (vector::iterator i         


        
6条回答
  •  半阙折子戏
    2020-12-23 00:36

    The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization.

    Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.

    #include 
    #include 
    using namespace std;
    
    int main()
    {
        vectors;
        s.push_back(11);
        s.push_back(22);
        s.push_back(33);
        s.push_back(55);
        for (int it=s.begin();it!=s.end();it++){
            cout<<*it< > >, __gnu_debug_def::vector > >' to 'int' in initialization
    

    The auto keyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!

提交回复
热议问题