【问题标题】:Finding size of the vector查找向量的大小
【发布时间】:2016-09-21 13:51:56
【问题描述】:

我正在尝试从文件中读取数字并取所有数字的平均值,但我不确定如何将 data.resize() 和 data.reserve() 部分包含到我的代码中。我必须使用调整大小和保留。当我将 current_size 或 max_size 设置为 data.size() 为 0。还有其他方法可以找到向量的大小吗?

//   1) Read in the size of the data to be read (use type size_t)
//   2) Use data.resize() to set the current size of the vector
//   3) Use a for loop to read in the specified number of values,
//      storing them into the vector using a subscript
void readWithResize(vector<int> &data) {
    cout << "Using resize!" << endl;

    if (cin){
        size_t current_size;
        current_size = data.size();
        //cin >> current_size;
        cout << "current_size = " << current_size << endl;
        data.resize(current_size);
        for (size_t i = 0; i < current_size; i++){
            cin >> data[i];
            data.push_back(data[i]);
            cout << data[i] << " ";
            cout << current_size << endl;
        }

    }

//   1) Read in the size of the data to be read (use type size_t)
//   2) Use data.reserve() to set the maximum size of the vector
//   3) Use a for loop to read in the specified number of values,
//      storing them into the vector using data.push_back()
void reserve(vector<int> &data) {

    cout << "Using reserve!" << endl;

    if (cin){
        size_t max_size;
        //max_size = 12;

        data.reserve(max_size);
        cout << "max_size = " << max_size << endl;

        for (size_t i = 0; i < max_size; i++){
            cin >> data[i];
            data.push_back(data[i]);
            cout << data[i] << " ";
        }

    }

【问题讨论】:

  • 你为什么要在这里使用reserve。就此而言,你为什么要使用向量呢?要获取一系列数字并找到它们的平均值,您需要 1. 一个累加器和 2. 一个计数器。
  • 您需要调整大小,而不是保留。 Reserve 不会调整大小,因此 data[I] 在您推送之前无效。您需要做的是调用 resize 然后删除带有 push_back 的行。
  • 我已经实现了一个函数resize,这是我必须编写的另一个函数。我是否将 max_size 设置为某个值?但我不认为我可以,因为我不知道文件中有多少个值。
  • 我回滚了你的编辑,因为它把问题变成了完全不同的东西。问一个新问题。

标签: c++ algorithm data-structures


【解决方案1】:

不要打扰resizereserve。将值读入int 类型的局部变量,然后使用data.push_back() 将其附加到向量中。向量将根据需要自行调整大小:

int value;
while (std::cin >> value)
    data.push_back(value);

这将正确处理任意数量的输入值。但是请参阅@WhozCraig 的评论——使用矢量对于上述问题来说太过分了。

【讨论】:

  • 有什么方法可以使用“resize”和“reserve”吗?
  • @bellaxnov - 前提是你知道你最终会得到多少元素。对于这段代码,你真的不需要它们中的任何一个。
  • 如果我要使用它们,我怎么知道有多少元素?
  • @bellaxnov - 你想用resizereserve 解决什么问题?如果不阅读文件,您无法知道它包含多少个元素。 vector 在内存扩展时可以很好地管理内存,如果您现在不提前知道您将拥有多少数据,这是您能做的最好的事情。
  • reserve 和 resize 到底有什么作用?有什么区别。
猜你喜欢
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多