How to insert all keys 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<std::string> keyvec;
     
    for (std::map<std::string, double>::iterator it = mp.begin(); it != mp.end(); it++) {
        keyvec.push_back(it->first);
    }
    
    print_vector(keyvec);
}
  
      
      
/*
run:
      
golden ratio
pi
tau
       
*/

 



answered Dec 26, 2024 by avibootz
edited 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<std::string> keyvec;
     
    for (auto const& m: mp) {
        keyvec.push_back(m.first);
    }
    
    print_vector(keyvec);
}
  
      
      
/*
run:
      
golden ratio
pi
tau
       
*/

 



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 ky = std::views::keys(mp);
    
    std::vector<std::string> keyvec{ ky.begin(), ky.end() };

    print_vector(keyvec);
}
  
      
      
/*
run:
      
golden ratio
pi
tau
       
*/

 



answered Dec 26, 2024 by avibootz

Related questions

...