Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a vector type of which will be determined at runtime. So how can I implement this?

I did some work on it. But it is not pretty and optimal.

Thank u in advance for any help.


What I have tried:

#include <iostream>
#include <vector>
#include <typeinfo>
#include <variant>

template <typename T>
void fillVector(std::vector<T>& vector)
{
	// fill vector with values
}

struct A
{
	std::vector<std::variant<int, float, short>> values;
};

int main()
{
	A data;
	int type;
	std::cin >> type;

	if (type == 0) // int
	{
		std::vector<int> intValues;
		fillVector(intValues);
		for (const auto& value : intValues) 
		{
			data.values.push_back(value);
		}
	}
	else if (type == 1) // short
	{
		std::vector<short> shortValues;
		fillVector(shortValues);
		for (const auto& value : shortValues)
		{
			data.values.push_back(value);
		}
	}
	else // float
	{
		std::vector<float> floatValues;
		fillVector(floatValues);
		for (const auto& value : floatValues)
		{
			data.values.push_back(value);
		}
	}

	return 0;
}
Posted
Updated 28-May-23 9:33am
Comments
Member 15627495 28-May-23 10:21am    
by an overload :
void fillVector(std::vector<T1>& vector)
{
	// fill vector with values
}
void fillVector(std::vector<T2>& vector)
{
	// fill vector with values
}
void fillVector(std::vector<T3>& vector)
{
	// fill vector with values
}



bartello 28-May-23 11:15am    
Thank u! But It's not what I need.
0x01AA 28-May-23 11:17am    
Ok, we see what you tried. Now the questions:
a.) What part you are not happy about
b.) What you expect?
bartello 28-May-23 11:24am    
Each time I create a new vector, and then I copy this vector into the one I need. Instead of this, I would like to just add values to the vector (don't care what type they are).
I'm parsing a file where the data type is written from the very beginning. Then I read the rest of the file (data which type is on the first line). So, ideally, I would like to have a vector where I would add the data without caring what type they are.
0x01AA 28-May-23 11:25am    
Maybe a read of this will help: Run-time type information - Wikipedia[^]

1 solution

Use std::any as a vector template parameter and you all set.

So it should look like
C++
std::vector<std::any> myVecOfAnyValues;


std::any - cppreference.com[^]
 
Share this answer
 
Comments
bartello 28-May-23 16:04pm    
Thank u! About "any" k5054 already said. I've tried it and everything looks OK!
CPallini 29-May-23 4:00am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900