0

I want this kind of interface

#include <vector>
void fun(std::vector<int> v){ }
int main(){
  fun({1, 2, 3, 4}); //<-- this type of invocation
}

instead of

void fun(int argc, int* args){ }
int main(){
   int a[]={1,2,3,4};
   fun(sizeof(a)/sizeof(int), a);
}

Can I make the vector go to the stack (or use something that behaves like an on-the-stack vector)?

(std::array appears to do the stack part, but it requires an explicit hardcoded size, and I don't want that.)

It's a premature optimization type of question, really, but I'm curious.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 1
    Any reason (other than curiosity) why you explicitly want to use the limited stack? – deviantfan Nov 29 '15 at 13:13
  • 1
    "It's a premature optimization type of question" - yes, it is. There is no trivial way to achieve this with variable length. It has been asked before tho'. I'll try to mark this as a dublicate. – Mats Petersson Nov 29 '15 at 13:15
  • http://stackoverflow.com/questions/26346688/how-to-initialize-vector-from-array-without-allocating-more-storage-space or http://stackoverflow.com/questions/354442/looking-for-c-stl-like-vector-class-but-using-stack-storage – Mats Petersson Nov 29 '15 at 13:21
  • 1
    Did I misunderstand, what you have already works. – Galik Nov 29 '15 at 13:22
  • You might consider to implement your own allocator for the vector in order to avoid the free store maybe. Otherwise I don't see how. @Galik It works, but uses the heap. The OP wants to be *on stack*. – Ely Nov 29 '15 at 13:22
  • See [Boost.Container](http://www.boost.org/libs/container/)'s [`static_vector`](http://www.boost.org/doc/libs/release/doc/html/container/non_standard_containers.html#container.non_standard_containers.static_vector) and [`small_vector`](http://www.boost.org/doc/libs/release/doc/html/container/non_standard_containers.html#container.non_standard_containers.small_vector). – ildjarn Jan 02 '16 at 02:25

1 Answers1

0

A std::vector uses the heap to store its elements, so you cannot use it if you need your elements to be on the stack.

You can use a std::array or the raw array T[] to keep the elements on the stack. Using templates you can get rid of the length parameter in the interface:

template<int size>
void func(int(&)[size]) { 
    // Code 
}

int main() {
    int a[] = { 1,2,3,4 };
    func(a);
}
José D.
  • 4,175
  • 7
  • 28
  • 47