2013-10-19 25 views
0

我在Cpp寫了一個簡單的程序,但我不知道什麼是測試這個最好的方法?單元測試有像Java一樣的特定格式嗎?如何測試簡單的Cpp文件?

#include <iostream> 
#include <sstream> 
#include <string> 
#include <algorithm> 
#include <vector> 

using namespace std; 
static vector<int> getAllFlipLocations(
     vector<int> & pancakesRepresentedByDiameter); 

/** 
* Problem statement can be viewed at: 
* http://www.programming-challenges.com/pg.php?page=downloadproblem&probid=110402&format=html 
* 
* The following is a solution for the above problem. 
* 
* @author Quinn Liu ([email protected]) 
*/ 
int main(void) { 
    string stackOfPancakes; 

    while (getline(cin, stackOfPancakes)) { 
     istringstream is(stackOfPancakes); 

     vector<int> pancakesRepresentedByDiameter; 

     int diameterOfPancake; 
     while (is >> diameterOfPancake) { 
      pancakesRepresentedByDiameter.push_back(diameterOfPancake); 
     } 
     reverse(pancakesRepresentedByDiameter.begin(), 
       pancakesRepresentedByDiameter.end()); 

     vector<int> orderOfFlipLocations = getAllFlipLocations(
       pancakesRepresentedByDiameter); 

     // first print original stack of pancakes 
     cout << stackOfPancakes << endl; 

     // now print location within stack to flip pancakes to get a stack 
     // of pancakes where the pancake diameters decrease as they move 
     // from the bottom to the top 
     for (int i = 0; i < orderOfFlipLocations.size(); i++) { 
      if (i != 0) { 
       cout << ' '; 
      } 
      cout << orderOfFlipLocations[i]; 
     } 
     cout << endl; 
    } 
} 

/** 
* Return the order of the locations to flip pancakes in the pancake stack. 
*/ 
vector<int> getAllFlipLocations(vector<int> &pancakesRepresentedByDiameter) { 
    vector<int> orderOfFlipLocations; 

    vector<int>::iterator beginIndex = pancakesRepresentedByDiameter.begin(); 
    vector<int>::iterator endIndex = pancakesRepresentedByDiameter.end(); 

    for (int i = 0; i < pancakesRepresentedByDiameter.size(); i++) { 
     vector<int>::iterator currentIndex = beginIndex + i; 
     vector<int>::iterator maximumIndex = max_element(currentIndex, 
       endIndex); 

     // iterate through the stack of pancakes 
     if (currentIndex != maximumIndex) { 

      if (maximumIndex + 1 != endIndex) { 
       // adds value of (maximumIndex - beginIndex + 1) to the end of the vector 
       orderOfFlipLocations.push_back(maximumIndex - beginIndex + 1); 
       reverse(maximumIndex, endIndex); 
      } 
      orderOfFlipLocations.push_back(i + 1); 
      reverse(currentIndex, endIndex); 
     } 
    } 
    orderOfFlipLocations.push_back(0); 
    return orderOfFlipLocations; 
} 
+0

C++沒有內置的生成/運行單元測試的方法,但快速的谷歌搜索會出現相當多的單元測試框架。 – suszterpatt

+0

我喜歡使用gookletest/googlemock,但還有一些其他測試框架用於C++。 –

回答

0

不,開箱即用C++沒有任何單元測試。儘管這些日子有很多IDE。 Here是在Visual Studio中進行單元測試的方法,也有一些值得一提的框架是CppUnit,UnitTest++Google C++ Testing Framework。如果你正在尋找更具體的東西,你可以檢查主題here的舊線程。