首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为c++中的enumerable寻找合适的容器/函数

为c++中的enumerable寻找合适的容器/函数
EN

Stack Overflow用户
提问于 2013-05-06 12:08:27
回答 2查看 94关注 0票数 0

我正在尝试将一些代码从c#转换为c++,但是缺少字典表/枚举表等,这使得我很难在c++中获得所需的结果。有谁可以帮助在c++中使用的容器/方法的类型,以获得所需的结果?

提前谢谢。

按c1查找所有c1及其计数分组,其中c2 >0且c3 <4按c1排序

代码语言:javascript
复制
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
.....

.

代码语言:javascript
复制
expected output(number of rows meeting criteria for each c1):
3 1
4 2
5 1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-06 12:32:58

你至少需要:

  • 用于保存每个c1/c2/c3元组的容器(如果使用C++11,则为std::tuple )。
  • 用于保存所有元组的容器(类似数组的容器,但具有动态大小)。
  • A C9(排序关联容器)用作计算输出的字典。H210F211

我相信这足以让你入门,如果你在实际编写代码时遇到了特定的问题,请毫不犹豫地提出新的问题。

根据您的评论进行编辑:

你不会错过太多,elvena的解决方案几乎就是你需要的,除了它缺少存储对象的向量容器。这很简单:

代码语言:javascript
复制
#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
EN

Stack Overflow用户

发布于 2013-05-06 13:02:25

应该是这样的,唯一使用的内存是用于c1和此c1的有效c2/c3计数:

代码语言:javascript
复制
#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;
}

给出

代码语言:javascript
复制
3 1
4 1
5 1

请注意,您的示例不适合c1=4,因为4.2.4在c3规则上失败。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16391830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档