initilize unordered_map with a vector in c++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I simply would like to initizlize an unordered_map with a vector.
When I have tried the code below, the code does not compile.
What is the shortest syntax to initilize unordered_map with a vector? How would you implement following method without using loop.
unordered_map<int, int> convertToMap(const vector<int>& v)
{
unordered_map<int, int> umap(v.begin(), v.end());
return umap;
}
I have found some resources, and I have tried to initialize through a range, but it does not worked either!
initialize-unordered-map

How to initialize unordered_map with vector?
If your vector contains pairs of elements, so that one could be interpreted as key and one as value then you can use range initialization:
#include <vector>
#include <unordered_map>
#include <iostream>
#include <utility>
int main()
{
std::vector<std::pair<int, int>> v = { {1,10}, {2,20}, {3,30} };
std::unordered_map<int, int> map(v.begin(), v.end());
std::cout << map[2] << std::endl;
return 0;
}
The above prints: 20

Related

Best way to copy members from vector<Class> to vector<Member_Type> [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 months ago.
Improve this question
I have a vector of complicated structs (here std::pair<int, int>). I now want to copy a member (say std::pair::first) into a new vector. Is there a better (more idiomatic) way than
std::vector<std::pair<int, int>> list = {{1,2},{2,4},{3,6}};
std::vector<int> x_values;
x_values.reserve(list.size());
for( auto const& elem : list )
{
x_values.emplace_back(elem.first);
}
std::transform is often used for exactly this:
#include <algorithm> // transform
#include <iterator> // back_inserter
// ...
std::vector<int> x_values;
x_values.reserve(list.size());
std::transform(list.cbegin(), list.cend(), std::back_inserter(x_values),
[](const auto& pair) { return pair.first; });
In c++20 using std::ranges::views::transform and range algorithms one might do
#include <ranges> // std::views::transform
#include <algorithm> // std::ranges::copy
std::vector<int> x_values;
x_values.reserve(list.size());
std::ranges::copy(std::views::transform(list, [](const auto& pair) {
return pair.first; }), std::back_inserter(x_values));
or may be a just view over the pair.first (if the indention is to have a read only range)
#include <ranges> // std::views::transform
const auto x_values_view = std::views::transform(list, [](const auto& pair) {
return pair.first; }
);
Live Demo

changing key values of all elements in a multimap container [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am working on a c++ code which includes a command schedule. I implement the schedule as a multimap container, with execution time,as the key, and command name I want to execute. I need to be able to time shift all the commands in the schedule.
I assume I can do that by copying the container to another container and erasing the original container, then changing the key values for each pair in the copy container and inserting it back in the original container, like the example code below.
#include <stdio.h>
#include <map>
int main() {
std::multimap<int,int> original,copy;
original.insert(std::pair<int,int>(10,1));
original.insert(std::pair<int,int>(10,2));
original.insert(std::pair<int,int>(12,3));
std::multimap<int,int>::iterator it;
copy=original;
it=original.begin();
original.erase(it,original.end());
int tctime;
int command;
for (it=copy.begin();it!=copy.end();it++){
tctime =(*it).first+5;
command=(*it).second;
original.insert(std::pair<int,int> (tctime, command));
}
return 0;
}
while this works, I would like to know if there is a better solution to implement it.
Although you should ask these kind of questions on Code Review, I will write my answer here also so it may help someone else (and since it is not yet closed).
First, since your question has a C++ tag, please use #include <iostream> instead of #include <stdio.h>.
Second, I suggest you to use std::make_pair instead of the std::pair constructor. std::make_pair automatically deduces types of the values passed to it so I would prefer it over std::pair where you need to specify the types. So, you should use something like this:
original.insert(std::make_pair(10,1));
Next, since you are erasing all the values from the std::multimap<int,int> original, why not just use std::multimap::clear? It is less code to write and your intention is more straightforward.
original.clear()
instead of
it=original.begin();
original.erase(it,original.end());
Furthermore, I would suggest using range-for loops over the standard loops.
for (auto const& it : copy) {
tctime = it.first +5;
command = it.second;
original.insert(std::make_pair(tctime, command));
}
instead of
for (auto it = copy.begin(); it != copy.end(); it++){
tctime =(*it).first+5;
command=(*it).second;
original.insert(std::pair<int,int>(tctime, command));
}
And the last thing, good practice would be to initialize variables tctime and command to 0.
Full code:
#include <iostream>
#include <map>
int main() {
std::multimap<int,int> original,copy;
original.insert(std::make_pair(10,1));
original.insert(std::make_pair(10,2));
original.insert(std::make_pair(12,3));
copy=original;
original.clear();
int tctime = 0;
int command = 0;
for (auto const& it : copy) {
tctime = it.first +5;
command = it.second;
original.insert(std::make_pair(tctime, command));
}
return 0;
}
Here is the fully refactored code live.

Duplicate elements in array using Hash Table in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
Can someone give an example of finding array duplicates using a Hash table and a function.
I am looking for some examples in C++.
The codes I am getting are all in Java.
One solution is to put in a hash table the element of the array (as key) and their number of occurrence (as value).
Then you copy the key of the hash table where the associated value is more than 1.
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
int main(int argc, char* argv[]) {
std::vector<int> vec{1,1,2,3,1,4,5};
std::map<int, int> m;
// We copy the element of the vector into the hash table
std::for_each(vec.begin(), vec.end(), [&m](auto & elt){ m[elt] += 1; });
std::vector<int> res;
// We select the key where the value is > 1
std::for_each(m.begin(), m.end(), [&res](auto & elt) { if(elt.second > 1) res.push_back(elt.first); });
}

Extract vector from std::map<int, std::vector> [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Here is my code
#include <iostream>
#include <map>
#include <string>
#include <vector>
typedef std::vector<int> VectorInt;
typedef std::map<int, VectorInt> MapVectorInt;
int main() {
MapVectorInt myMap;
VectorInt v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
VectorInt v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
myMap.insert(std::make_pair(0, v1));
myMap.insert(std::make_pair(1, v2));
return 0;
}
What is the bese way to take (extract/get) the vector at position x (eg 1,2...);
You can use:
auto v1=myMap[0]; //This will do a deep copy for the vector
or:
auto& v1=myMap[0]; //This will hold a reference to the vector
Be careful in the second approach because if the item has removed , the reference will be invalid.
If you want a safe option use std::map::at:
auto v1=myMap.at(0);
or:
auto& v1=myMap.at(0)
This will throw an exception (std::out_of_range) if the item is not there.
Short answer:
Best place to look for it http://en.cppreference.com/w/cpp/container/map/find
With context:
For visualisation only, I guess you should express you intention as you said in your question(get an element from the map and not "eventually" insert it as using [] for accessing a non-existing element creates it), so:
const auto& search = myMap.find(1);
if (search != example.end()) {
for(auto value: search->second) {
std::cout << value << '\n';
}
}
else {
std::cout << "Not found\n";
}
Try It Live
You can refer to the vector in the map with myMap[0] or myMap[1].
You could make an alias for either of those, e.g. auto& x = myMap[0];. Using the alias will access the vector as it is stored in the map.
To take a copy of the vector (so that you can modify the map contents without changing the copy), it is just the same as copying any other object:
auto x = myMap[0];
Note that 0 and 1 refer to the key you used in the insert call; not to the search order or the insertion order (although in your example those things all happen to be the same).

Sorting a vector of pairs <int,int> [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How to sort a vector of pairs in descending order when the pair is incr<int,int>using the std::sort() in STL?It should sort first with respect to the first element and then the second.
The operator< is overloaded for pair<int,int> so you can sort a vector of pairs just like any other vector. If you need descending order, you have two options - either sort and then call std::reverse to reverse the result or provide predicate for the sorting.
You can also make use of std::greater:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<pair<int, int> > a;
a.push_back(make_pair(1, 2));
a.push_back(make_pair(2, 3));
sort(a.begin(), a.end(), greater<pair<int,int> >());
return 0;
}
use this,
template<class T>
struct sortFunctor: public unary_function<std::pair<int, int>, std::pair<int, int>>
{
bool operator()(const std::pair<int, int>& First, const std::pair<int, int>& Second)
{
if(First.first < Second.first)
{
return false;
}
if(First.first == Second.first && First.second < Second.second)
{
return false;
}
return true;
}
}
then pass this functor as a third parameter to sort function.