找到矢量的大小

时间:2016-09-21 13:51:56

标签: c++ algorithm data-structures

我试图从文件中读取数字并获取所有数字的平均值,但我不确定如何将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] << " ";
        }

    }

1 个答案:

答案 0 :(得分:2)

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

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

这将正确处理任意数量的输入值。但请参阅@WhozCraig的评论 - 如上所述,使用向量对于问题是过度的。