简体   繁体   English

C ++中的数组初始化

[英]Array initialization in c++

I'm new to C++, and I want to know if this valid. 我是C ++的新手,我想知道这是否有效。

So I want to create an array of strings, but I wont know the size of the array I need until a value is passed in to a function within the class I'm working in. So, can I do this: 因此,我想创建一个字符串数组,但是在将值传递给正在使用的类中的函数之前,我不知道需要的数组大小。因此,我可以这样做:

string sList[];

void init(unsigned int size=1)
{
    sList = new string[size];

 }

I'm sorry if this is a dumb question, but I'm a Java guy new to C++. 如果这是一个愚蠢的问题,我感到抱歉,但是我是C ++的Java新手。

EDIT: This is an assignment that involves me writing an array wrapper class. 编辑:这是一项涉及我编写数组包装器类的任务。 If I could use vector<>, trust me, I would. 如果我可以使用vector <>,请相信我。

This is correct, although string sList[] should be string *sList . 这是正确的,尽管string sList[]应该是string *sList Don't forget the delete [] sList at the end. 不要忘记最后的delete [] sList

As many others say, you can use std::vector if you want, but getting some practice with arrays is an excellent way to learn how the memory management works and I encourage you to explore it further. 就像许多其他人所说的那样,您可以根据需要使用std::vector ,但是对数组进行一些练习是了解内存管理如何工作的绝佳方法,我鼓励您进一步探索它。

A new-expression (such as new string[size] ) returns a pointer to a dynamically allocated object. new表达式 (例如new string[size] )返回一个指向动态分配对象的指针。 In this case, it returns a pointer to the first string object in the dynamically allocated array. 在这种情况下,它返回一个指向动态分配数组中第一个string对象的指针。 So to make this work, sList should be a pointer: 因此,要使其工作, sList应该是一个指针:

string* sList;

It is important to remember that you must always delete / delete[] and object that has been created with new / new[] . 重要的是要记住,必须始终delete / delete[]和使用new / new[]创建的对象。 So you must at some point delete[] sList . 因此,您必须在某些时候delete[] sList If you don't do this, the memory allocated for the array of string s will “never” be deallocated. 如果不这样做,分配给string s的内存将“从不”释放。

However, you'll be in a much better situation if you use a std::vector<std::string> instead, rather than doing your own dynamic allocation. 但是,如果您使用std::vector<std::string>而不是自己进行动态分配,则情况会更好。

The right way to do this in C++: 在C ++中执行此操作的正确方法:

#include <string>
#include <vector>

std::vector<std::string> sList;

void init(unsigned int size = 1)
{
    sList.resize(size);
}

int main()
{
    init(25);
}

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

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