简体   繁体   English

arrays c++ 的指针与向量

[英]Pointers vs vectors for arrays c++

In the case I am creating an 'array' on stack in c++, is it better to initialise an empty vector with a reserved number of elements and then pass this to a function like foo() as a reference as below.如果我在 c++ 的堆栈上创建一个“数组”,最好用保留数量的元素初始化一个空向量,然后将其传递给一个 function,如foo()作为参考,如下所示。 Or is it better to set an array arrb of size nelems , then using a pointer p_arrb to the address of the first element increment the pointer and assign some value?或者最好设置一个大小为nelems的数组arrb ,然后使用指向第一个元素地址的指针p_arrb递增指针并分配一些值?

#include <iostream>
#include <vector>
 
void foo(std::vector<int>& arr){
    int nelems = arr.capacity();    
    
    for (int i = 0; i < nelems; i++){
        arr[i] = i;
    }

}


int main()
{
    
    int nelems; 
    std::cout << "Type a number: "; // Type a number and press enter
    std::cin >> nelems; 

    std::vector<int> arr;
    arr.reserve(nelems); // Init std lib vector
    foo(arr);
    
    int arrb[nelems];
    int* p_arrb = &(arrb[0]);  // pointer to arrb
    
    for (int i = 0; i < nelems; i ++){
        *(p_arrb++) = i;  // populate using pointer
    }
    p_arrb -= nelems; // decrement pointer

    return 0;
}

It seems people prefer the use of vector as it is standardised and easier to read?似乎人们更喜欢使用矢量,因为它是标准化的且更易于阅读? Apart from that, is there any performance benefit to using vector instead of a basic pointer in this case where I do not need to change the size of my vector/array at any point in the code?除此之外,在这种情况下,我不需要在代码中的任何位置更改向量/数组的大小,使用向量而不是基本指针是否有任何性能优势?

What you should use depends on the exact goal you have.您应该使用什么取决于您的确切目标。 In general the best approach is to avoid using "raw arrays" (both dynamic and static) wherever possible.一般来说,最好的方法是尽可能避免使用“原始数组”(动态和静态)。

If you need dynamic array, use std::vector .如果您需要动态数组,请使用std::vector If you need static array, use std::array .如果您需要 static 数组,请使用std::array

You can't use the arrb variant because the size of an array must be a compile-time constant in C++, but you are trying to use a runtime size here.您不能使用arrb变体,因为数组的大小必须是 C++ 中的编译时常量,但您在此处尝试使用运行时大小。

If your compiler is compiling this, then it is doing so only because it supports these so-called variable-length arrays as a non-standard extension.如果您的编译器正在编译它,那么它这样做只是因为它支持这些所谓的变长 arrays作为非标准扩展。 Other compilers will not support them or have differing degree of support or behavior.其他编译器将不支持它们或具有不同程度的支持或行为。 These arrays are optionally-supported in C, but even there they are probably not worth the trouble they cause.这些 arrays 在 C 中是可选支持的,但即使在那里,它们也可能不值得它们造成的麻烦。

There is no way to allocate a runtime-dependent amount of memory on the stack in C++ (except if you misuse recursive function calls to simulate it).无法在 C++ 的堆栈上分配与运行时相关的 memory 数量(除非您滥用递归 function 调用来模拟它)。

So yes, you should use the vector approach.所以是的,你应该使用vector方法。 But as discussed in the comments under the question, what you are doing is wrong and causes undefined behavior.但是正如问题下的评论中所讨论的那样,您所做的事情是错误的并导致未定义的行为。 You need to either reserve memory and then emplace_back / push_back elements into the vector or you need to resize the vector to the expected size and then you may index it directly.您需要reserve memory 然后将emplace_back / push_back元素保留到向量中,或者您需要将向量resize为预期大小,然后您可以直接对其进行索引。 Indexing a vector outside the the range of elements already created in it causes undefined behavior.对超出其中已创建元素范围的向量进行索引会导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM