0

I want to write a function to create an array with a viewed vector. Such as

int foo(vector<int> &A){
    int N=A.size();
    int myarray[N]={0}; //here is an error
}

Here are my questions:

  1. I know to build an array must use const value but vector::size() isn't return a const value?
  2. using const modify the expression doesn't work N still a variable.
bolov
  • 72,283
  • 15
  • 145
  • 224
Jack Liu
  • 13
  • 3

1 Answers1

2

I don't see why you ever should need to create an array. If you pass arrays anywhere into a function, you pass a pointer to such an array. But you easily can get the vector's internal data as such a pointer:

std::vector<int> v({1, 2, 3, 4});
int* values = v.data();

Done, you have your "array", and you don't even have to copy the data...

If you still need a copy, just copy the vector itself.

Side-note: The vector's content is guaranteed by the standard to be contiguous, so you won't get into any trouble iterating over your "arrays".

However, one problem actually exists: If you want to store pointers to the contents of your array, they might get invalidated if you add further elements into your vector, as it might re-allocate its contents. Be aware of that! (Actually, the same just as if you need to create a new array for any reason...)

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • Thanks for your answer.Acctually i am learning algorithm in LeetCode.What i must do is using an array to store the element of the vector.but i don`t want to create another vector and just a similar array instead.So the situation is that and i met an error. – Jack Liu Mar 12 '18 at 12:52
  • @刘宇哲 This is a hint to learn from a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) instead – Passer By Mar 12 '18 at 13:00
  • But you know my "wrong" code accepted by the OJ.WTF – Jack Liu Mar 12 '18 at 13:05
  • "Wrong" - better let's call it "non-standard" - code accepted? Well, there are compilers out there supporting VLA (variable length arrays) as an extension to standard C++. If answers are checked (note: I don't say this is a good idea!) by just letting them be compiled with one of these... Side note: It is not *always* evil to rely on such compiler extensions, however, in *any* of these cases you have to be aware that you are writing *non-portable* code! If you *can*, avoid it! – Aconcagua Mar 12 '18 at 14:12