简体   繁体   中英

Read data in a specific position in a std::vector<unsigned char>

I have an std::vector<unsigned char> with binary data in.

I just would like to simply read this vector, in a specific position with a specific size.

I would a function like this :

myvector.read(PositionBegin, Size)
myvector.read(1200,3)

This function could be read data from 1200 , to 1203 .

Is there a function like this in C++ ?

I'm assuming you want another std::vector with the range out...

This link provides a good answer: Best way to extract a subvector from a vector?

your function could look like:

std::vector<unsigned char> readFromVector(const std::vector<unsigned char> &myVec,
        unsigned start, unsigned len)
{
    // Replaced T with unsigned char (you could/should templatize...)
    std::vector<unsigned char>::const_iterator first = myVec.begin() + start;
    std::vector<unsigned char>::const_iterator last = first + len;
    std::vector<unsigned char> newVec(first, last);
    return newVec;
}

use appropriate tags for your questions.

a simple iterator thrue your vector:

for (i=0; i<myvector.size(); i++)
cout << " " << myvector.at(i);
cout << endl;

so if you wanted to use a range, you just need to set your for loop constraints

for (i=PositionBegin; i<PositionBegin+Size; i++)
cout << " " << myvector.at(i);
cout << endl;

If you want this function to output this to another vector, instead of using cout, you have to push it in a new vector.

mynewvector.push_back(myvector.at(i));

Don't forget that when you are making this function you have to make it with a type:

vector<type> function()

and at the end:

return mynewvector;

read up on vectors at : cplusplus

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