2016-09-21 122 views
-3

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

为什么要在这里首先使用'reserve'。就此而言,为什么要使用矢量呢?要获得一系列数字并找到他们的平均值,您需要1.累加器和2.计数器。 – WhozCraig

+1

您需要调整大小,而不是保留。保留区不会调整大小,因此数据[I]在您推送前无效。你需要做的是调用调整大小,然后用push_back删除行。 – Robinson

+0

我已经实现了一个函数调整大小,这是我必须编写的另一个函数。我是否将max_size设置为某个值?但我不认为我可以,因为我不知道文件中有多少个值。 – bellaxnov

回答

2

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

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

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

+0

有没有办法可以使用'resize'和'reserve'? – bellaxnov

+0

@bellaxnov - 只有当你知道你将要结束多少元素。对于这段代码,你真的不需要它们中的任何一个。 –

+0

如果我要使用它们,我将如何找到有多少元素? – bellaxnov