Vector of Structs Initialization

Vector of structs initialization

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.

c++ right way to initialize a vector of a struct

The easiest and 'correct' solution here is probably to just use the resize() function that belongs to the vector object with aggregate initialization (if you have access to c++11 and on), something like

size.resize(100,{0,0,0}); //aggregate initialization 

for(int k = 0; k < N; ++k)
{
size[t].predator++;
size[t].prey1++;
size[t].prey2++;
}

All members of each numberOfSpecies object will be initialized to 0.

How to initialize a vector in a struct in c++

Since you're using C++; if you want to create a grupo dynamically, you should use the new operator, with the constructor:

grupo = new grupo();

malloc does not properly initialize C++ objects such as std::vector.


P.S. I am not sure what the grupo->modelos and grupo->grupos are supposed to be, but I'd use proper C++ types for them (perhaps modelos should be std::string, etc). Additionally, I suspect that you've got one * too much for both modelos and grupos.

C++ initialization of vector of structs

Finally, I found the right solution as
Initialize a vector of customizable structs within an header file . Unfortunately, replacing parenthesis did not help.

Concerning setting an unsigned int to its highest possible value using -1, I find as overkill to use std::numeric_limits<unsigned int>::max() for such a case, a kind of over-standardization. I personally think that as long as we are using two's complement representation, the assignment will be correct. For example, at
http://www.cplusplus.com/reference/string/string/npos/
you may read:

static const size_t npos = -1;

...

npos is a static member constant value with the greatest possible
value for an element of type size_t.

...

This constant is defined with a value of -1, which because size_t is
an unsigned integral type, it is the largest possible representable
value for this type.

Compilation error when trying to initialize vector of structs

Use std::string instead of c-style null-terminated arrays. std::string is less error-prone and there is usually no reason to avoid it.

#include <vector>
#include <string>

struct TEST_TYPE_B
{
int a;
int b;
std::string txt1;
std::string txt2;
};

std::vector <TEST_TYPE_B> TEST_B =
{
{1, 2, "1010101111", "ABC"},
{4, 5, "1010101111", "ABC"},
{7, 8, "1010101111", "ABC"},
{0, 1, "1010101111", "ABC"},
{3, 4, "1010101111", "ABC"}
};

Compiles fine

If you want to keep using char[], and arrays are large enough to hold the text, compilers seem to disagree on if the code is valid (clang compiles it, gcc doesn't). But they all agree with this form:

std::vector <TEST_TYPE_B> TEST_B =
{
TEST_TYPE_B{1, 2, "1010101111", "ABC"},
TEST_TYPE_B{4, 5, "1010101111", "ABC"},
TEST_TYPE_B{7, 8, "1010101111", "ABC"},
TEST_TYPE_B{0, 1, "1010101111", "ABC"},
TEST_TYPE_B{3, 4, "1010101111", "ABC"}
};

Vector of (Structs having vector)

For list initialiation,

Otherwise, the constructors of T are considered, in two phases:

All constructors that take std::initializer_list as the only argument,
or as the first argument if the remaining arguments have default
values, are examined, and matched by overload resolution against a
single argument of type std::initializer_list

If the previous stage does not produce a match, all constructors of T
participate in overload resolution against the set of arguments that
consists of the elements of the braced-init-list, with the restriction
that only non-narrowing conversions are allowed. If this stage
produces an explicit constructor as the best match for a
copy-list-initialization, compilation fails (note, in simple
copy-initialization, explicit constructors are not considered at all).

day is of type vector <Day>, whose constructor taking std::initializer_list as parameter expects an std::initializer_list<Day>, which can't be constructed from the braced-initializer {32}. Then the constructor taking size_type is used and construct the vector with 32 default-inserted instances of Day.

On the other hand, if Day could be initialized from an int, e.g. has a constructor taking int, then std::initializer_list<Day> could be constructed from {32} because of the implicit conversion from int to Day, then vector <Day> day {32}; would construct the vector with one element initialized from 32.

LIVE

Initialize a struct from elements of a vector

For the class in question, write a constructor which accepts a std::vector, or include the logic directly in the function template:

struct somedata{
string str1;
string str2;
somedata(const std::vector& vec) : str1(vec[0]), str2(vec[1]){

}
}

struct moredata{
string str1;
string str2;
string str3;
moredata(const std::vector& vec) : str1(vec[0]), str2(vec[1]), str3(vec[2]){

}
}

template<class Dataholder>
Dataholder queryUser(args){
auto vec = get_vector_from_user(args)
Dataholder dat{vec}; // The elements of vec become the structured variables in dat.
return dat;
}

Just make sure you add a check to assert there are correct number of elements in the vector.

C++ Initializing a vector inside a struct definition

vector<double>(24,-777)

This creates a temporary std::vector with 24 values of -777.

Then the hour vector is constructed by using that temporary, using the move constructor.

Initialize a vector of struct with zero values in Rust

Here is a criterion benchmark of your three approaches:

use criterion::{black_box, criterion_group, criterion_main, Criterion};

criterion_group!(
benches,
init_structs_with_iter,
init_structs_with_macro,
init_structs_with_unsafe
);
criterion_main!(benches);

const N_ITEMS: usize = 1000;

#[allow(unused)]
#[derive(Debug, Clone)]
struct MyStruct {
v1: u32,
v2: u64,
}

impl Default for MyStruct {
fn default() -> Self {
Self { v1: 0, v2: 0 }
}
}

fn init_structs_with_iter(c: &mut Criterion) {
c.bench_function("structs: with_iter", |b| {
b.iter(|| {
let mut my_vec = Vec::with_capacity(N_ITEMS);
(0..my_vec.capacity()).for_each(|_| my_vec.push(MyStruct::default()));
black_box(my_vec);
})
});
}

fn init_structs_with_macro(c: &mut Criterion) {
c.bench_function("structs: with_macro", |b| {
b.iter(|| {
let my_vec = vec![MyStruct::default(); N_ITEMS];
black_box(my_vec);
})
});
}

fn init_structs_with_unsafe(c: &mut Criterion) {
c.bench_function("structs: with_unsafe", |b| {
b.iter(|| {
let my_vec: Vec<MyStruct> = vec![unsafe { std::mem::zeroed() }; N_ITEMS];
black_box(my_vec);
})
});
}

And the results:

structs: with_iter      time:   [1.3857 us 1.3960 us 1.4073 us]                                
structs: with_macro time: [563.30 ns 565.30 ns 567.32 ns]
structs: with_unsafe time: [568.84 ns 570.09 ns 571.49 ns]

The vec![] macro seems to be the fastest (and also the cleanest and easiest to read).

As you can see, the time is measured in nanoseconds, so although the iterator version is 2-3x slower, it won't matter in practice. Optimizing the zero-initialization of a struct is the least important thing you can do - you can save at most 1 microsecond ;)

PS: those times include the memory allocation and deallocation times



Related Topics



Leave a reply



Submit