In the following cases, how do I write the initial value (2*2 array, value 1) for data?
structure name {
intx;
inty;
}
std::shared_ptr<std::vector<std::vector<std;structure name>>>data;
I tried the following, but the value was not printed because the array size was 0.
for(const auto&data:*data){
for(const auto&data_info:data){
data_info.x = 1;
data_info.y = 1;
}
}
*Additional information
#include<bits/stdc++.h>
structureSomeData{
intx;
inty;
SomeData():
x(0),
y(0){}
SomeData(int_num1, int_num2):
x(_num1),
y(_num2){}
};
struct Data {
std::shared_ptr<std::vector<std::vector<SomeData>>>data;//☆
};
void func(const Data&data_info)
{
auto data=std::make_shared<std::vector<std::vector<SomeData>>();
data->push_back({{1,1},{1,1}});
data->push_back({{1,1},{1,1}});
for(const auto&data:*data){
for(const auto&data_info:data){
std::cout<<"x:"<<data_info.x<<std::endl;
std::cout<<"y:"<<data_info.y<<std::endl;
}
}
}
int main (const Data & data_info)
{
func(data_info);
return 0;
}
output results:
x:1
y:1
x:1
y:1
x:1
y:1
x:1
y:1
In this case, how should I write the initial value (2*2 array, value 1) for data?
Note This is an example of not using initializer_list
using T=std::vector<SomeData>;;
std::shared_ptr<std::vector<T>>data=std::make_shared<std::vector<T>>(2,T(2,SomeData(1,1));
This is an example of when you want to set the initial value later instead of initializing.
using T=std::vector<SomeData>;;
std::shared_ptr<std::vector<T>>data;
std::shared_ptr<std::vector<T>>tmp=std::make_shared<std::vector<T>>(2,T(2,SomeData(1,1));
data.swap(tmp)
If you want to do everything with initialization:
using T=std::vector<Structure Name >;;
auto data=std::make_shared<std::vector<T>>(
std::initializer_list<T>{
{{1, 1}, {1, 1}},
{{1, 1}, {1, 1}}});
If push_back()
is acceptable,
auto data=std::make_shared<std::vector<std::vector<std::vector<structure name>>>();
data->push_back({{1,1},{1,1}});
data->push_back({{1,1},{1,1}});
© 2024 OneMinuteCode. All rights reserved.