Convert Struct type to vect int - c++

I have problem i need to convert from my "Array" structure to std::vector<int>... the point is i have a dynamic matrix who purpose is being Database. But at some point i need to move some values from the 'Array' to a vector. and i get the fallowing error
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits /stl_iterator_base_types.h:166:53: error: 'int' is not a class, struct, or union type
Anyone has some clue how to achive this thing?
structure:
const int days=31;
const int exp=6;
struct Arr{
int days;
int exp;
int **M;
};
typedef Arr* Array;
vector:
vector <int> vec(31);
EDIT:
int dayExp(int day, Array &M){
int s=0;
for(int i=0;i<6;i++){
s += M->M[day][i];
}
return s;
}
void srtDesc(Array &M){
vector <int> vec(31);
for(int i=0;i<31;i++){
vec[i]=dayExp(i, M);
}
sort(vec[0],vec[1]);
for(int i=0;i<31;i++){
cout<< vec[i];
}
}

Your Arr struct does not implicitly convert to int. First of all, your struct contains 3 int types, whereas a vector<int> is one int at a time.
If you want to put your Arr into a vector, you should create a std::vector<Arr> and then call push_back on it to put your Arr structs in it.
std::vector<Arr> myvec;
myvec.push_back(someArr);
You will need to create for loop that goes through the length - 1 of your array and calls push_back to put each item in the vector

Related

Return struct of multi-array from user-defined function in C++

I wrote a function as below, declared a struct of 2D array. size of this struct is initialized in function read_landmask.
struct landmask {
double value;
};
landmask read_landmask(NcFile &dataFile,grid grid, parameters params) {
NcVar lm;
...
size_t m=grid.lat.size();
size_t n=grid.lon.size();
landmask lmdomain[m][n];
for (int i=0;i<m;++i){
for (int j=0;j<n;++j){
neighborpoints nbpoints=closest_distance(lmbnds.sizelat,lmbnds.sizelon,*lmdata, lmbnds.lat,lmbnds.lon, grid.lat[i], grid.lon[j]);
lmdomain[i][j].value=interp2D_Cressman(nbpoints.lon, nbpoints.lat,nbpoints.val, grid.lat[i], grid.lon[j]);
}
};
return lmdomain[m][n];
};
and in the main function, it is called like:
int main(){
landmask landmask_array=read_landmask(lmfile,grid,params);
cout<< landmask_array[3][2].value<< endl;
};
but the cout is error. Seems like the array is not return the whole 2D array, so I cannot put the indices of rows and columns.
Does anyone have ideas or experiences with this before?
Thanks

how to save vector from c++ to c [duplicate]

