结构初始化向量

发布于 2024-12-14 12:23:54 字数 689 浏览 2 评论 0原文

我想知道如何使用 push_back 方法向结构向量添加值

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


vector<subject> sub;

那么现在如何向其添加元素呢?

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

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);

}

函数调用

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

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

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");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小耗子 2024-12-21 12:23:55

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

#include <vector>
using namespace std;

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

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

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

所以在上面的基础上进行扩展。

#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}
                         }}
    };
}

如果没有花括号初始化器中的评估,编译器在尝试推导类型时将会失败。

以上已在c++17中用gcc编译并测试。然而,它应该从 c++11 及更高版本开始工作。在 c++20 中,我们可能会看到指示符语法,我希望它将允许以下

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

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

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 assessment in the braced initializer the compiler will fail when attempting to deduce the type.

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

  {"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

这个俗人 2024-12-21 12:23:55

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

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

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

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 Behavior if the index is invalid.

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

subject subObj;
subObj.name = s1;
sub.push_back(subObj);
吻泪 2024-12-21 12:23:55

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

但我发现新的方法可以使用 default_struct_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;
  } 
}

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

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...

#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?

不奢求什么 2024-12-21 12:23:54

创建向量、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;
}

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

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

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.

幽梦紫曦~ 2024-12-21 12:23:54

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

sub.emplace_back ("Math", 70, 0); // requires a fitting constructor, though

sub.push_back ({"Math", 70, 0}); // works without constructor

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

sub.emplace_back ("Math", 70, 0); // requires a fitting constructor, though

or

sub.push_back ({"Math", 70, 0}); // works without constructor

.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文