shortening of datatypes

i know it's possible, but i don't remember how.
for example you have a struct that contains another struct and that struct has a vector inside and so on, so you would need to write a lot of stuff each time you use a variable of the vector. but to shorten this you can define your own datatype/variable/namespace/..(i dont remember) and just use that instead.

hope you guys understand what i mean and can help me.
You can use typedef to define new types, which are basically new names for existing types.

So, for example, if you were using vectors of strings:

1
2
3
4
5
6
7
// Declare some vectors
std::vector<std::string> myStrings1;
std::vector<std::string> myStrings2;
std::vector<std::string> myStrings3;

// Declare a function that uses them
int Compare(const std::vector<std::string>& vector1, const std::vector<std::string>& vector2);


you could do:

1
2
3
4
5
6
7
8
9
10
// Define a new type with a helpful, descriptive name
typedef std::vector<std::string> StringVec;

// Declare some vectors
StringVec myStrings1;
StringVec myStrings2;
StringVec myStrings3;

// Declare a function that uses them
int Compare(const StringVec& vector1, const StringVec& vector2);
In C++11 it's also possible to use using to do the same thing.
using StringVec = std::vector<std::string>;
typedef is what i was searching, thanks guys
In C++11 it's also possible to use using to do the same thing.


Interesting. Not sure what the point of it is, though. Are there any differences between that and typedef?

Of course, I could stop being lazy and look it up myself :)
I don't think there is any difference in this case, but with using you can make use of template arguments which is not possible with typedef.

1
2
3
4
5
template <typename T>
using HomoPair = std::pair<T, T>;

HomoPair<int> intPair;
HomoPair<std::string> stringPair;
Last edited on
Ah, OK. That's handy!
Topic archived. No new replies allowed.