I am trying to convert some code from c# to c++ but lack of dictionary tables/enumerables etc making me difficult to get the result needed in c++. Can anyone help with the type of container/methods to use in c++ to get the result needed?
Thanks in advance.
Find all c1 and it's count group by c1 where c2 > 0 and c3 < 4 order by 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
You will need at the very least:
struct
to hold each c1/c2/c3 tuple (or a std::tuple
if you use C++11).std::vector
(array-like container, but with dynamic size) to hold all your tuples.std::map
(sorted associative container) to act as a dictionary to compute your output.I believe this is enough to get you started, if you have a specific problem when actually writing the code don't hesitate to ask new questions.
Edit according to your comments:
You're not missing much, elvena's solution is almost what you need except it lacks the vector container to store the objects. This is quite straightforward:
#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;
}