gpt4 book ai didi

c++ - Boost.MultiArray 任意开始和结束索引

转载 作者:行者123 更新时间:2023-11-30 05:42:00 25 4
gpt4 key购买 nike

我有一个看起来像这样的类。目的是有一个任意的起点和终点,但运算符 [] 映射到索引 0 作为下限。

template <class T>
class Vec : public std::vector<T>
{
public:
Vec()
{
this->reserve(32000);
}

Vec(std::string s, int upperbound, int lowerbound)
{
SetBounds(s, upperbound, lowerbound);
}

void SetBounds(const std::string& s, int upperbound, int lowerbound)
{
mys = s;
ub = upperbound;
lb = lowerbound;

std::cout << "resizing Vec for symbol: "
<< symbol << " "
<< upperbound << " "
<< lowerbound << " "
<< upperbound - lowerbound << '\n';


try
{
this->resize(ub - lb + 1);
}
catch(std::exception& ex)
{
std::cout << "Resize Exception: " << ex.what() << "\n";
}
catch(...)
{
std::cout << "SetBounds exception" << "\n";
}
}
public:
T& operator[] (int idx)
{
try
{
//std::cout << idx << std::endl;

return this->at(idx - lb);
}
catch(std::exception& ex)
{
std::cout << "Access Exception: " << idx << " " << symbol << " " << ex.what() << '\n';
}
catch(...)
{
std::cout << "Access Exception: " << idx << " " << symbol << '\n';
}
}

private:
std::string mys;
int ub;
int lb;
};

我的问题是,对于 Boost.MultiArray 是否有等效的方法来做到这一点,以便可以为每个维度指定其自己的任意起始和结束索引?

最佳答案

是的。

http://www.boost.org/doc/libs/1_58_0/libs/multi_array/doc/user.html#sec_base

Setting The Array Base

In some situations, it may be inconvenient or awkward to use an array that is zero-based. the Boost.MultiArray components provide two facilities for changing the bases of an array. One may specify a pair of range values, with the extent_range type, to the extent_gen constructor in order to set the base value.

Example

typedef boost::multi_array<double, 3> array_type;
typedef boost::multi_array_types::extent_range range;
// OR typedef array_type::extent_range range;

array_type::extent_gen extents;

// dimension 0: 0-based
// dimension 1: 1-based
// dimension 2: -1 - based
array_type A(extents[2][range(1,4)][range(-1,3)]);

An alternative is to first construct the array normally then reset the bases. To set all bases to the same value, use the reindex member function, passing it a single new index value.

关于c++ - Boost.MultiArray 任意开始和结束索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com