Skip to content

C++11 Learning Summary #14

@DaddyTrap

Description

@DaddyTrap

Chapter 1: auto

auto is not a new key word in C++, but in C++11 it has a new feature (and the feature in C++98 was disabled). Using auto, for example, auto i = 1, means we let the compiler judge the type of i. auto will be treated as int here. And you can write auto a = getX(), then you can easily get the X without thinking more about its type.
You can remember your code, but maybe you will forget others' code. So, it is convenient.

Somebody thinks it makes no sense to add this feature, but it is really a delicious sugar!(Syntactic sugar I mean)
For instance, please see the following code.

#include <iostream>
#include <vector>
#define CPP98
using std::cout;
using std::endl;
int main() {
  int arr[10] = {};
  for (int i = 0; i < 10; ++i) {
    arr[i] = i;
  }
  std::vector<int> v(arr, arr + 10);
#ifdef CPP98
  for (std::vector::iterator it = v.begin(); it != v.end(); ++it) {
    cout << *it << " ";
  }
  cout << endl;
#endif

#ifdef CPP11
  for (auto it = v.begin(); it != v.end(); ++it) {
    cout << *it << " ";
  }
  cout << endl;
#endif

  return 0;
}

At the first time I compile it, I got some compile errors, such as

main2.cpp:13:13: error: ‘template<class _Tp, class _Alloc> class std::vector’ used without template parameters
   for (std::vector::iterator it = v.begin(); it != v.end(); ++it) {
             ^
main2.cpp:13:30: error: expected ‘;’ before ‘it’
   for (std::vector::iterator it = v.begin(); it != v.end(); ++it) {
                              ^
main2.cpp:13:46: error: ‘it’ was not declared in this scope
   for (std::vector::iterator it = v.begin(); it != v.end(); ++it) {
                                              ^

Finally I found that I didn't give the template to vector. But if I use auto, it won't annoy me.
And when we use some libraries, for example, cocos2d-x. It use factory mode to produce instance, so auto is used generally.


The final and correct code:

#include <iostream>
#include <vector>
#define CPP11
using std::cout;
using std::endl;
int main() {
  int arr[10] = {};
  for (int i = 0; i < 10; ++i) {
    arr[i] = i;
  }
  std::vector<int> v(arr, arr + 10);
#ifdef CPP98
  for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
    cout << *it << " ";
  }
  cout << endl;
#endif

#ifdef CPP11
  for (auto it = v.begin(); it != v.end(); ++it) {
    cout << *it << " ";
  }
  cout << endl;
#endif

  return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions