rah*_*man 3 c++ constructor stdmap
我在这里读到,如果密钥不存在,std :: map operator []会创建一个对象!
首先,我可以知道在哪里可以找到这个索赔的参考资料吗?(虽然我知道这是真的)
接下来,想象下面的代码片段:
#include <iostream>
#include <vector>
#include<map>
class Value {
//..
int some_member; //is used for any purpose that you like
std::vector<int> some_container;
public:
Value(int some_member_) :
some_member(some_member_) {
std::cout << "Hello from the one-argument constructor" << std::endl;
}
Value() {
std::cout << "Hello from the no argument constructor" << std::endl;
}
void add(int v) {
some_container.push_back(v);
}
int getContainerSize()
{
return some_container.size();
}
//...
};
//and somewhere in the code:
class A {
public:
std::map<int, Value> myMap;
void some_other_add(int j, int k) {
myMap[j].add(k);
}
int getsize(int j)
{
return myMap[j].getContainerSize();
}
};
//and the program actually works
int main() {
A a;
std::cout << "Size of container in key 2 = " << a.getsize(2) << std::endl;
a.some_other_add(2, 300);
std::cout << "New Size of container in key 2 = " << a.getsize(2) << std::endl;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Hello from the no argument constructor
Size of container in key 2 = 0
New Size of container in key 2 = 1
Run Code Online (Sandbox Code Playgroud)
我可以从上面的输出中看到,调用了无参数构造函数.
我的问题是:有没有办法调用map的Value(s)的单参数构造函数?
谢谢
我可以在哪里找到这个索赔的参考资料吗?
这就是C++ 11标准所要求的.根据第23.4.4.3段:
Run Code Online (Sandbox Code Playgroud)T& operator[](const key_type& x);1 效果:如果
x地图中没有等效的键,则插入value_type(x, T())到地图中.[...]
Run Code Online (Sandbox Code Playgroud)T& operator[](key_type&& x);5 效果:如果
x地图中没有等效的键,则插入value_type(std::move(x), T())到地图中.
关于第二个问题:
有没有办法调用map的Value(s)的单参数构造函数?
你可以在C++ 03中做到这一点:
void some_other_add(int j, int k) {
myMap.insert(std::make_pair(j, Value(k)));
}
Run Code Online (Sandbox Code Playgroud)
并使用emplace()C++ 11中的成员函数:
myMap.emplace(j, k);
Run Code Online (Sandbox Code Playgroud)