Reputation: 180
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.
Upvotes: 2
Views: 144
Reputation: 33931
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.
Upvotes: 1
Reputation: 57
C++ keywords: using
Usage
In your sample
using MyVector = vector<int>;
is identical to:
typedef vector<int> MyVector;
Upvotes: 0
Reputation: 1515
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
.
Upvotes: 4
Reputation: 11113
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.
Upvotes: 2