How do I convert a std::vector<double> to a double array[]?
There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?
If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where v is a vector of doubles. The elements of a vector are contiguous.
Otherwise, you just have to copy each element:
double arr[100];
std::copy(v.begin(), v.end(), arr);
Ensure not only thar arr is big enough, but that arr gets filled up, or you have uninitialized values.
For C++11, vector.data() will do the trick.
vector<double> thevector;
//...
double *thearray = &thevector[0];
This is guaranteed to work by the standard, however there are some caveats: in particular take care to only use thearray while thevector is in scope.
As to std::vector<int> vec, vec to get int*, you can use two method:
int* arr = &vec[0];
int* arr = vec.data();
If you want to convert any type T vector to T* array, just replace the above int to T.
I will show you why does the above two works, for good understanding?
std::vector is a dynamic array essentially.
Main data member as below:
template <class T, class Alloc = allocator<T>>
class vector{
public:
typedef T value_type;
typedef T* iterator;
typedef T* pointer;
//.......
private:
pointer start_;
pointer finish_;
pointer end_of_storage_;
public:
vector():start_(0), finish_(0), end_of_storage_(0){}
//......
}
The range (start_, end_of_storage_) is all the array memory the vector allocate;
The range(start_, finish_) is all the array memory the vector used;
The range(finish_, end_of_storage_) is the backup array memory.
For example, as to a vector vec. which has {9, 9, 1, 2, 3, 4} is pointer may like the below.
So &vec[0] = start_ (address.) (start_ is equivalent to int* array head)
In c++11 the data() member function just return start_
pointer data()
{
return start_; //(equivalent to `value_type*`, array head)
}
Vectors effectively are arrays under the skin. If you have a function:
void f( double a[]);
you can call it like this:
vector <double> v;
v.push_back( 1.23 )
f( &v[0] );
You should not ever need to convert a vector into an actual array instance.
std::vector<double> vec;
double* arr = vec.data();
We can do this using data() method. C++11 provides this method.
Code Snippet
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int>v = {7, 8, 9, 10, 11};
int *arr = v.data();
for(int i=0; i<v.size(); i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
If you have a function, then you probably need this:foo(&array[0], array.size());. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.
You can do some what like this
vector <int> id;
vector <double> v;
if(id.size() > 0)
{
for(int i = 0; i < id.size(); i++)
{
for(int j = 0; j < id.size(); j++)
{
double x = v[i][j];
cout << x << endl;
}
}
}

c++ declare vector array to get a class, but cannot access member variable

When I declare vector to get a class, but cannot access member variable.
Code has more details,
class test{
public :
int num; //member variable
test(int k){ //constructor
num=k;
}
};
int main(){
vector<test *> a[10]; //declare vector
for(int i=0;i<10;i++)
a.push_back(new test(p)); //use constructor initial
for(int i=0;i<10;i++)
cout<<a[i].num<<endl; //THIS STEP ERROR, 'NO MENBER num'
}
I can't find out solution. QAQ~
class test{
public :
int num; //member variable
test(int k){ //constructor
num=k;
}
Why not a struct if all members are public anyway?
Also, that ctor calls for a ctor-init-list, like this, instead:
struct test{
int num;
test(int num) : num(num) {}
};
int main(){
vector<test *> a[10]; //declare vector
Lies in advertising, you are actually defining, and an array of ten vectors.
vector<test*> a; // This is a vector of pointers to test
for(int i=0;i<10;i++)
a.push_back(new test(p)); //use constructor initial
for(int i=0;i<10;i++)
cout<<a[i].num<<endl; //THIS STEP ERROR, 'NO MENBER num'
}
a[i] is of type test*, and pointers do not have members. You wanted to use the arrow-operator ->.
cout<<a[i]->num<<endl;
Last, you forgot to delete all that memory you allocated.
Solutions:
Don't allocate dynamic memory but store test-objects directly.
vector<test> a; // This is a vector of test
for(int i=0;i<10;i++)
a.push_back(test(p)); //use constructor initial
for(int i=0;i<10;i++)
cout<<a[i].num<<endl;
Use smart-pointers (<memory>):
vector<std::unique_ptr<test>> a; // This is a vector of std::unique_ptr<test>
for(int i=0;i<10;i++)
a.push_back(new test(p)); //use constructor initial
for(int i=0;i<10;i++)
cout<<a[i]->num<<endl;
Add all the manual memory-management, but remember all allocations can throw.
Too long and error-prone, won't write it.
You have declared an array of vectors:
std::vector<> a[10];
An array of 10 vectors.
Each slot in the array is a vector of pointers to your test class:
std::vector<Test *> a[10];
So, to access a Test item, you will need to find out which array element to access and where the item is inside the array:
Test p_object = 0;
p_object = a[3].[2]; // The fourth vector, the third slot in the fourth vector.
std::cout << "Test item from 3rd slot in 4th vector: "
<< p_object->num
<< "\n";
I don't think this is what you need or want. The picture that the code shows resembles a 2d matrix. Usually, 2d Matrices are declared as a vector of vectors or a 2d array; not a combination of both.

How to convert vector to array

How do I convert a std::vector<double> to a double array[]?
There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?
If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where v is a vector of doubles. The elements of a vector are contiguous.
Otherwise, you just have to copy each element:
double arr[100];
std::copy(v.begin(), v.end(), arr);
Ensure not only thar arr is big enough, but that arr gets filled up, or you have uninitialized values.
For C++11, vector.data() will do the trick.
vector<double> thevector;
//...
double *thearray = &thevector[0];
This is guaranteed to work by the standard, however there are some caveats: in particular take care to only use thearray while thevector is in scope.
As to std::vector<int> vec, vec to get int*, you can use two method:
int* arr = &vec[0];
int* arr = vec.data();
If you want to convert any type T vector to T* array, just replace the above int to T.
I will show you why does the above two works, for good understanding?
std::vector is a dynamic array essentially.
Main data member as below:
template <class T, class Alloc = allocator<T>>
class vector{
public:
typedef T value_type;
typedef T* iterator;
typedef T* pointer;
//.......
private:
pointer start_;
pointer finish_;
pointer end_of_storage_;
public:
vector():start_(0), finish_(0), end_of_storage_(0){}
//......
}
The range (start_, end_of_storage_) is all the array memory the vector allocate;
The range(start_, finish_) is all the array memory the vector used;
The range(finish_, end_of_storage_) is the backup array memory.
For example, as to a vector vec. which has {9, 9, 1, 2, 3, 4} is pointer may like the below.
So &vec[0] = start_ (address.) (start_ is equivalent to int* array head)
In c++11 the data() member function just return start_
pointer data()
{
return start_; //(equivalent to `value_type*`, array head)
}
Vectors effectively are arrays under the skin. If you have a function:
void f( double a[]);
you can call it like this:
vector <double> v;
v.push_back( 1.23 )
f( &v[0] );
You should not ever need to convert a vector into an actual array instance.
std::vector<double> vec;
double* arr = vec.data();
We can do this using data() method. C++11 provides this method.
Code Snippet
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int>v = {7, 8, 9, 10, 11};
int *arr = v.data();
for(int i=0; i<v.size(); i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
If you have a function, then you probably need this:foo(&array[0], array.size());. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.
You can do some what like this
vector <int> id;
vector <double> v;
if(id.size() > 0)
{
for(int i = 0; i < id.size(); i++)
{
for(int j = 0; j < id.size(); j++)
{
double x = v[i][j];
cout << x << endl;
}
}
}

C++ copy vector of objects to another

I want to copy to vectors with the same size and same type one to another but after printing the value it seems like it doesn't work correctly or it doesn't want to copy all pointers to data in each object. Thanks for help
Here is code:
std::vector<Vehicle> vehicles(2);
std::vector<Vehicle> vehiclesCopy(2);
vehicles[0].setX_pos(3);
for(int i=0;i<vehicles.size();i++)
vehiclesCopy.push_back(vehicles[i]);
cout<<vehicles[0].getX_pos()<<endl;
cout<<vehiclesCopy[0].getX_pos()<<endl;
Output:
3
0
Here is the Vehicle code
class Vehicle
{
private:
unsigned int x_pos,y_pos,velocity;
char type;
public:
void vehicle(char inType,
unsigned int inX_pos,
unsigned int inY_pos,
unsigned int inVelocity)
{
type=inType;
x_pos=inX_pos;
y_pos=inY_pos;
velocity=inVelocity;
}
unsigned int getMaxPassengers(){
return maxPassengers;
}
unsigned int getX_pos(){
return x_pos;
}
unsigned int getY_pos(){
return y_pos;
}
unsigned int getVelocity(){
return velocity;
}
char getType(){
return type;
}
void setX_pos(unsigned int input){
x_pos=input;
}
void setY_pos(unsigned int input){
y_pos=input;
}
void setVelocity(unsigned int input){
velocity=input;
}
void setType(char input){
type=input;
}
};
You create two vectors with size 2. Then you push all elements from one vector to the other. You now have one unmodified vector and the other vector with 4 elements. Pushing two elements at the end wont have any effect on the first element (the one you print).
To copy vectors use simple assignment:
vehiclesCopy = vehicles;
Or if you want to use a loop (why would you?), assuming they both have correct size (they do in your example):
for(int i=0;i<vehicles.size();i++) {
vehiclesCopy[i] = vehicles[i];
}
PS: this answer isnt the whole truth. If vehiclesCopy is really just a copy of vehicles you should not first construct an empty vector and then copy it, but instead use the right constructor. See here for details (overload (6) is your friend here).