5

I have the vector:

vector<int[2]> storeInventory; //storeInventory[INDEX#]{ITEMNUM, QUANTITY}

and I am wanting to use the push_back() method to add new arrays to the inventory vector. Something similar to this:

const int ORANGE = 100001;
const int GRAPE = 100002

storeInventory.push_back({GRAPE,24});
storeInventory.push_back{ORANGE, 30};

However, when I try using the syntax as I have above I get the error Error: excpeted an expression. Is what I am trying just not possible, or am I just going about it the wrong way?

Brook Julias
  • 2,085
  • 9
  • 29
  • 44

6 Answers6

6

Built-in arrays are not Assignable or CopyConstructible. This violates container element requirements (at least for C++03 and earlier). In other words, you can't have std::vector of int[2] elements. You have to wrap your array type to satisfy the above requirements.

As it has already been suggested, std::array in a perfect candidate for a wrapper type in C++11. Or you can just do

struct Int2 {
  int a[2];
};

and use std::vector<Int2>.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 2
    Technically, I think `vector storeInventory;` is valid in C++11 with the new fine-grained container requirements. The value type needs only be _destructible_, which an array type is. `push_back` requires that the value type is copy insertable, which an array type is not. A container of an array type is not very usable (or useful), and using a wrapper structure (like `std::array`) would be advisable. – James McNellis Nov 30 '12 at 19:37
3

I don't believe it's possible to pass arrays like that. Consider using std::array instead:

vector<std::array<int, 2> > storeInventory; 
storeInventory.push_back({{GRAPE,24}});
Pubby
  • 51,882
  • 13
  • 139
  • 180
3

If it's only vector of int[2] you could use:

std::vector<std::pair<int, int>> vec

Adding elements:

int a, b;
vec.push_back(std::make_pair(a, b));
2
storeInventory.push_back({GRAPE, 24});
storeInventory.push_back({ORANGE, 30}); 

You can try this. I think you forgot parentheses.

David G
  • 94,763
  • 41
  • 167
  • 253
2

C-style arrays are not copyable, so can't be used as the element type in a std::vector.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

Simply use a std::vector<int *> :)

Klauz
  • 1
  • This answer could be improved if it made more of an effort to explain to the asker why this solution would work and how they should apply it. – nhgrif May 22 '15 at 22:43