我正在尝试将一些代码从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发布于 2013-05-06 12:32:58
你至少需要:
std::tuple )。我相信这足以让你入门,如果你在实际编写代码时遇到了特定的问题,请毫不犹豫地提出新的问题。
根据您的评论进行编辑:
你不会错过太多,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;
}发布于 2013-05-06 13:02:25
应该是这样的,唯一使用的内存是用于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规则上失败。
https://stackoverflow.com/questions/16391830
复制相似问题