简体   繁体   中英

Vector Initialization

I am working with C++ vectors that I faced with the following snippets code :

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    using MyVector = vector<int>;

    MyVector vectorA(1);
    cout << vectorA.size() << " " << vectorA[0] << endl;

    MyVector vectorB(1, 10);
    cout << vectorB.size() << " " << vectorB[0] << endl;

    MyVector vectorC{ 1, 10 , 100, 1000 };
    cout << vectorC.size() << " " << vectorC[3] << endl;
    return 0;
}

Why in this code vector object defined with using keyword? I can't understand why vector used in this code with this approach.

With using keyword you create alias MyVector for type vector<int> . You can read more about it here: http://en.cppreference.com/w/cpp/language/type_alias The effect is the same as with typedef vector<int> MyVector .

It can be annoying to continuously type out template arguments especially when they get really long. The using syntax is handy to keep things short and consistent without needing to type vector<...> everytime.

In this case, using A = B; , using allows you to substitute data type name A for data type name B in a more controlled manner than a macro definition and similar, if not identical to, a typedef .

The intent is to replace some arcane bit of wizardry with a term easier to convey and use. Here you're typically looking to improve one or both of clarity and brevity. You are trying to make something easier to read and easier to type.

The example of using MyVector = vector<int>; is almost meaningless. vector<int> is short and clear. You know exactly what vector<int> is at a glance, so no clarity benefit is gained.

Brevity is questionable. A whole three characters are saved. Over time this will add up, but I'm not sure it will match the time wasted by others looking up what a MyVector is. Fortunately modern IDEs are good at this for you so you don't waste time and hair looking for MyVector.h .

However for something like using CubeDataIterator = std::list<core::utils::DataRecord<UEI::Cube>>::iterator , is a kindness to the eyes. It is an iterator for Cube data, whatever the heck that is. But if you already know what a Cube is, you are rocking.

C++ keywords: using

Usage

  • using-directives for namespaces and using-declarations for namespace members
  • using-declarations for class members
  • type alias and alias template declaration (since C++11)

In your sample

using MyVector = vector<int>;

is identical to:

typedef  vector<int> MyVector;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM