查找向量的大小

Posted

技术标签:

【中文标题】查找向量的大小【英文标题】: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 设置为某个值?但我不认为我可以,因为我不知道文件中有多少个值。 我回滚了你的编辑,因为它把问题变成了完全不同的东西。问一个新问题。 【参考方案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 到底有什么作用?有什么区别。

以上是关于查找向量的大小的主要内容,如果未能解决你的问题,请参考以下文章

查找两个不同长度的向量之间的所有组合

查找向量中小于阈值的所有数字(复杂度)

如何使用向量将多个字符串传递给函数

在向量 GENy 中配置闪存块表

在 C++ 中,如何获取指向向量的指针?

查找向量的向量的最大值/最小值