C++ 结构体初始化向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8067338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:57:31  来源:igfitidea点击:

Vector of structs initialization

c++vectorstructpush-back

提问by SRN

I want know how I can add values to my vector of structs using the push_backmethod

我想知道如何使用该push_back方法将值添加到我的结构向量中

struct subject
{
  string name;
  int marks;
  int credits;
};


vector<subject> sub;

So now how can I add elements to it?

那么现在我该如何添加元素呢?

I have function that initializes string name(subject name to it)

我有初始化字符串名称的函数(主题名称)

void setName(string s1, string s2, ...... string s6)
{
   // how can i set name too sub[0].name= "english", sub[1].name = "math" etc

  sub[0].name = s1 // gives segmentation fault; so how do I use push_back method?

  sub.name.push_back(s1);
  sub.name.push_back(s2);
  sub.name.push_back(s3);
  sub.name.push_back(s4);

  sub.name.push_back(s6);

}

Function call

函数调用

setName("english", "math", "physics" ... "economics");

回答by John Humphreys - w00te

Create vector, push_back element, then modify it as so:

创建向量,push_back 元素,然后像这样修改它:

struct subject {
    string name;
    int marks;
    int credits;
};


int main() {
    vector<subject> sub;

    //Push back new subject created with default constructor.
    sub.push_back(subject());

    //Vector now has 1 element @ index 0, so modify it.
    sub[0].name = "english";

    //Add a new element if you want another:
    sub.push_back(subject());

    //Modify its name and marks.
    sub[1].name = "math";
    sub[1].marks = 90;
}

You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

在该索引处的向量中存在元素之前,您无法使用 [#] 访问向量。此示例填充 [#],然后对其进行修改。

回答by Sebastian Mach

If you want to use the new current standard, you can do so:

如果你想使用新的现行标准,你可以这样做:

sub.emplace_back ("Math", 70, 0);

or

或者

sub.push_back ({"Math", 70, 0});

These don't require default construction of subject.

这些不需要subject.

回答by Rikard S?derstr?m

You may also which to use aggregate initialization from a braced initialization list for situations like these.

对于此类情况,您还可以使用花括号初始化列表中的聚合初始化。

#include <vector>
using namespace std;

struct subject {
    string name;
    int    marks;
    int    credits;
};

int main() {
    vector<subject> sub {
      {"english", 10, 0},
      {"math"   , 20, 5}
    };
}

Sometimes however, the members of a struct may not be so simple, so you must give the compiler a hand in deducing its types.

然而,有时结构体的成员可能并不那么简单,因此您必须帮助编译器推断其类型。

So extending on the above.

所以在上面延伸。

#include <vector>
using namespace std;

struct assessment {
    int   points;
    int   total;
    float percentage;
};

struct subject {
    string name;
    int    marks;
    int    credits;
    vector<assessment> assessments;
};

int main() {
    vector<subject> sub {
      {"english", 10, 0, {
                             assessment{1,3,0.33f},
                             assessment{2,3,0.66f},
                             assessment{3,3,1.00f}
                         }},
      {"math"   , 20, 5, {
                             assessment{2,4,0.50f}
                         }}
    };
}

Without the assessmentin the braced initializer the compiler will fail when attempting to deduce the type.

如果没有花assessment括号初始化器,编译器在尝试推断类型时将失败。

The above has been compiled and tested with gcc in c++17. It should however work from c++11 and onward. In c++20 we may see the designator syntax, my hope is that it will allow for for the following

上面已经在c++17中用gcc编译和测试过。然而,它应该从 c++11 开始工作。在 c++20 中,我们可能会看到指示符语法,我希望它允许以下内容

  {"english", 10, 0, .assessments{
                         {1,3,0.33f},
                         {2,3,0.66f},
                         {3,3,1.00f}
                     }},

source: http://en.cppreference.com/w/cpp/language/aggregate_initialization

来源:http: //en.cppreference.com/w/cpp/language/aggregate_initialization

回答by Alok Save

You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the []operator on std::vector.
[]does not add elements if none exists, but it causes an Undefined Behaviorif the index is invalid.

您不能通过下标访问空向量的元素。
使用[]on 运算符时,请始终检查向量是否为空且索引是否有效std::vector
[]如果不存在元素,则不添加元素,但如果索引无效,则会导致未定义行为

You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()

您应该创建结构的临时对象,填充它,然后将其添加到向量中,使用 vector::push_back()

subject subObj;
subObj.name = s1;
sub.push_back(subObj);

回答by Onk_r

After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

查看接受的答案后,我意识到如果知道所需向量的大小,那么我们必须使用循环来初始化每个元素

But I found new to do this using default_structure_element like following...

但我发现新的使用 default_structure_element 来做到这一点,如下所示......

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

typedef struct subject {
  string name;
  int marks;
  int credits;
}subject;

int main(){
  subject default_subject;
  default_subject.name="NONE";
  default_subject.marks = 0;
  default_subject.credits = 0;

  vector <subject> sub(10,default_subject);         // default_subject to initialize

  //to check is it initialised
  for(ll i=0;i<sub.size();i++) {
    cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
  } 
}

Then I think its good to way to initialize a vector of the struct, isn't it?

然后我认为初始化结构向量的方法很好,不是吗?