簡體   English   中英

訪問struct元素。 是否可以像矢量一樣訪問?

[英]Access to the struct elements. Is it possible to access like a vector?

我使用結構有以下示例(簡化):

#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;

struct s_str
{
    int a=1,b=2,c=3;
};

int main(void)
{
    s_str str;
    int sel;    
    srand(time(NULL));                 //initialize random seed
    sel = rand() % (3);                //generate a random number between 0 and 2

    cout << "sel: " << sel << endl;     
    cout << "str: " << str.??? << endl;//I was wondering to output a, b or c 
    return 0;                          //depending whether sel=0,1,2respectively.           
 }

當定義struct“str”時,我們可以使用opertor“。”訪問每個元素。 后跟元素的名稱。 例如,“str.c”將給出數字3。

但是在這個例子中,我們不知道編程時輸出的“str”元素,因為它是由sel隨機選擇的。

我不知道如何輸出“str。???” 來自sel number,即,如果sel = 0,str.a,如果sel = 1,則str.b,如果sel = 3,則str.c.

我嘗試了類似“str。[sel]”的東西,但它沒有用。 你能幫助我嗎?

PD:我不想太煩,但是如何解決同樣的問題,但現在假設a,b和c有不同的變量類型。 例如:

int a=1,b=2;
string c="hola";  

我嘗試用兩個運算符來完成它,但它沒有編譯,因為它們被重載了。

如前所述,如果不提供某個映射和索引操作符,則無法執行此操作。 以下應該運作良好

struct s_str
{
    int a=1,b=2,c=3;
    int& operator[](int index) {
        switch(index) {
            case 0:
                return a;
            case 1:
                return b;
            case 2:
                return c;
            default:
                throw std::out_of_range("s_str: Index out of range.");
            break;
        }   
    }
};

int main() {
    s_str s;
    cout << s[0] << ", " << s[1] << ", " << s[2] << endl;
    // cout << s[42] << endl; // Uncomment to see it fail.
    return 0;
}

一般來說,沒有。

如果結構元素的唯一區別特征是它們的索引,則在結構中定義向量或數組。

如果有時想要按名稱引用元素,有時需要按位置引用元素,請為結構定義operator []( int )

最簡單的方法是,如果你的結構中只有幾個整數:

struct s_str
{
    int a = 1, b = 2, c = 3;
    int& operator[] (size_t t) {
        assert(t<3); // assumption for the following to return a meaningful value
        return (t == 0 ? a : (t == 1 ? b : c));
    }
};

你可以訪問

   cout << "str: " << str[sel] << endl;

你甚至可以使用int來分配,因為它是通過引用:

str[sel] = 9; 
cout << "a,b,c=" << str.a << "," << str.b << "," << str.c << endl;

暫無
暫無

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

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