2014-05-19 51 views
0

我需要计算存储在一个文本文件中的阵列,如逆转的次数:(C++)从文本文件计数数组中的反转,每行一个数组?

1 4 5 3 2 
2 1 4 3 
6 2 4 1 3 5 

我已经写了两个函数来计算的倒置,但他们采取数组作为参数,就像这样:

int merge_sort(int array[], int inferior_limit, int superior_limit) 

我现在的问题是如何读取一次一行的文本文件,并将每行存储到数组中以计算倒数。我想过使用二维数组,但每列的列数都不相同。我一直在使用getline,如也被认为是:

while(std::getline(inFile,numbers)) 

不过,我不知道如何处理,使其不读所有的数字跟随它。任何帮助将不胜感激。

+2

难道你用C风格的数组的要求?毕竟你是用C++编程的,为什么不用'std :: vector'等等? – Rook

+0

你的问题不是很好,你问的是倒数,你显然知道该怎么做。你应该有(不)要求是从文件中读取行。我在说(不),因为那可能很快就会成为一个重复的问题。 –

回答

2

您可以使用sstream从字符串

#include <sstream> 

while(std::getline(inFile,numbers)) { 
    std::vector<int> arr; 
    std::stringstream ss(numbers); 
    int temp; 
    while(ss >> temp) arr.push_back(temp); 
    // First argument of merge_sort would be &arr[0] 
    // size of array would be arr.size(); 
} 
0

这里读阵列是一个例子分配如何做。您可以使用代码背后的想法。

#include <iostream> 
#include <sstream> 
#include <vector> 
#include <string> 
#include <numeric> 
#include <iterator> 
#include <functional> 

int main() 
{ 
    std::string record; 

    while (std::getline(std::cin, record)) 
    { 
     std::istringstream is(record); 
     std::vector<int> v((std::istream_iterator<int>(is)), 
          std::istream_iterator<int>()); 

     if (v.empty()) continue;      

     bool increase = true; 

     auto n = std::inner_product(std::next(std::begin(v)), std::end(v), 
            std::begin(v), size_t(0), 
            std::plus<size_t>(), 
            [&] (int x, int y) -> size_t 
            { 
             bool current = increase; 
             return ((increase = x >= y)^current); 
            }); 

     std::cout << n << std::endl; 
    } 

    return 0; 
} 

如果文件中包含的记录

1 4 5 3 2 
2 1 4 3 
6 2 4 1 3 5 

那么输出将是

1 
3 
4 
相关问题