【发布时间】:2012-09-28 03:54:44
【问题描述】:
可以轻松高效地将数组转换为std::vector:
template <typename T, int N>
vector<T> array_to_vector(T(& a)[N]) {
return vector<T>(a, a + sizeof(a) / sizeof(T));
}
是否有类似的方法可以将二维数组转换为std::map 而无需遍历成员?这看起来像是一个不寻常的函数签名,但在我的特殊情况下,这些映射中的键和值将属于同一类型。
template <typename T, int N>
map<T, T> array_to_map(T(& a)[N][2]) {
// ...?
}
这是我为这个问题整理的测试代码。它将按原样编译和运行;目标是让它与 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;
*/
}
同样,我不是在寻找对数组的每个成员进行迭代的代码的答案...我可以自己编写。如果不能以更好的方式完成,我会接受它作为答案。
【问题讨论】:
-
您可以编写一个使用双精度数组的自定义迭代器,但这会有用吗?肯定会有更多的代码。
-
@KerrekSB 我不确定它是否有用,我不妨在函数内部进行迭代。我想知道是否有某种方法可以通过将数组转换为 std::pair 或利用 STL 中我不知道的其他东西来做到这一点。
-
也许 std::copy 带有专门的 insert_iterator?