c++ 给std::map<int,std::string>赋值
时间: 2023-11-18 15:53:15 浏览: 79
可以使用 insert 函数或者 [] 运算符来给 std::map<int,std::string> 赋值。具体实现如下:
```c++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> myMap;
// 使用 insert 函数赋值
myMap.insert(std::make_pair(1, "hello"));
myMap.insert(std::make_pair(2, "world"));
// 使用 [] 运算符赋值
myMap[3] = "C++";
// 遍历 map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
1: hello
2: world
3: C++
```
相关问题
std::map::find
`std::map::find`是C++标准库中`std::map`容器提供的成员函数之一,用于在`std::map`中查找指定的键,并返回指向该键值对的迭代器。
以下是`std::map::find`函数的语法:
```cpp
iterator find (const key_type& key);
```
其中,`key_type`是`std::map`中键的数据类型。`key`是要查找的键。
以下是一个示例:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
std::map<int, std::string>::iterator it = myMap.find(2);
if (it != myMap.end()) {
std::cout << "Key found! Value: " << it->second << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
return 0;
}
```
在上述示例中,我们创建了一个`std::map<int, std::string>`类型的`myMap`对象,并插入了几个键值对。然后,我们使用`find`函数查找键为2的元素,并将返回的迭代器赋值给`it`。如果找到了键为2的元素,则输出相应的值;如果没有找到,则输出"Key not found!"。
运行程序时,输出结果为:
```
Key found! Value: Two
```
这表示在`myMap`中成功找到了键为2的元素,并输出了对应的值。
typedef struct PIDInfo { FC_INT32 m_pid; FC_INT32 m_ppid; PIDInfo() :m_pid(-1) , m_ppid(-1) {} } STPIDInfo; typedef std::unordered_set<STPIDInfo> VECRUNPID; std::map<FC_STRING, VECRUNPID> m_mRunProcCache;如何添加一个k
要向`m_mRunProcCache`中添加一个键值对,即添加一个新的`FC_STRING`类型的键和一个`VECRUNPID`类型的值,可以使用`std::map`的`insert()`函数来完成。具体操作如下:
```c++
STPIDInfo pidInfo;
pidInfo.m_pid = 123;
pidInfo.m_ppid = 456;
FC_STRING key = "newKey";
auto it = m_mRunProcCache.find(key); // 查找key是否已经存在
if (it == m_mRunProcCache.end()) { // 如果key不存在
VECRUNPID vec;
vec.insert(pidInfo); // 将pidInfo插入vec中
m_mRunProcCache.insert(std::make_pair(key, vec)); // 将key和vec插入map中
} else { // 如果key已经存在
it->second.insert(pidInfo); // 将pidInfo插入对应的vec中
}
```
这段代码首先创建了一个`STPIDInfo`类型的对象`pidInfo`,并对其成员变量赋值。然后将要插入的键值对的键存储在`key`中。接着使用`std::map`的`find()`函数查找`key`是否已经存在,如果不存在,则创建一个新的`VECRUNPID`类型的向量`vec`,将`pidInfo`插入其中,并使用`std::make_pair()`函数创建一个键值对,将`key`和`vec`插入到`m_mRunProcCache`中。如果`key`已经存在,则直接在对应的`VECRUNPID`类型的向量中插入`pidInfo`即可。