我正在尝试将一些代码从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
答案 0 :(得分:1)
至少你需要:
struct
用于保存每个c1 / c2 / c3元组(如果使用C ++ 11,则为std::tuple
。)std::vector
(类似于数组的容器,但具有动态大小)来容纳所有元组。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;
}
答案 1 :(得分:1)
这样的事情应该做,唯一使用的内存是c1和c1的有效c2 / c3的计数:
#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规则上失败。