How to insert all values from a std::map into a vector in C++

3 Answers

0 votes
#include <map>
#include <vector>
#include <string>
#include <iostream>

template <class T>
void print_vector(const std::vector<T>& v) {
     for (T n : v) {
          std::cout << n << "\n";
    }
}
 
int main()
{
    std::map<std::string, double> mp{{ "pi", 3.14 }, { "tau", 6.28 }, { "golden ratio", 1.6 }};
     
    std::vector<double> valuevec;
     
    for (std::map<std::string, double>::iterator it = mp.begin(); it != mp.end(); it++) {
        valuevec.push_back(it->second);
    }
    
    print_vector(valuevec);
}
  
      
      
/*
run:
      
1.6
3.14
6.28
       
*/

 



answered Dec 26, 2024 by avibootz
0 votes
#include <map>
#include <vector>
#include <string>
#include <iostream>

template <class T>
void print_vector(const std::vector<T>& v) {
     for (T n : v) {
          std::cout << n << "\n";
    }
}
 
int main()
{
    std::map<std::string, double> mp{{ "pi", 3.14 }, { "tau", 6.28 }, { "golden ratio", 1.6 }};
     
    std::vector<double> valuevec;
     
    for (auto const& m: mp) {
        valuevec.push_back(m.second);
    }
    
    print_vector(valuevec);
}
  
      
      
/*
run:
      
1.6
3.14
6.28
       
*/

 



answered Dec 26, 2024 by avibootz
0 votes
// c++20
#include <map>
#include <ranges>
#include <vector>
#include <string>
#include <iostream>

template <class T>
void print_vector(const std::vector<T>& v) {
     for (T n : v) {
          std::cout << n << "\n";
    }
}
 
int main()
{
    std::map<std::string, double> mp{{ "pi", 3.14 }, { "tau", 6.28 }, { "golden ratio", 1.6 }};
    
    auto vl = std::views::values(mp);
    
    std::vector<double> valuesvec{ vl.begin(), vl.end() };

    print_vector(valuesvec);
}
  
      
      
/*
run:
      
1.6
3.14
6.28
       
*/

 



answered Dec 26, 2024 by avibootz

Related questions

3 answers 171 views
1 answer 79 views
1 answer 94 views
2 answers 182 views
182 views asked Apr 13, 2020 by avibootz
1 answer 181 views
...