组合相同的唯一ID项

时间:2016-11-03 07:41:08

标签: c++ sorting

我有一个列表,例如:

1 a
2 b
3 c
3 d
4 e
5 f

我希望它转移到相同的唯一ID

1 a
2 b
3 c d
4 e
5 f

这是我的代码,很多项都是已知的,但我只是不能编写可以传输列表输入的函数。

#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <stdlib.h>

using namespace std;

vector<int> transaction_id;
vector<int> item_id;

vector<vector<int> > transaction_table;
vector<int> items_for_each_row;
vector<int> temp_items_for_each_row;

    int real_id = 0;
    int rows_count = 1;


    while(rows_count < orig_line_count){

        while(rows_count < orig_line_count){
            if(transaction_id[real_id] == transaction_id[real_id+1]){
                rows_count++;
                real_id++;
            }else{
                break;
            }
        }

        for(i=0; 0 < rows_count; i++){
            items_for_each_row.push_back(item_id[real_id]);
            transaction_table.push_back(items_for_each_row);
            real_id++;
        }
        rows_count = 1;
    }


cout << transaction_table[1][0];

1 个答案:

答案 0 :(得分:3)

您可以使用std::map为每个整数存储std::vector<char>。整数值是地图的关键字。每个键都包含一个字符向量:

std::map<int, std::vector<char>> mp;
mp.emplace(1, std::vector<char>{'a'});
mp.emplace(2, std::vector<char>{'b'});
mp.emplace(3, std::vector<char>{'c', 'd'});
mp.emplace(4, std::vector<char>{'e'});
mp.emplace(5, std::vector<char>{'f'});

for (const auto &map_element : mp)
{
    //map_element.first is map's key (1,2,3,4,5)
    cout << map_element.first << " = ";

    //map_element.second is a vector containing letters
    for (const auto &ch : map_element.second)
        cout << ch << " ";

    cout << "\n";
}

或使用std::multimap

std::multimap<int, char> m;
m.emplace(1, 'a');
m.emplace(2, 'b');
m.emplace(3, 'c');
m.emplace(3, 'd');
m.emplace(4, 'e');
m.emplace(5, 'f');

for (int i = 0; i <= 5; i++)
{
    if (!m.count(i))
        continue;

    std::pair<
        std::multimap<int, char>::iterator,
        std::multimap<int, char>::iterator> pr;

    pr = m.equal_range(i);

    auto it = pr.first;
    cout << (*it).first << " = ";

    for (it = pr.first; it != pr.second; ++it)
        cout << (*it).second << " ";

    cout << "\n";
}

根据数据,您也可以使用std::map<char, int>。但这假设char是地图的关键字,每个字符只出现一次。每个字符都可以与任何数字相关联。