C++ Push Multiple Types Onto Vector

C++ Push Multiple Types onto Vector

In order to do that, you'll definitely need a wrapper class to somehow conceal the type information of your objects from the vector.

It's probably also good to have this class throw an exception when you try to get Type-A back when you have previously stored a Type-B into it.

Here is part of the Holder class from one of my projects. You can probably start from here.

Note: due to the use of unrestricted unions, this only works in C++11. More information about this can be found here: What are Unrestricted Unions proposed in C++11?

class Holder {
public:
enum Type {
BOOL,
INT,
STRING,
// Other types you want to store into vector.
};

template<typename T>
Holder (Type type, T val);

~Holder () {
// You want to properly destroy
// union members below that have non-trivial constructors
}

operator bool () const {
if (type_ != BOOL) {
throw SomeException();
}
return impl_.bool_;
}
// Do the same for other operators
// Or maybe use templates?

private:
union Impl {
bool bool_;
int int_;
string string_;

Impl() { new(&string_) string; }
} impl_;

Type type_;

// Other stuff.
};

push back multiple types of data in a vector in c++

In C++14:

struct DistanceBetweenPoints
{
double distance = {};
size_t p1 = {};
size_t p2 = {};
};

std::vector<DistanceBetweenPoints> foo;
foo.push_back({ 70.54, 0, 1 });
//...

EDIT

Just like Khouri Giordano noted in the comments section, this isn't supported in C++11 because when using in-class initialization, it becomes a non-POD type and you lose aggregate construction. See his answer for C++11 compatible solutions.

How to push data of different data types into a vector by reading from a file?

%d is for integers. Change it to %lf for double, and change other parts accordingly, for example, change ivalue to double.


According to your comment in the question, I think you might need something like


while(fscanf(fp,"%s", str)!=EOF)
{
char* pch = strtok(str, ",");
pch = strtok(NULL, ","); // skip first
while (pch != NULL)
{
double d = atof(pch);
printf("Counter-%d\n",counter++);
srcdata.push_back(d);
pch = strtok (NULL, ",");
}
}

How do I pass multiple ints into a vector at once?

Try pass array to vector:

int arr[] = {2,5,8,11,14};
std::vector<int> TestVector(arr, arr+5);

You could always call std::vector::assign to assign array to vector, call std::vector::insert to add multiple arrays.

If you use C++11, you can try:

std::vector<int> v{2,5,8,11,14};

Or

 std::vector<int> v = {2,5,8,11,14};

What is wrong with using struct for pushing multiple types in std::vector?

Specific answer in comments: then you could template it to the types using std::tuple instead of std::pair, as std::vector<std::tuple<type1, type2,.. typen>> m_types


It is a good idea, although you are not profiting from polymorphism. I understand you cannot change type1 and type2 classes, but you can wrap a class around them that suits your need:

(not tested)

class TypeWrap
{
public:
virtual void execute() = 0;
};

class Type1Wrap : public TypeWrap
{
private:
Type1 m_type;
public:
void execute(){ m_type.execute(); }
};

class Type2Wrap : public TypeWrap
{
private:
Type2 m_type;
public:
void execute(){ m_type.execute(); }
};

And then use a vector<TypeWrap*> m_types which will allow you to call m_types[0]->execute();

As a side note its bad practice (in a general sense) to use new operators directly, other options such as unique_ptr or shared_ptr are better if you need to allocate dynamically, or simply use Type1Wrap type; m_types.push_back(&type); to get a pointer to the object, but make sure to keep the object alive!

Add multiple values to a vector

You can just make an operator:

template <class T>
std::vector<T>& operator+=(std::vector<T>& lhs, std::initializer_list<T> l)
{
lhs.insert(std::end(lhs), l);
return lhs;
}

Append different types of data to a vector of bytes

If BYTE is an alias for char, signed char, unsigned char or std::byte, you can reinterpret_cast pointers to objects to pointers to BYTE, and use the InputIt overload of vector::insert.

This is only sensible if all your data are of trivial types.

std::vector<BYTE> PackedData()
{
std::vector<BYTE> packed_data;

// Here I have initialized the header with two byte
packed_data.insert(packed_data.end(), m_header.begin(), m_header.end());

// I specified encoding of the packet
packed_data.insert(packed_data.end(), reinterpret_cast<BYTE*>(&m_messageEncoding), reinterpret_cast<BYTE*>(&m_messageEncoding + 1));

// I specified message type
packed_data.insert(packed_data.end(), reinterpret_cast<BYTE*>(&m_messageType), reinterpret_cast<BYTE*>(&m_messageType + 1));

// I specified size of payload should send to the server
packed_data.insert(packed_data.end(), reinterpret_cast<BYTE*>(&m_messageSize), reinterpret_cast<BYTE*>(&m_messageSize + 1));

// I specified payload itself must send to the server
packed_data.insert(packed_data.end(), m_payload.begin(), m_payload.end());

// I specified footer
packed_data.insert(packed_data.end(), m_footer.begin(), m_footer.end());

return packed_data;
}


Related Topics



Leave a reply



Submit