数组可以简单有效地转换为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
,而无需迭代成员?这看起来像一个不寻常的函数签名,但在我的特定情况下,这些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;
*/
}
再次声明,我并不是用遍历数组中每个成员的代码来寻找答案……我可以自己写。如果不能用更好的方法来解决,我会接受这个答案。
1条答案
按热度按时间1l5u6lss1#
下面的代码对我来说很好:
如果你有C++03,你可以使用
完整demo
Live On Coliru