我会创建一个类
- 将任意指定索引转换为从 0 开始的增量索引
- 包装一维数组,以便您可以使用转换后的索引将其作为二维数组访问
一个工作示例看起来像这样
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iterator>
#include <cassert>
using namespace std;
class DataFrame
{
vector<int> data;
public:
typedef vector<ssize_t> idx_t;
private:
idx_t rowIdx;
idx_t colIdx;
public:
DataFrame(const idx_t &rowIdx, const idx_t &colIdx)
: data(rowIdx.size() * colIdx.size())
, rowIdx(rowIdx)
, colIdx(colIdx)
{
assert(is_sorted(rowIdx.begin(), rowIdx.end()));
assert(is_sorted(colIdx.begin(), colIdx.end()));
}
int& operator()(int i, int j)
{
idx_t::iterator itI, itJ;
itI = lower_bound(rowIdx.begin(), rowIdx.end(), i);
if(rowIdx.end() == itI || i != *itI) throw out_of_range("could not find specified row");
itJ = lower_bound(colIdx.begin(), colIdx.end(), j);
if(colIdx.end() == itJ || j != *itJ) throw out_of_range("could not find specified col");
return data[distance(rowIdx.begin(), itI)*colIdx.size() +
distance(colIdx.begin(), itJ)];
}
vector<int> & getData() { return data; }
};
int main()
{
DataFrame::idx_t rI, cI;
rI.push_back(3);
rI.push_back(5);
cI.push_back(2);
cI.push_back(3);
cI.push_back(10);
DataFrame df(rI, cI);
df(3,2) = 1;
df(3,3) = 2;
df(3,10) = 3;
df(5,2) = 4;
df(5,3) = 5;
df(5,10) = 6;
ostream_iterator<int> out_it(cout, ", ");
copy(df.getData().begin(), df.getData().end(), out_it);
cout << endl;
return 0;
}
每行/列的任意索引在向量中指定。为了保持一些性能,代码要求索引单调递增。 (如果您有 C++11,则在 ctor 中进行检查;如果您没有 C++11,则没有 is_sorted 函数。此外,此代码不会验证任意的唯一性指数。)
当您访问数据时,它只是对每个索引向量进行二进制搜索,以找到向量中与任意索引匹配的位置,并将该位置用作基础数据的对应索引。有一个从 2D 索引到 1D 索引的简单转换。
如果您需要担心的话,您可能需要检查我的索引错误检查对于所有坏/好索引组合是否正确。
我会留给您在const 访问器、各种构造函数等方面添加更多的健壮性/功能。如果您想将其推广到除 2 之外的维度数组,我建议您为只需将任意索引转换为基于 0 的索引,这将消除我的一些代码重复。还有其他方法可以将任意索引转换为基于 0 的索引,例如像其他人建议的那样使用map。但是在这种情况下,存在一些问题,例如 map 的创建者必须确保如果有 10 列,则 [0, 10) 中的每个索引作为映射中的值恰好出现一次。