Universal Stack Universal Stack - 1 year ago 61
C++ Question

Combining same unique ID items

I have a list such as:

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

and I'd like it transfer to for the same unique id ones

1 a
2 b
3 c d
4 e
5 f

here's my code, many items are known, but i just can't to write the function that can transfer the list input.

#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]){

for(i=0; 0 < rows_count; i++){
rows_count = 1;

cout << transaction_table[1][0];

Answer Source

You can use std::map to store std::vector<char> for each integer. The integer value is the map's key. Each key contains a vector of characters:

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";

Or use 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))

        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";

Depending on the data, you may also be able to use std::map<char, int>. But this assumes char is the map's key, and each character appears no more than once. Each character can be associated with any number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download