在 C++ 中声明和使用 map<string, string>
declaring and using a map<string, string> in c++
我是一个C++初学者,试图声明和使用一个地图,但是尽管检查了教程和类似的问题,我还没有设法让它编译。
这是一个最小的例子,也在 ideone 中。
#include <iostream>
#include <bits/stl_map.h>
#include <string>
using namespace std;
int main() {
// error: ‘_Rb_tree’ does not name a type
map<string, string> dictionary;
// dictionary["value 1"] = "value 2";
// dictionary.insert(pair<string, string>("value 3", "value 4"));
// dictionary.insert(make_pair("value 5", "value 6"));
return 0;
}
下一个问题是插入数据,我已经看到了三种方法,如上面的评论。我应该选择哪一个?这些方式是否都等价?
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
map<string, string> dictionary;
dictionary["value 1"] = "value 2";
dictionary.insert(pair<string, string>("value 3", "value 4"));
dictionary.insert(make_pair("value 5", "value 6"));
return 0;
}
对我来说效果很好,你需要包括地图 header。它也找不到#include "bits/stl_map.h"。不知道是不是你的本地文件
个人比较喜欢第二种。有点笨重,但一目了然。
如果我是你,我不会担心性能差异,你可以随时对其进行基准测试,但最终这些东西不会成就或破坏你的代码。
见http://www.cplusplus.com/reference/map/map/operator[]
所以,选择你找到最多的那个 clear/convenient!
我是一个C++初学者,试图声明和使用一个地图,但是尽管检查了教程和类似的问题,我还没有设法让它编译。
这是一个最小的例子,也在 ideone 中。
#include <iostream>
#include <bits/stl_map.h>
#include <string>
using namespace std;
int main() {
// error: ‘_Rb_tree’ does not name a type
map<string, string> dictionary;
// dictionary["value 1"] = "value 2";
// dictionary.insert(pair<string, string>("value 3", "value 4"));
// dictionary.insert(make_pair("value 5", "value 6"));
return 0;
}
下一个问题是插入数据,我已经看到了三种方法,如上面的评论。我应该选择哪一个?这些方式是否都等价?
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
map<string, string> dictionary;
dictionary["value 1"] = "value 2";
dictionary.insert(pair<string, string>("value 3", "value 4"));
dictionary.insert(make_pair("value 5", "value 6"));
return 0;
}
对我来说效果很好,你需要包括地图 header。它也找不到#include "bits/stl_map.h"。不知道是不是你的本地文件
个人比较喜欢第二种。有点笨重,但一目了然。
如果我是你,我不会担心性能差异,你可以随时对其进行基准测试,但最终这些东西不会成就或破坏你的代码。
见http://www.cplusplus.com/reference/map/map/operator[]
所以,选择你找到最多的那个 clear/convenient!