簡體   English   中英

C ++中具有消極索引的類似數組的數據結構

[英]Array like data structure with negetive index in C++

我需要一個結構來跟蹤某些項目的存在。 我只想取一個數組a0 .... aN並將元素標記為a [0] = 0,a [1] = 0,a [2] = 1 ........( a[i]=1如果元素存在,則a[i]=1如果元素不存在,則a[i]=0 )。 但是項目的范圍是-1000到+1000。 可以通過將負數范圍設置為1001到2000來完成。我需要知道c ++中是否還有其他數據結構可以像數組一樣使用負索引。 感謝您的時間。

map僅用於此目的,以具有任何基本/用戶定義的數據類型的key/index 請參閱-http: //www.cplusplus.com/reference/map/map/

您的案例示例:

#include <iostream>
#include <map>
#include <string>

int main ()
{
  std::map<int, int> mymap;

  mymap[-1]=1;
  mymap[-2]=0;
  mymap[-3]=1;

  std::cout << mymap[-1] << '\n';
  std::cout << mymap[-2] << '\n';
  std::cout << mymap[-3] << '\n';

  return 0;
}

字符示例:

#include <iostream>
#include <map>
#include <string>

int main ()
{
  std::map<char,std::string> mymap;

  mymap['a']="an element";
  mymap['b']="another element";
  mymap['c']=mymap['b'];

  std::cout << "mymap['a'] is " << mymap['a'] << '\n';
  std::cout << "mymap['b'] is " << mymap['b'] << '\n';
  std::cout << "mymap['c'] is " << mymap['c'] << '\n';
  std::cout << "mymap['d'] is " << mymap['d'] << '\n';

  std::cout << "mymap now contains " << mymap.size() << " elements.\n";

  return 0;
}

您將創建一個支持-ve索引的數據結構。 在將索引存儲在數組中時,只需向索引添加偏移量即可。

class MyArray {
    int *arr;
    public:
    MyArray(int offset) {
        arr = new int[2*offset]; // size must to double the offset
    }
    ~MyArray(){
        delete arr;
    }
    void add(int index, int val) {
        arr[index + offset] = val;
    }
    void get(int index) {
        return arr[index + offset];
    }
}

然后,您可以只使用您的類來添加和獲取具有任何索引的元素。

MyArray arr = MyArray(1000); // pass max -ve index as offset
arr.add(10, -150);
cout << arr.get(100);

我需要一個結構來跟蹤某些項目的存在。

如果您想要的是設置語義,請使用設置數據結構。 無需實現自定義數組包裝器。 您可以為此使用std::set (或std::unordered_set )。 請記住, “過早的優化是萬惡之源”

插入其中的值,忽略缺失的值。 無需擔心負面指數。 您可以使用std::set::find()std::set::count()方法檢查項目的存在。 查看文檔以查找一些示例代碼。

如果以后發現這是對性能至關重要的優化,則可以隨時使用基於位數組編寫的數據結構替換std::set<int> 如果不是這樣,過早地這樣做可能會成為不必要的意外錯誤來源和浪費時間。

以供參考:

最有效的方法將只是移動數組索引,以使所有索引均為非負數。 就您而言,只需使用a[i+1000]就足夠了。

如果您確實需要使用負索引,則也可以。 C / C ++使用表的地址計算數組元素的內存地址,然后向其添加索引值。 使用負數僅指向表之前放置的存儲區(通常不希望這樣做)。

int a[2001];
int *b = &a[1000];
int x = b[-1000]; // This points to 1000 places before b which translates to a[0] (valid place)

另一種方法是使用容器。 然后,任何數字都可以轉換為字符串並存儲在適當的容器中。

我認為@Rajev的答案幾乎可以。 我剛剛用std::vector替換了普通數組。 因此,存儲器管理是安全的,並且復制和移動容易。

template <typname T>
class MyArray {
  private:
    std::vector<T> arr;
  public:
    MyArray(int offset) {
        arr.resize(2*offset); // size must to double the offset
    }

    void set(int index, int val) {
        arr[index + offset] = val;
    }

    void get(int index) {
        return arr[index + offset];
    }
}

您可以通過重載MyArray的operator []來進一步擴展此功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM