以下对我来说效果很好:
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;
}
如果你有 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;
}
完整演示
住在科里鲁 http://coliru.stacked-crooked.com/a/a5bafcdf8793dd5a
#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;
}