Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

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

...