Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify the type of a vector with a string

Tags:

c++

types

vector

How do you specify a type with a string? I mean:

string s = "int";
Vector<s> vec;

And I want vec to be vector<int>. Is this possible?

I want to make a class where the user can type in a string and a vector with that type will be created.

like image 511
shizzle Avatar asked Dec 20 '11 18:12

shizzle


People also ask

How do you define a string vector?

A vector of strings is created the way a vector of any other type would be created. Remember to make the template specialization, string. Do not forget to include the string library and the vector library. The common ways of creating vectors with string as the element type have been illustrated above.

How do you determine a vector type?

Given a vector, you can determine its type with typeof() , or check if it's a specific type with an “is” function: is. character() , is.

Can you have a vector of strings in C++?

Using C++ STL Container - Vector Thus, C++ Vectors can be used to create a string array and manipulate the same easily. The vector. push_back(element) method is used to add elements to the vector string array.


2 Answers

Not possible in C++, atleast not the way you want.

Templates are a compile time concept, while user input is a runtime concept. Completely different, not mixable.

To make that work, you need a dynamically typed language, which C++ is not. It's statically typed.

like image 174
Xeo Avatar answered Sep 30 '22 08:09

Xeo


Is this possible?

This is not possible in C++. If using boost is an option, consider creating a vector of boost::variant objects instead: this way, your statically-typed vector would be prepared to accept elements of different types.

like image 31
Sergey Kalinichenko Avatar answered Sep 30 '22 08:09

Sergey Kalinichenko