MMM
MMM

Reputation: 345

Storing values from a certain range in a map

So I have a map of values, for example:

 1 3 5 7 9

With my current code, I'm currently able to find the number of occurrences between a certain range of [low, high]. For example if I had [3, 7] I would get the value 3.

My current code looks like this:

 // map::lower_bound/upper_bound
 #include <iostream>
 #include <map>
 using namespace std;

 int main ()
 {
   map<long,deque<my_struct>> my_map;
   deque<my_struct> results;

   mymap[12345].push_back(some_obj);
   mymap[23456].push_back(some_obj);
   mymap[34567].push_back(some_obj);
   mymap[45678].push_back(some_obj);

   auto low = my_map.lower_bound (12345);  
   auto high = my_map.upper_bound (34567);  

   int num = 0;
   for (auto it = low; it != high; ++it){
        ++num;
        //how to insert into my results deque? 
    }
    cout << num << " found\n"; //3found
   return 0;
 }

My question is: How do I get the 3 objects in this example that exist between low and high? I want to store these 3 objects in the "results" deque so I know what 3 I found within that certain range. I know I want to push 3 objects of my-struct in but I'm having a hard time figuring out the syntax. Any tips or help would be appreciated!!

Edit: Trying to use the new method

 using namespace std;

 struct my_struct{
     string value;
 };

 int main ()
 {
     map<long,deque<my_struct>> my_map;
     deque<my_struct> results;

my_struct entrya;
entrya.value = "today is a great day";

my_struct entryb;
entryb.value = "today is an okay day";

my_struct entryc;
entryc.value = "today is a bad day";


my_map[12345].push_back(entrya);
my_map[23456].push_back(entryb);
my_map[34567].push_back(entryc);


auto low = my_map.lower_bound (12345);
auto high = my_map.upper_bound (34567);

int num = 0;
for (auto it = low; it != high; ++it){
    ++num;
    results.insert(results.back(), it->second.begin(), it->second.end());
    //how to insert into my results deque?
}
cout << num << " found\n"; //3found

cout << "testing results\n";
for (int i = 0; i < results.size(); i++){
    cout << results[i].value << "\n";
}
return 0;

}

Edit: pic version https://gyazo.com/4960e067252f23ffafb924fa8e6693eb

Upvotes: 0

Views: 47

Answers (1)

paddy
paddy

Reputation: 63481

The lower_bound and upper_bound functions return a map iterator, so what you're really asking is how to access the object stored in a map via an iterator.

The iterator for maps points to a std::pair, where the first element is the key and the second element is the value. So, to get out your stored values, you use it->second.

Since the value type in the map is actually a std::deque<my_struct>, presumably you want to concatenate all the data into the single deque results. You can do this using std::deque::insert function as follows:

//how to insert into my results deque?
results.insert( result.end(), it->second.begin(), it->second.end() );

Upvotes: 2

Related Questions