2013-05-06 39 views
0

我想將c#中的一些代碼轉換爲C++,但缺乏字典表/枚舉等,這使得我很難在C++中獲得所需的結果。任何人都可以幫助使用C++中的容器/方法來獲得所需的結果嗎?尋找合適的容器/函數在C++中枚舉

在此先感謝。

找到所有C1,它通過C1的次數羣,其中C2> 0和c3 < 4由C1

table(c1,c2,c3) (number of rows expected is not finite - so - can't use Array as a structure for this) 
5 1 2 
4 2 3 --> edited this line to make it into the list 
4 4 3 
4 0 1 --> ignore this row as c2=0 
3 1 3 
2 1 5 --> ignore this row as c3 > 4 
..... 

爲了.....

expected output(number of rows meeting criteria for each c1): 
3 1 
4 2 
5 1 

回答

1

您將需要至少是:

  • struct(如果使用C++ 11或std::tuple)來保存每個C1/C2/C3元組。
  • A std::vector(類似數組的容器,但具有動態大小)來容納所有的元組。
  • A std::map(排序關聯容器)充當字典來計算您的輸出。

我相信這足以讓您開始,如果您在實際編寫代碼時遇到特定問題,請不要猶豫提出新問題。


根據您的評論編輯:

您不會錯過太多,elvena的解決方案是幾乎需要,除了它是什麼缺少載體容器來存儲對象。這是很簡單的:

#include <iostream> 
#include <map> 
#include <vector> 
#include <tuple> 

int main() 
{ 
    std::vector<std::tuple<int, int, int>> values; 
    while (you_have_more_data) { 
     int c1, c2, c3; 
     // somehow read c1, c2, c3 from cin/file/whatever 
     values.push_back(std::make_tuple(c1, c2, c3)); 
    } 

    std::map<int, int> dict; 
    // iterate over the vector 
    for (auto i = values.begin(); i != values.end(); ++i) { 
     // *i (dereferencing the iterator) yields a std::tuple<int, int, int> 
     // use std::get to access the individual values in the tuple 
     // 0 => c1; 1 => c2; 2 => c3 (same order as in std::make_tuple) 
     if (std::get<1>(*i) > 0 && std::get<2>(*i) < 4) 
      dict[std::get<0>(*i)] += 1; // see std::map::operator[] 
    } 

    // iterate over the map and print its items 
    for (auto i = dict.begin(); i != dict.end(); ++i) 
     // *i (dereferencing the iterator) yields a std::pair<int, int> 
     // but writing (*i).first is cumbersome 
     // let's write i->first instead (this is the same, just a different notation) 
     std::cout << i->first << " " << i->second << std::endl; 

    return 0; 
} 
+0

感謝syam。我正在使用c + + 11,實際上開始了一些類似的道路,但無法取得很大進展。在c#中,我可以創建基表的過濾器(視圖),然後應用過濾器/組/排序選項以獲取所需的輸出。會再做一次,看看我能不能得到任何東西..謝謝 – ejuser 2013-05-06 11:28:51

+0

換句話說 - 由於我有限的c + +技能,無法獲得太多...... – ejuser 2013-05-06 11:40:25

+0

@ejuser:我編輯了我的答案,包括一個'vector/tuple'示例。 – syam 2013-05-06 13:44:21

1

像這樣的事情應該做,唯一使用的內存爲C1和有效的C2/C3的這一C1計數:

#include <iostream> 
#include <map> 

using namespace std; 

int main() 
{ 
    int a,b,c = 0; 
    map<int, int> n; 
    int i; 

    for(i = 0 ; i < 6 ; i ++) 
    { 
     cout << "Enter three numbers separated by space" << endl; 
     cin >> a >> b >> c; 
     if(b > 0 && c < 4) 
      n[a] += 1; 
    } 

    for(auto iter = n.begin(); iter != n.end() ; ++iter) 
     cout << iter->first << " " << iter->second << endl; 

    return 1; 
} 

給人

3 1 
4 1 
5 1 

請注意,您的示例不適用於c1 = 4,因爲4.2.4在c3規則上失敗。

+0

謝謝elvena。但是這種解決方案看起來不是一個可行的解決方案,因爲所有這些行必須通過某種方式存儲在容器中。 – ejuser 2013-05-06 11:20:36