Dag*_*bit 4 c++ arrays vector map
数组可以std::vector轻松高效地转换为:
template <typename T, int N>
vector<T> array_to_vector(T(& a)[N]) {
return vector<T>(a, a + sizeof(a) / sizeof(T));
}
Run Code Online (Sandbox Code Playgroud)
有没有类似的方法将二维数组转换为一个std::map不迭代成员?这看起来像一个不寻常的函数签名,但在我的特定情况下,这些映射中的键和值将是相同的类型.
template <typename T, int N>
map<T, T> array_to_map(T(& a)[N][2]) {
// ...?
}
Run Code Online (Sandbox Code Playgroud)
这是我为这个问题整理的测试代码.它将按原样编译和运行; 目标是让它在未main注释的情况下使用块注释进行编译.
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
template <typename T, int N>
vector<T> array_to_vector(T(& a)[N]) {
return vector<T>(a, a + sizeof(a) / sizeof(T));
}
template <typename T, int N>
map<T, T> array_to_map(T(& a)[N][2]) {
// This doesn't work; members won't convert to pair
return map<T, T>(a, a + sizeof(a) / sizeof(T));
}
int main() {
int a[] = { 12, 23, 34 };
vector<int> v = array_to_vector(a);
cout << v[1] << endl;
/*
string b[][2] = {
{"one", "check 1"},
{"two", "check 2"}
};
map<string, string> m = array_to_map(b);
cout << m["two"] << endl;
*/
}
Run Code Online (Sandbox Code Playgroud)
同样,我不是在寻找代码的答案,这些代码遍历数组的每个成员......我可以自己编写.如果不能以更好的方式完成,我会接受这个答案.
以下工作对我来说很好:
template <typename T, int N>
map<T, T> array_to_map(T(& a)[N][2])
{
map<T, T> result;
std::transform(
a, a+N, std::inserter(result, result.begin()),
[] (T const(&p)[2]) { return std::make_pair(p[0], p[1]); }
);
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果你有C++ 03,你可以使用
template <typename T>
static std::pair<T, T> as_pair(T const(&p)[2]) {
return std::make_pair(p[0], p[1]);
}
template <typename T, int N>
map<T, T> array_to_map(T(& a)[N][2]) {
map<T, T> result;
std::transform(a, a+N, std::inserter(result, result.begin()), as_pair<T>);
return result;
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
template <typename T, int N>
vector<T> array_to_vector(T const(& a)[N]) {
return vector<T>(a, a + sizeof(a) / sizeof(T));
}
template <typename T>
static std::pair<T, T> as_pair(T const(&p)[2])
{
return std::make_pair(p[0], p[1]);
}
template <typename T, int N>
map<T, T> array_to_map(T const(& a)[N][2])
{
map<T, T> result;
// C++03: std::transform(a, a+N, std::inserter(result, result.begin()), as_pair<T>);
std::transform(
a, a+N, std::inserter(result, result.begin()),
[] (T const(&p)[2]) { return std::make_pair(p[0], p[1]); }
);
return result;
}
int main() {
int a[] = { 12, 23, 34 };
vector<int> v = array_to_vector(a);
cout << v[1] << endl;
const string b[][2] = {
{"one", "check 1"},
{"two", "check 2"}
};
map<string, string> m = array_to_map(b);
cout << m["two"] << endl;
}
Run Code Online (Sandbox Code Playgroud)