std::map initializer list syntax ?

Augusdi發表於2016-10-10


C++11 supports the initialization of most containers by the simple syntax as follows:

std::set<int> = {3,4,6,34,2,6,78,8,5,0};
std::list<int> = {7,3,5,6,3,4,6,8};

 map also has a constructor that takes std::initializer_list<value_type>:

#include <map>
#include <string>
#include <iostream> 
int main() {
    std::map<int, std::string> m{{1, "Hello"}, {2, "world"}, {4, "!!!"}};
    for (std::map<int, std::string>::const_iterator it = m.begin(); it != m.end(); ++it) {
        std::cout << it->first << ' ' << it->second << '\n';
    }
}



相關文章