0

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++ ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • I don't think vector is really the structure you want to be using for this task. Take a look through this [STL reference](http://www.cplusplus.com/reference/) and see is there's something that might better suit your needs. – jpm Apr 01 '12 at 10:38

2 Answers2

2

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;
}
Community
  • 1
  • 1
starruler
  • 302
  • 2
  • 10
0

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

Rps
  • 277
  • 1
  • 5
  • 25