lets say I have 1 vector of names and another vector for the telephone numbers. First, the user will enter names (not sorted, meaning they are not organized from a to z), then, the user will enter the corresponding telephone number.
After filling out both vectors, the program then executes sorting mechanism in the name vector(vector 1). The problem is now the vector 2, (since there is no adopting mechanism to map it to vector 1).
Example:
vector name | vector telephone
f 232132
a 34242342
b 997345
the result will be
vector name | vector telephone
a 232132
b 34242342
f 997345
as you can see, the vector telephone hasnt been adjusted. how can we adjust this?? thanks
Create a struct that holds a string for the name and a string/int for the phone number. Go through it linearly and record the name information. Go through it again and record the phone # information. Then sort.
If you do not wish to create a class, you can use a pair object.
vector<pair<string,int> > nameAndNumber;
Edit: fixed a bug, thanks smocking
the vector telephone hasnt been adjusted. how can we adjust this??
By combining both entities "name" and "telephone" inside a data structure and then use its vector.
struct NameNumber {
std::string t_Name;
unsigned long t_Number;
bool operator < (const NameNumber&) const; // use 't_Name' inside
};
std::vector<NameNumber> v;
For completeness of the solution, I have mentioned the operator < which will sort the vector according to the names.
Related
I need suggestion to use STL containers in the best possible way to sort 3 sets of data
1. A ID (Integer)
2. First Value (String)
3. Second Value (String)
An example of the data structure is as below:
I want to use map as it is sorted at the time of insert and no need to execute a sorting algorithm separately. Since the ID can repeat it must be a multimap, and each data of a column is linked to each other so the rows will change in order to sort keeping the same values attached to a ID.
Sorting the ID and value is ok, but how do I sort 2 values as multimap can take only one value. From my thinking it will be multimap of a multimap or a struct of the data structure and then STL containers. But I want to make it as simple as possible. I need suggestion on how this can be achieved.
Thanks!
Having a map or a set makes sense if and only if you are going to do many insert/erase operations it. If the data structure is static, storing a vector and sorting it once is way more effective. That said, if I understand your question correctly, I think you don't need a map, but a multiset.
typedef pair<int, pair<string, string>> myDataType;
set<myDataType> mySet;
here, the operator < of pair will take care of the ordering.
If you don't want to refer to the id as elem.first, and to the strings as elem.second.first, and elem.second.second, then you can use a struct and overload operator < for it.
struct myType
{
int id;
string s1;
string s2;
};
bool operator < (const myType& t1, const myType& t2)
{
return make_tuple(t1.id, t1.s1, t1.s2) < make_tuple(t2.id, t2.s1, t2.s2);
}
You could just use a std::set<std::tuple<int, std::string, std::string>>. Tuples are lexicographically compared thus you would get the effect you want for free.
Live Demo
Elements in a multimap are sorted by the Key. You cannot 'sort' multimap. What you can do is to create vector of pairs<Key, Map<Key>::Interator> with elements fulfilling some logical condition and sort vector.
In chess, each type of coin has some weight. Given the name of the coin and weight for the coin, write a C++ code to print the name of the coins in ascending order of their weight. Assume that weight of each coin is unique.
I want to use map
My codes is here
#include <iostream>
#include <map>
using namespace std;
int main(){
int n,i=0;
char name;
int weight;
cin>>n;
class std::map<char,int> coins;
while(i<n)
{
i++;
cin>>name;
cin>>weight;
coins[name]=weight;
}
coins.sort(coins.begin(),coins.end(),weight);
while(i<n){
i++;
cout<<coins;
}
You cannot sort a map. The elements are already sorted in an
order defined by the key of each element.
If it is guaranteed that every piece will have a unique weight,
none the same as any other,
then you can use weight instead of name as your key
in a map of type std::map<int,char>.
Then simply iterating through the map will give you the elements
in order of increasing weight.
But if you do that
and if it ever happens that someone specifies two pieces that have
the same weight in the input to your program, one of the pieces
will be lost and will not appear at all in the output list.
For the reason just mentioned, using a map this way has a bad
"code smell" and I would be reluctant to use it in real life.
I would also be hesitant to give this as an answer to an
exercise in a programming course.
If you use multimap instead of map, however, you can have
multiple elements with the same key, still sorted according to the
order of their keys.
That seems like a much better idea.
No need to sort . Only list needs to be sorted . Maps by default keep the data in sorted format
so I'm just learning (or trying to) a bit about hashing. I'm attempting to make a hashing function, however I'm confused where I save the data to. I'm trying to calculate the number of collisions and print that out. I have made 3 different files, one with 10,000 words, 20,000 words and 30,000 words. Each word is just 10 random numbers/letters.
long hash(char* s]){
long h;
for(int i = 0; i < 10; i++){
h = h + (int)s[i];
}
//A lot of examples then mod h by the table size
//I'm a bit confused what this table is... Is it an array of
//10,000 (or however many words)?
//h % TABLE_SIZE
return h
}
int main (int argc, char* argv[]){
fstream input(argv[1]);
char* nextWord;
while(!input.eof()){
input >> nextWord;
hash(nextWord);
}
}
So that's what I currently have, but I can't figure out what the table is exactly, as I said in the comments above... Is it a predefined array in my main with the number of words in it? For example, if I have a file of 10 words, do I make an array a of size 10 in my main? Then if/when I return h, lets say the order goes: 3, 7, 2, 3
The 4th word is a collision, correct? When that happens, I add 1 to collision and then add 1 to then check if slot 4 is also full?
Thanks for the help!
The point of hashing is to have a constant time access to every element you store. I'll try to explain on simple example bellow.
First, you need to know how much data you'd have to store. If for example you want to store numbers and you know, that you won't store numbers greater than 10. Simpliest solution is to create an array with 10 elements. That array is your "table", where you store your numbers. So how do I achieve that amazing constant time access? Hashing function! It's point is to return you an index to your array. Let's create a simple one: If you'd like to store 7, you just save it to array on position 7. Every time, you'd like to look, for element 7, you just pass it to your hasning funcion and bzaah! You got an position to your element in constant time! But what if you'd like to store more elements with value 7? Your simple hashing function is returning 7 for every element and now its position i already occupied! How to solve that? Well, there is not many solution, the simpliest are:
1: Chaining - you simply save element on first free position. This has significant draw back. Imagine, you want to delete some element ... (this is the method, you describing in question)
2: Linked list - if you create an array of pointers on some linked lists, you can easilly add your new element at the end of linked list, that is on position 7!
Both of this simple solutions has its drawbacks and cons. I guess you can see them. As #rwols has said, you don't have to use array. You can also use a tree or be a real C++ master and use unordered_map and unordered_set with custom hash function, which is quite cool. Also there is structure named trie, which is usefull, when you'd like to create some sort of dictionary (where is really hard to know, how many words you will need to store)
To sum it up. You has to know, how many things, you wan't to store and then, create ideal hashing function, that covers up array of apropriate size and in perfect world, it has to have uniform index distribution, with no colisions. (Achiving this is pretty hard and in the real world, I guess, this is impossible, so the less colisions, the better.)
Your hash function, is pretty bad. It will have lot of colisions (like strings "ab" and "ba") and also, you need to mod m it with m being the size of you array (aka. table), so you can save it to some array and you can profit of it. The modus is a way of simplyfiing the has function, because has function has to "fit" in table, that you specified in beginning, because you can't save element on position 11, 12, ... if you have array of 10.
How should good hashing function look like? Well, there is better sources than me. Some example (Alert! It's in Java)
To your example: You simply can't save 10k or even more words into table of size 10. That'll create a lot of collisions and you loose the main benefit of hashing function - constant access to elements you saved.
And how would your code look? Something like this:
int main (int argc, char* argv[]){
fstream input(argv[1]);
char* nextWord;
TypeOfElement table[size_of_table];
while(!input.eof()){
input >> nextWord;
table[hash(nextWord)] = // desired element which you want to save
}
}
But I guess, your goal isn't to save something somewhere, but to count number of colisions. Also note that code above doesn't solve colisions. If you'd like to count colisions, create array table of ints and initialize it to zero. Than, just increment the value, which is stored on index, which is returned by your hash funcion, like this:
table[hash(nextWord)]++;
I hope I helped. Please specify, what else you want to know.
If a hash table is required then as others have stated std::unordered_map will work in most cases. Now if you need something more powerful because of a large entry base, then I would suggest looking into tries. Tries combine the concepts of (Vector-Array) insertion, (Hashing) & Linked Lists. The run time is close to O(M) where M is the amount of characters in a string if you are hashing a string. It helps to remove the chance of collisions. And the more you add to a trie structure the less work has to be done as certain nodes are opened and created. The one draw back is that tries require more memory. Here is a diagram
Now your trie may vary on the size of the array due to what you are storing, but the overall concept and construction of one is the same. If you was doing a word - definition look up then you may want an array of 26 or a few more for each possible hashing character.
To count a number of words which have same hash, we should know hashes of all previous words. When you count a hash of some word, you should write it down, for example in some array. So you need an array with size equal to the number of words.
Then you should compare the new hash with all previous ones. Method of counting depends on what you need - number of pair of collisions or number off same elements.
Hash function should not be responsible for storing data. Normally you would have a container that uses hash function internally.
From what you wrote I understood that you want to create hashtable. One way you could do that (probably not the most efficient one, but should give you an idea):
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <memory>
using namespace std;
namespace example {
long hash(char* s){
long h;
for(int i = 0; i < 10; i++){
h = h + (int)s[i];
}
return h;
}
}
int main (int argc, char* argv[]){
fstream input(argv[1]);
char* nextWord;
std::map<long, std::unique_ptr<std::vector<std::string>>> hashtable;
while(!input.eof()){
input >> nextWord;
long newHash = example::hash(nextWord);
auto it = hashtable.find(newHash);
// Collision detected?
if (it == hashtable.end()) {
hashtable.insert(std::make_pair(newHash, std::unique_ptr<std::vector<std::string>>(new std::vector<std::string> { nextWord } )));
}
else {
it->second->push_back(nextWord);
}
}
}
I used some C++ 11 features to write an example faster.
I am not sure that I understand what you do not understand. The explanations below might help you.
A hash table is a kind of associative array. It is used to map keys to values in a similar manner an array is used to map indexes (keys) to values. For instance, an array of three numbers, { 11, -22, 33 }, associates index 0 to 11, index 1 to -22 and index 2 to 33.
Now, let us assume that we would like to associate 1 to 11, 2 to -22 and 3 to 33. The solution is simple: we keep the same array, only we transform the key by subtracting one from it, thus obtaining the original index
This is fine until we realize that this is just a particular case. What if the keys are not so “predictable”? A solution would be to put the associations in a list of {key, value} pairs and when someone is asking for a key, just search the list: { 123, 11}, {3, -22}, {0, 33} If the value associated to 3 is asked, we simply search the keys in list for a match and find -22. That’s fine, but if the list is large we’re in trouble. We could speed the search if we sort the array by keys and use binary search, but still the search may take some time if the list is large.
The search speed may be further enhanced if we break the list in sub-lists (or buckets) made of related pairs. This is what a hash function does: puts together pairs by related keys (an ideal hash function would associate one key to one value).
A hash table is a two columns table (an array):
The first column is the hash key (the index computed by a hash function). The size of the hash table is given by the maximum value of the hash function. If, for instance, the last step in computing the hash function is modulo 10, the size of the table will be 10; the pairs list will be broken into 10 sub-lists.
The second column is a list (bucket) of key/values pairs (the sub-list I was taking about).
Lets say i have a struct below
struct info
{
string firstname;
string lastname;
double kids;
double income;
double cars;
int index;
};
Lets say i have 500 people in this struct, each containing the information first, last name, kids, income and cars.
I created a int called index so that i can sort who has the most income from highest to least.
What method would you use or how would you go about finding the top 5 people with the most income, and giving them an index as 1,2,3,4,5 etc. So that i can tell who the top 5 are if i wished to print their names out.
I am looking for a simple method as im still learning about trees and such.
Thanks!
vector of structs. Supply a specialized function for comparison that gets called during sort.
the specialized compare function shall compare based on income (descending order)
the first top 5 elements from sorted vector should give your answer
If you just want the top 5 (and don't need them in order) you can use std::nth_element to find them. This is normally faster than sorting.
If you do want the top 5 in order, you could use std::partial_sort to do the job, something like this:
std::partial_sort(x.begin(), x.begin() + 5, x.end(),
[](auto a, auto b) { return b.income < a.income; });
Note that I've swapped the two parameters when comparing them to get it to sort in descending order instead of ascending.
I don't see a very good way to use the index field you've put into the structure. To work very well, you'd want the index separate from the data you're sorting, and you'd do an indirect sort on the indexes (that is, you'd sort the indexes based on the income for the item at that index).
Say I have a high score table structured like
name score
name score
....
I need to do some file operations and manipulate certain areas of the file, and I thought the best way to do this would be to store it in a container that preserved the order of the file, do the data manipulation with the container, then output back to the file.
I considered using a map< std::string, int >, but a map wouldn't preserve the order of the file. Would a vector< pair< std::string, int >> be better, or is there some kind of ordered map I can use? I also need the container to repeat a name if necessary. I think a multimap keeps one key, but allows multiple values for that key, which isn't what I want since it wouldn't preserve order.
Use the
std::vector< std::pair< std::string, int > >
solution.
Or even better, do a HighScoreEntry class, and have a std::vector< HighScoreEntry > -- then you'll be able to add additional data to it later, and embed score handling code in the class.
To add an entry, push the entry to the end of the vector, and run std::sort on it, just remember to write a comparison operator for HighScoreEntry.
class HighScoreEntry
{
public:
std::string name;
uint32 score;
bool operator<(const HighScoreEntry& other) const
{
// code that determines ordering goes here
return score < other.score
}
};
Highscore table:
std::vector< HighScoreEntry > highscores;
Sorting:
std::sort( highscores.begin(), highscores.end() );
To preserve sort order for highscores that have the same score, use a timestamp, and add it to the comparator.
typedef std::pair<int, int> score_entry; // score, timestamp/serial
typedef std::map<score_entry, std::string, std::greater<score_entry> > score_map;
It's ordered by the score and timestamp/serial (in descending order), and allows duplicates of the same high score. (If you want earlier timestamp/serial to be listed first, put in negative numbers.)
Using a serial number instead of a timestamp means that you can allow duplicates without having to use multimap. Thanks to Steve Jessop for the suggestion!
If you want an ordered map, then you want it ordered by score, so it should be a multimap<int, string>, to preserve order and permit tied scores.
This strikes me as silly, though, not to mention it's not obvious what on earth is being "mapped". Container performance on a high-score table is very unlikely ever to matter, so I'd just use the vector of pair<string,int>.
Why use a priority_queue? Should make adding new scores easy as well.
I also need the container to repeat a name if necessary.
So stick the same name into your vector-of-pairs twice. Is that really such a big deal?