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 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 144 views
1 answer 66 views
1 answer 76 views
2 answers 161 views
161 views asked Apr 13, 2020 by avibootz
1 answer 167 views
...