我在这里读到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;
}
输出:
Hello from the no argument constructor
Size of container in key 2 = 0
New Size of container in key 2 = 1
我可以从上面的输出中看到调用了无参数构造函数。
我的问题是:有没有办法调用 map 的 Value(s) 的单参数构造函数?
谢谢你