STD对初始化
Std Pair Initialization
这是我第一次使用对,完全困惑。如何初始化一对以将其插入地图?
我应该为此提供一些标准库吗?
#include <string>
#include <map>
using namespace std;
class Roads
{
public:
map< pair<string,string>, int > Road_map;
void AddRoad( string s, string d )
{ int b = 2 ; Road_map.insert( pair<s,d>, b) ; } //pair<s,d> is wrong here.
};
您可以使用std::make_pair
:
Road_map[make_pair(s, d)] = b;
另外,您可以像这样构造std::pair
:
Road_map[pair<string,string>(s,d)] = b;
std::make_pair
方法可以节省您必须命名s
和d
的类型。
请注意,此处适当的功能是operator[]
,而不是insert
。std::map::insert
采用单个参数,该参数是包含要插入的密钥和值的std::pair
。您必须这样做:
Road_map.insert(pair<const pair<string,string>, int>(make_pair(s, d), b);
您可以使用typedef
使它更漂亮:
typedef map<pair<string,string>, int> map_type;
Road_map.insert(map_type::value_type(map_type::key_type(s, d), b));
而不是使用std::make_pair
。喜欢:
#include <string>
using namespace std;
class Roads
{
public:
map< pair<string,string>, int > Road_map;
void AddRoad( string s, string d )
{
int b = 2 ;
Road_map[make_pair(s,d)] = b;
}
};
对于map<K, T>
,value_type
实际上是pair<K const, T>
。但是,最简单的访问方法是使用Typedefs:
typedef std::pair<std::string, std::string> string_pair;
typedef std::map<string_pair, int> map_type;
// ...
Road_map.insert(map_type::value_type(map_type::key_type(s, d), b));
在C 11中,您可以使用更轻松的emplace
接口:
Road_map.emplace(map_type::key_type(s, d), b);
相关文章:
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 使用通用值初始化 std::map,不重复
- 初始化 std::vector 替换为单大括号而不是双大括号
- 在构造函数中使用可变参数初始化 std::tuple
- 使用大括号初始化 std::vector 使用初始值设定项列表
- 为什么初始化 std::vector 时不能使用模板整数?
- 如何在构造函数参数中初始化"std::set"?
- 初始化 std::数组 of Eigen::Map
- 我可以列表初始化 std::vector 并完美转发元素吗?
- 在 C++20 之前和之后初始化 std::atomic
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 如何初始化 std::向量的映射?
- 如何在构造函数初始值设定项列表中使用 n 个元素初始化 std::vector<std::time_t>
- 使用范围库初始化 std::vector
- 如何在类的初始值设定项列表中初始化 std::array,而不对数组的大小进行硬编码
- 我是否需要在构造函数中显式初始化 std::unique_ptr?
- 如何使用派生类类型数据初始化 std::shared_ptr?
- 为什么我必须在初始化 std::array<SomeStruct, size> 时指定每个项目的类型C++
- 根据指针条件初始化std::vector
- 正在使用unique_ptr初始化std::vector