2015-03-30 86 views
0

因此,可以說我有一個這樣的結構:添加結構到一個數組

struct example_structure 
{ 
int thing_one; 
int thing_two; 
}; 

我也有我試圖填補這些結構的空數組。我試圖將它們添加如下,但它似乎並不奏效:

array[i].thing_one = x; 
array[i].thing_two = y; 

相反的,這是有申報類型example_structure的變量,然後添加到陣列的方法是什麼?

+0

什麼類型'x'和'y'? – 2015-03-30 18:13:52

+2

請發佈一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) – NathanOliver 2015-03-30 18:14:08

+0

「它似乎沒有工作」是什麼意思? 'example_structure example; ...;數組[i] = example;'是完全有效的,但顯然你在這裏有更深的問題。 – 2015-03-30 18:14:39

回答

1

你可以寫簡單

array[i] = { x, y }; 

或者你可以有結構型的獨立變量。例如

struct example_structure obj = { x, y }; 
array[i] = obj; 
+0

這不會'工作。該OP說,「我也有一個空的陣列,我正試圖用這些結構填補。」 – 2015-03-30 18:18:36

+0

如果你這樣做,只要你改變'struct'中成員的順序就更新你的代碼。您可能需要向'struct'添加註釋,以指示不應更改順序。 C++有一個習慣,就是提供很多機會將語義從水中排除出去。 – 2015-03-30 18:18:55

+0

@R Sahu我不明白爲什麼它不能工作。 – 2015-03-30 18:21:16

4

使用載體。他們可以根據需要擴展。

#include <iostream> 
#include <vector> 

int main() 
{ 
    struct example_structure 
    { 
     int thing_one; 
     int thing_two; 
    }; 

    std::vector<example_structure> data; 
    for (int i = 0; i < 3; i++) 
    { 
     data.push_back({i, i * 2}); 
    } 

    for (const auto& x : data) 
    { 
     std::cout << x.thing_one << " " << x.thing_two << "\n"; 
    } 
} 

活生生的例子: http://ideone.com/k56tcQ

+0

如果你這樣做,只要你改變'struct'中成員的順序就更新你的代碼。您可能需要向'struct'添加註釋,以指示不應更改成員順序,特別是如果兩個成員都是相同類型的成員。 C++有一個習慣,就是提供很多機會將語義從水中排除出去。爲了完整性,可能還需要聲明一個'example_structure example;'並在'.push_back(example)'前面初始化它。 – 2015-03-30 18:20:08

+1

'emplace_back'如何? :-) – AndyG 2015-03-30 18:20:43

相關問題