2015-03-30 88 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

相关问题