简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:理解C++之三种key-value键值生成方式。
2.应用实例
<1>.map方式
#include <iostream>
#include <vector>
#include <map>
int main() {
std::map<std::string, std::string> keyValueMap;
//v1.0
keyValueMap = { {"name", "张三"}, {"age", "20"}, {"country", "中国"} };
// 遍历map并打印键值对
for (const auto& pair : keyValueMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
std::cout << std::endl;
keyValueMap.clear();
//v2.0
keyValueMap.insert({"name","李四"});
keyValueMap.insert({"age","18"});
keyValueMap.insert({"country","China"});
//遍历map并打印键值对
for (const auto& pair : keyValueMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
std::cout << std::endl;
return 0;
}
<2>.vector + pair方式
#include <iostream>
#include <vector>
#include <map>
int main() {
//vector + pair
//v1.0
std::vector<std::pair<std::string, std::string>> keyValuevt;
keyValuevt = { {"name", "王五"}, {"age", "22"}, {"country", "中国"} };
for (const auto& vv : keyValuevt) {
std::cout << vv.first << ": " << vv.second << std::endl;
}
std::cout << std::endl;
keyValuevt.clear();
//v2.0
keyValuevt.push_back({"name","Tom"});
keyValuevt.push_back({"age","10"});
keyValuevt.push_back({"countyr","China"});
for (const auto& vv : keyValuevt) {
std::cout << vv.first << ": " << vv.second << std::endl;
}
return 0;
}
<3>.vector + make_pair方式
#include <iostream>
#include <vector>
#include <map>
int main() {
std::vector<std::pair<std::string, std::string>> keyValuevt;
//vector + make_pair
//v1.0
keyValuevt.push_back(std::make_pair("name", "六五"));
keyValuevt.push_back(std::make_pair("age", "21"));
keyValuevt.push_back(std::make_pair("country", "中国"));
for (const auto& vv : keyValuevt) {
std::cout << vv.first << ": " << vv.second << std::endl;
}
std::cout << std::endl;
keyValuevt.clear();
//v2.0
keyValuevt.push_back({"name","Tom"});
keyValuevt.push_back({"age","10"});
keyValuevt.push_back({"countyr","China"});
for (const auto& vv : keyValuevt) {
std::cout << vv.first << ": " << vv.second << std::endl;
}
return 0;
}