[英]C++ vector with wrapping random access?
我真正想要的是C ++中的容器類,除了[]運算符具有包裝行為外,它與各種方式的STL向量類完全相同。 例如:
vector<int> myVec;
myVec.push_back(5);
myVec.push_back(10);
myVec.push_back(15);
cout << myVec[ 5] << endl; // would output 15
cout << myVec[ 1] << endl; // would output 10
cout << myVec[-2] << endl; // would output 10
這樣的容器是否已經存在,或者是否可以在向量模板中重載或重新定義[]運算符?
我已經看到了Boost循環緩沖區 ,它不會以這種方式運行。
這樣的容器是否已經存在
至少不在標准庫中。
是否有可能在向量模板中重載或重新定義[]運算符?
不,你不能重載或重新定義std::vector
[]運算符。
當然可以編寫一個帶有重載的T& operator[](int pos)
的包裝器,它具有您描述的行為。 像這樣:
T& operator[](int pos) {
std::vector<T>::size_type fancy_pos =
pos < 0 ? data.size() + pos
: pos - 1;
return data[fancy_pos];
}
在C ++中,容器的索引從0開始。
您可以將標准容器std :: vector包裝在一個類中並重載operator [],以便計算index = index % size()
如index = index % size()
或index %= size()
您正在尋找循環緩沖區或循環緩沖區。
提升他們:
他們有時遠遠優於如滾動自己用的std :: deque的表演,看到ASIO此示例:
我維護boost :: circular_buffer可能是你/應該想要的 - 因為它抽象了你通常想要的大多數任務的“如何”。 但是,創建自己的適配器類型很簡單:
#include <vector>
namespace mylib {
template <typename T, typename Container = std::vector<T> >
struct circular : Container {
using Container::Container;
using Container::operator =;
auto& operator[](int i) const {
// mixed signed/unsigned modulo is undefined
while (i<0) i += Container::size();
return Container::operator[](i % Container::size());
}
auto& operator[](int i) {
while (i<0) i += Container::size();
return Container::operator[](i % Container::size());
}
};
}
#include <iostream>
template <typename Whatever>
void test(Whatever const& data) {
std::cout << data[ 5] << ", "; // would output 15
std::cout << data[ 1] << ", "; // would output 10
std::cout << data[-2] << std::endl; // would output 10
}
#include <string>
#include <deque>
int main() {
test(mylib::circular<int> { 5, 10, 15 });
test(mylib::circular<std::string> { "five", "teen", "fiteen" });
test(mylib::circular<std::string, std::deque<std::string> > { "five", "teen", "fiteen" });
test(mylib::circular<int, std::deque<float> > { 5, 10, 15 });
}
打印:
15, 10, 10
fiteen, teen, teen
fiteen, teen, teen
15, 10, 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.