【问题标题】:how to allocate memory for a type when we don't know the size of it? [duplicate]当我们不知道它的大小时,如何为类型分配内存? [复制]
【发布时间】:2018-04-01 06:28:00
【问题描述】:

只是一个简单的问题。 我想接收一些整数并将其放入一个数组中,但我不知道它的大小,因为它是由用户给出的 输入预计为:1 2 3 4 5

#include <iostream>
using namespace std;
int main()
{
    int *contain;
    int y;
    int i=0;
    char c;

    while(true)
    {
        cin>>contain[i];
        i++;
        c=getchar();
        if(c=='\n')
        break;
    }
}

【问题讨论】:

  • 如果用户输入一个大小,您可以分配该数字。让它变得简单并使用std::vector
  • 将它们读入一个随着您添加项目而增长的容器。例如标准::向量。这样你就不需要事先知道你会读多少。
  • 这应该是数据结构问题,所以不能分配多余的空间。
  • 没有用户给出的尺寸。
  • 我对矢量有点陌生,但我知道你应该给它大小

标签: c++ arrays io


【解决方案1】:

使用std::vector

让您入门的演示示例,它将读取数字并将它们存储到向量中,直到读取 0(它也将存储在向量中):

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  int myint;

  std::cout << "Please enter some integers (enter 0 to end):\n";

  do {
    std::cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";

  return 0;
}

输出:

Please enter some integers (enter 0 to end):
1 2 3 4 5 0
myvector stores 6 numbers.

在您拥有的类 C 代码中,例如,您需要使用 realloc(),并在每次有新数字到达时将大小增加 1(非常低效)。

【讨论】:

  • 数组的调整大小操作通常以增量方式进行,而不仅仅是 1 比 1,以避免进行过多的调整大小。 #随机提示
  • @alseether 这就是为什么我说这会非常低效。实际上,每次需要重新分配时,您都会将大小翻倍。
  • 所以你的意思是它就像摊销分配
  • @Nznin 你的意思是在向量中? vector 是一个 C++ 容器,它在后台(自动)处理容器的大小。
  • 查看另一个答案@Nznin,我只是举了一个示范性的例子让你开始。
【解决方案2】:

std::vectorstd::istream_iterator 一起使用。这样你就不需要事先知道尺寸了。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;

int main() {
    // Input
    vector<int> data(istream_iterator<int>(cin), {});

    // Output
    for (auto i : data)
        cout << i << endl;

    // Output 2: suggested by alfC
    copy(data.begin(), data.end(), ostream_iterator<int>(cout, " "));
    return 0;
}

输入

1 2 3 4 5

输出

1
2
3
4
5
1 2 3 4 5

查看它在 Ideone

的工作

【讨论】:

  • 那是一个更好的答案,Nzim 接受这个答案。
  • 这么酷的答案应该以std::copy(data.begin(), data.end(), std::ostream_iterator&lt;int&gt;(cout, " "));而不是循环结尾。
  • 感谢您的帮助,但我得看看它是什么,因为我是 vector 和 istream_iterator 的新手
  • @Nznin 阅读 en.cppreference.com
猜你喜欢
  • 2023-03-13
  • 2013-03-14
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2018-03-05
  • 2018-06-19
相关资源
最近更新 更多