Code worked on:
#include <algorithm>
#include <list>
#include <vector>
class key_value_sequences {
public:
int size(int key);
int * data(int key);
void insert(int key, int value);
private:
list< pair<int, vector<int> > > myList;
}; // class key_value_sequences
#endif
void key_value_sequences::insert(int key, int value){
list< pair<int, vector<int> > >::iterator it;
for(it = myList.begin(); it != myList.end(); ++it){
if (it->first == key){
it->second.push_back(value);
return;
}
}
vector<int> v;
v.push_back(value);
myList.push_back(make_pair(key, v));
return;
};
int * key_value_sequences::data(int key){
list< pair<int, vector<int> > >::iterator it;
for(it = myList.begin(); it != myList.end(); ++it){
if (it->first == key){
return (it->second);
}
}
vector<int> v;
return v;
};
int key_value_sequences::size(int key){
list< pair<int, vector<int> > >::iterator it;
for(it = myList.begin(); it != myList.end(); ++it){
if (it->first == key){
return it->second.size();
}
}
return -1;
};
I am getting errors for template arguments, and can't figure out why. It looks like this line
std::list< pair<int, vector<int> > > myList;
is throwing errors
error: template argument 1 is invalid
std::list< pair<int, vector<int> > > myList;
^
error: template argument 2 is invalid
error: expected unqualified-id before ‘>’ token
std::list< pair<int, vector<int> > > myList;
^
I can't figure out why.
I'm also stuck with errors
/usr/include/c++/5/bits/stl_algobase.h:840:58: error: no type named ‘value_type’ in ‘struct std::iterator_traits<std::vector<int> >’
typedef typename iterator_traits<_II2>::value_type _ValueType2;
^
/usr/include/c++/5/bits/stl_algobase.h:845:9: error: no type named ‘value_type’ in ‘struct std::iterator_traits<std::vector<int> >’
&& __are_same<_ValueType1, _ValueType2>::__value);
^
The instantiation of the iterator is:
list<pair<int, vector<int>>>::iterator it;
Edit trying out vector hashtable:
class key_value_sequences {
public:
int size(int key);
int* data(int key);
void insert(int key, int value);
private:
vector<list<pair<int,int>>> hash_table;
list<pair<int, vector<int>>>::iterator it;
int hash(int value)
{
return abs(value%static_cast<int>(hash_table.size()));
}
}; // class key_value_sequences
#endif // A3_HPP
void key_value_sequences::insert(int key, int value){
list<pair<int,int>> &collisionlist = hash_table[hash(key)];
for (std::pair<int,int> &test: collisionlist)
{
if (key == test.first)
{
test.second = value; // update existing
return;
}
}
collisionlist.push_back(pair<int,int>(key, value));
};
int* key_value_sequences::data(int key){
for(it = hash_table.begin(); it != hash_table.end(); ++it){
if (it->first == key){
return &(it->second[0]);
}
}
return nullptr;
};
int key_value_sequences::size(int key){
for(it = hash_table.begin(); it != hash_table.end(); ++it){
if (it->first == key){
return it->second.size();
}
}
return -1;
};