简体   繁体   中英

push_back whole array wchar_t[n] to vector<wchar_t> efficiently

Why I use vector<wchar_t> instead of vector<array<wchar_t, n> > , if you are interested:

I want to store a lot of wchar_t arrays with different sizes together so that I can write it all to a file later after some encrypt/compress process.

I don't know how many arrays are there before I start, so I chose to use vector .

But these arrays are not the same size and I want them to be stored next to each other, so I can't use something like vector<array<wchar_t, n> > .


The only way I can think of doing this is push_back every wchar_t in every array one by one, and I think it is not efficient, because copy a string by yourself is always slower than strcpy , and every time I push_back it will check about capacity which is unnecessary in this case.

Is there any better solution?

I was hoping something like push_back(array_address, n) .

Considering a container src , and your vector of wchar_t use the insert method :

std::vector<wchar_t> dst;
dst.insert( end(dst), begin(src), end(src));

But there is no strong guarantee that it will optimize to a plain memcpy in case of a POD type or even a native type.

As I understand you need a vector of vectors of wchar_ts, but with the condition that vectors of wchar_ts are stored contiguously in base vector. Something like:

vector<vector<wchar_t>> v = {"string""value""list"};

The question is you need this for performance (means that that you can access each string separately, but they are in same space) or just need a contiguous array of strings to process it later?

If is the first then you need to make your own container that have these properties, if is the second then just append sequences to the vector, but if you want to use the memxxx functions then you may try this:

v.resize(v.size() + arr_sz);
std::copy_n(std::begin(sz), arr_sz, v.end() - arr_sz);

that is because (at least in VC++ 2013) copy_n uses memxxx on scalar types values:

template<class _InIt,
    class _Diff,
    class _OutIt> inline
    _OutIt _Copy_n(_InIt _First, _Diff _Count,
        _OutIt _Dest, _Scalar_ptr_iterator_tag)
    {   // copy [_First, _First + _Count) to [_Dest, ...), pointers to scalars
    _CSTD memmove(&*_Dest, &*_First,
        _Count * sizeof (*_First));
    return (_Dest + _Count);
    }

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