我读到了用C++获取数组的长度,你这样做:
int arr[17];
int arrSize = sizeof(arr) / sizeof(int);
Run Code Online (Sandbox Code Playgroud)
我试着为字符串做同样的事情:我在哪里
string * arr;
arr = new (nothrow) string [213561];
Run Code Online (Sandbox Code Playgroud)
然后我做
arr[k] = "stuff";
Run Code Online (Sandbox Code Playgroud)
我循环遍历每个索引并在其中放入"stuff".
现在我想要数组的大小应该是213561,这是正确的方法,为什么它在C++中如此复杂?
您尝试做的事情无法工作,因为sizeof在编译时对类型起作用(并且指针类型永远不会保持它们可能指向的数组的大小).
在你的情况下,计算sizeof(arr)返回指针所占用的内存大小,而不是
size of the array * size of a std::string
Run Code Online (Sandbox Code Playgroud)
我建议你使用这两个选项之一
......除非你有充分的理由不这样做.
在C++中执行此操作的正确方法是使用a vector.这样,您可以预先指定大小,也可以随意调整大小.
预先指定大小:
using namespace std;
vector<string> arr(213561);
for (vector<string>::iterator p = arr.begin(); p != arr.end(); ++p)
{
*p = "abc";
}
Run Code Online (Sandbox Code Playgroud)
随时扩展矢量:
using namespace std;
vector<string> arr; // <-- note, default constructor
for (int i = 0; i < 213561; ++i)
{
// add elements to the end of the array, automatically reallocating memory if necessary
arr.push_back("abc");
}
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,都可以找到数组的大小:
size_t elements = arr.size(); // = 213561
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11459 次 |
| 最近记录: |