0

I have a problem with push_back, it doesn't work with my code :(

    const int DIM = 10;
    vector<char[DIM]> categorie;

    int function_1(char cat[DIM]){
       categorie.push_back(cat);
       return 0;
    }

how can I resolve?

Thanks!

PS: I'm using Eclipse CDT

user3319149
  • 11
  • 1
  • 1
  • 1
    Resolve what? What is the problem that you have? How does the `push_back` not work? Please, add more info to your question. Do you have a compile error? Runtime crash? Unexpected results? – eerorika Feb 17 '14 at 12:44
  • 1
    use `std::array` if possible. – Jarod42 Feb 17 '14 at 12:47
  • This question is very clear, no additional info is necessary. In the code it shows a common misunderstanding among novices. People familiar with c++ can see the problem at first glance. Maybe this qustion phrasing sound silly, but https://stackoverflow.com/q/2392308 is even sillier still get 23 upvote. That question should be marked dup, for this question be canonical. @eerorika – 把友情留在无盐 Feb 08 '19 at 16:48

3 Answers3

3

This won't work. std::vector<T> requires T to be copyable or movable. A plain array is neither. Note that inside function_1, cat is a pointer to char, not an array of char.

If you have C++11, use std::array:

const int DIM = 10;
vector<array<char, DIM>> categorie;

int function_1(array<char, DIM> cat){
   categorie.push_back(cat);
   return 0;
}

If you don't have that, you'll have to wrap the array in a class and use that instead. Of course, Boost.Array can do that for you.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • 1
    This may be expensive since std::array is not movable so you will get two copy operations in some cases. Probably it is better to pass the array by const ref to `function_1`. – TNA Feb 17 '14 at 12:55
1

For historical reasons, built-in arrays are rather odd creatures that can't be copied, assigned or passed by value; this makes it rather awkward to keep them in a container. Despite appearances, your function's parameter is actually a pointer, char *, so does not match the type expected by push_back. Even if you had an actual array, push_back wouldn't work, since it requires a copyable type.

If you're using C++11, then std::array<char, DIM> would be more convenient. Otherwise, you could wrap the array in a little class and store that.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

1.

int function_1(char cat[DIM]); is not what you think. it decays to int function_1(char* cat); The correct syntax is int function_1(char (&cat)[DIM]);

2.

C-array are not copyable/moveable and std::vector requires at least one.

3.

You best option is to use std::vector<std::array<char, Dim>>.

Jarod42
  • 203,559
  • 14
  • 181
  • 302