13

I want to extract a range of elements from the beginning of a char array and put them into a string. The range may be less than or equal to the number of elements.

This is what I have come up with.

// buffer is a std::array<char, 128>

std::string message;

for (int i = 0; i < numberToExtract; ++i)
{
    message += buffer.at(i);
}

Is there a better way to do this?

I've been looking at something like std::string's iterator constructor. E.g. std::string(buffer.begin(), buffer.end()) but I don't want all the elements.

Thanks.

ksl
  • 4,519
  • 11
  • 65
  • 106
  • When working with the STL, it's often a good idea to question for loops that initialize objects. – Wolf Jan 30 '15 at 12:55
  • 1
    @Wolf [It's not the STL](http://stackoverflow.com/a/5205571/2069064). – Barry Jan 30 '15 at 12:59
  • @Barry I [see](https://en.wikipedia.org/wiki/C%2B%2B_Standard_Library). I reword it to *watch out for C++ Standard containers initialized with for loops*. – Wolf Jan 30 '15 at 13:06
  • @Wolf What do you mean? – ksl Jan 30 '15 at 13:22
  • I mean this pattern: `{1} container declaration (default construction) {2} for loop consisting in {3} append item to container`. Here `std::string` is the container: you want it *to contain* the extracted chars; done this way, you lose the option to make it const, because you have to declare it variable. I often look for alternatives of such undesirable side effects. – Wolf Jan 30 '15 at 13:37

3 Answers3

25

You don't have to go all the way to end:

std::string(buffer.begin(), buffer.begin() + numberToExtract)

or:

std::string(&buffer[0], &buffer[numberToExtract]);

or use the constructor that takes a pointer and a length:

std::string(&buffer[0], numberToExtract);
std::string(buffer.data(), numberToExtract);
Barry
  • 286,269
  • 29
  • 621
  • 977
2

You're close with your second example, you can do

std::string(buffer.begin(), buffer.begin() + numberToExtract)

This is using pointer arithmetic since array's use contiguous memory.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

Random access iterators let you do arithmetic operations:

std::string(buffer.begin(), buffer.begin() + numberToExtract);
jrok
  • 54,456
  • 9
  • 109
  • 141