简体   繁体   中英

C++ casting an array to a variably size vector

I would like to know if there is an easy solution for casting an array to a variably sized vector.

double CApp::GetTargetCost(const vector<unsigned char> &uHalfphoneFeatureVector_Bytes,const vector<unsigned char> &uTargetFeatureVector_Bytes)

I would like to pass

struct udtByteFeatures
{
    unsigned char Values[52];
};

to this function, but C++ does not like the fact that it has a fixed size. It expects a variably sized vector.

The error I am getting is

error C2664: 'CApp::GetTargetCost': Conversion of parameter 1 from 'unsigned char [52]' to 'const std::vector<_Ty> &' not possible

I am not sure yet whether I will use a fixed size later on or not, but currently I simply would like to stay flexible.

Thank you!

A conversion from an array to a std::vector is only possible if you know the size of the array. Note that sizeof works only if the size of the array is known at compile time, at least if you don't use C99 , so you cannot put this in a function. Namely, this won't work:

template <typename T>
  inline std::vector<T> ArrayToVec(const T* in) {
    return std::vector<T> (in, in + sizeof(in) / sizeof(T) );
  }

as sizeof(in) in this case will return the size of the pointer.

1) Reccomended way: convert your array to a std::vector when you call the function:

std::vector<unsigned char> (Value, Value + <number of elements in Value>)

I recommend that you put in some proper constant, maybe part of udtByteFeatures. By the way, defining a cast from udtByteFeatures to std::vector would be possible.

Source: What is the simplest way to convert array to vector?

2) Difficult and dangerous way: convert your array using a macro:

#define CharArrayToVec(in) (std::vector<char> (in, in + sizeof(in) / sizeof(*in) ) )

(too bad it cannot be templated on the type :) )

Edit:

(too bad it cannot be templated on the type :) )

Actually you could pass the type as an argument. If there were a typeof operator, you wouldn't even need that.

Values is not a vector. It's an array. It's not even remotely related to an object which is an instance of a class (which std::vector is). If you had searched Google for "initialize vector from array", you would have found out that the fact that arrays decay into pointers is very useful:

int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> v(a, a + 10);
for (std::vector<int>::iterator it = v.begin(); it != v.end(); it++)
    std::cout << *it << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM