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.
6
  • 9
    You need a compile-time constant value. vector::size() is not compile time constant Commented Mar 12, 2018 at 11:48
  • 7
    Why do you want to do that? Commented Mar 12, 2018 at 11:48
  • 1
    It's not possible in standard C++. Just use A instead of myarray. Commented Mar 12, 2018 at 11:51
  • 1
    If you insist you can use non-standard C++ and use a gcc extension to make it compile. Commented Mar 12, 2018 at 11:52
  • 2
    You already have a vector. Why do you think you need an array? Commented Mar 12, 2018 at 11:54

1 Answer 1

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...)

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@刘宇哲 This is a hint to learn from a good c++ book instead
But you know my "wrong" code accepted by the OJ.WTF
"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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.