how to use push_back in vector of a struct - c++

hey guys i have created a struct node. one of its fields is a vector (path) where i want to store characters.however when i try to push_back a character the compiler says "error: ‘path’ was not declared in this scope"
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <list>
#include <climits>
using namespace std;
struct node {
int weight;
bool pizza; // true an tin exo
vector <char> path;
int tetmimeni, tetagmeni; // i, j gia na vro geitones
} ;
node a;
int main(){
a.tetmimeni=0; // create start node
a.tetagmeni=0;
a.weight=0;
a.pizza=true;
a.path= path.push_back('S');

Replace a.path= path.push_back('S'); with just a.path.push_back('S');
The original code was trying to assign the return type of push_back to a.path which is invalid.
Instead you simply want to invoke the push_back method of the std::vector member of your struct.

In your code , node is a structure. Path is one element of struct.
Anytime you need to access element of struct , you have to use the name of struct along with it.
e.g. a.pizza or a.weight when 'a' is of the type node.
Similarly you need to access a.path when you want to access vector path. It doesn't matter even if you need to call the functions of vector.
You should go through struct/class

Related

std::map with structs as values

I have an issue where I need to keep a map of, e.g. vectors, of items, each vector has a corresponding indicator valid for all items for a given key in the map
I guess it could be map of pairs (map<string,pair<vector,bool>>) but that would e very confusing...
So
I wanted to ask you about code like that:
Would this be considered a correct implementation of the problem, is there any potential issue with this? When I add a new key with myMap["KEY"] nothing can ever break because it autoinitializes my struct? Can anything go wrong here?
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct ListOfItemsWithIndicator
{
bool _indicator;
vector<int> _items;
ListOfItemsWithIndicator(): _indicator(false) {}
};
int main() {
std::map<std::string,ListOfItemsWithIndicator> myMap;
myMap["ONE"]._items.push_back(1);
std::cout << myMap["ONE"]._items[0];
return 0;
}

How to iterate a deque>>vector>>bytes to a function

I need to be able to call a function that is looking for an iterator of a complex data structure (pseudo-code) vector::deque::vector(uint8_t)::iterator. I need to be able to call it with a deque::vector(uint8_t); I can not figure out how to "iterate" it.
In the code segment below, I'm trying to call the MyFunkyFunc function with the someMoreBytes deque structure.
#include <cstdlib>
#include <vector>
#include <deque>
#include "stdint.h"
using namespace std;
void MyFunkyFunc(std::vector<std::deque<std::vector<uint8_t>>>::iterator itsIt)
{
}
int
main(int argc, char** argv)
{
std::vector<std::deque<std::vector < uint8_t>>> bunchaBytes;
std::deque<std::vector<uint8_t>> someMoreBytes;
//... Put at least one element in bunchaBytes
MyFunkyFunc(bunchaBytes.begin());
MyFunkyFunc(someMoreBytes); // Problem is here
return 0;
}
This code stub is a close as I can get to the original; I am unable to make any modifications to the MyFunkyFunc function, as it is in a library I have to link with. Many thanks in advance
If we assume that MyFunkyFunc was implemented properly as a template accepting an iterator parameter:
template <typename I>
void MyFunkyFunc (I itsIt) {
//...
}
Then, you can just pass the address of someMoreBytes, since an iterator to a vector behaves the same as the address of an element of a vector.
MyFunkyFunc(&someMoreBytes);
Otherwise, you will need to redefine someMoreBytes to be a single element vector, and pass in the begin(), just as you did with bunchaBytes.

C++ How to store information inside a object pointer vector?

Let's say I have two member variables called attribute name and value and I want to store them inside a vector called attributes. I know I can create an object so let's say I had a class called Element and then I created an object called Element* Element_object Now I want to store the attribute name and attribute value inside of Element_object vector. I know there's a function called push_back() that helps you to do so. I was thinking that I would something like this attributes.push_back(attribute_value);except that won;t work because attribute is type element pointer and attribute value is a string type. Should I change the type of my vector attribute from element* to a string and then do attributes.push_back(attribute_value);I want to store multiple attributes inside the object vector so I'm assuming that in order to store multiple attributes inside element_object vector I would keep using push_back()?
My .h file looks like this:
#ifndef Header_h
#define Header_h
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
class Element{
public:
void set_attribute_name(string temp_attribute_name);
string get_attribute_name();
void set_attribute_value(string temp_attribute_value);
string get_attribute_value();
private:
/**Member variables**/
vector<Element*> attributes;
string attribute_name;
string attribute_value;
};
#endif /* Header_h */
you can create a separate class or a simple struct will do.
you cannot push individual struct members to vector. you need to push the entire object/pointer to obj.
struct keyvalue
{
std::string attribute_name;
std::string attribute_value;
};
vector<keyvalue*> vecKeyValue;
in implementation file:
keyvalue* pkval = new(std::nothrow) keyvalue;
pkval->attribute_name = "name";
pkval->attribute_value = "value";
vecKeyValue.push_back(pkval);

End process error code -1 if acess to string field of structure

#include <cstdlib>
#include <string>
#include <iostream>
#define S 10
using namespace std;
struct List
{
string name;
bool male;
int year;
string addr;
string diag;
bool hosp;
};
main()
{
struct List *l=NULL;
int n=0;
for(int i=0;i<10000;i++)
{
if(!(n%S))
{
l=(List*)realloc(l,(n/S+1)*S*sizeof(struct List));
cout<<"realloc ok\n";
};
l[n].male=rand()%2;
l[n].year=1900+rand()%100;
l[n].hosp=rand()%2;
//!l[n].name="abc";
n++;
cout<<l[rand()%n].male<<" "<<l[rand()%n].year<<" "<<l[rand()%n].hosp<<endl;
}
}
If l[n].name="abc" remarked then program works fine.
If i try put string value to this field the programm compiled without warnings nay, but crash with error code -1 after first realloc.
Any way to solve it?
Since your structure is non-trivial - it contains members of class type, std::string, which need to be initialised by calling their constructors - you can't simply allocate raw memory and pretend that contains a valid object.
The simplest solution is to use a type-aware dynamic array
std::vector<List> l;
which can be resized, perserving its contents, with
l.resize((n/S+1)*S);
Tip! Using "new" operator to allocate this structure will automatically create string object for each field.
List *l=new struct List[S];
It fix this issue, l[n].name="abc" will works, but it not implements reallocation functional.

Passing a vector to constructor

Iam new in C++ and iam trying to implement classes into my program. I have done similar program in java. But iam struggling to implement classes in c++. I want to pass a vector with strings from main to a class called Search.I can pass a vector either by value or reference. Iam using a vector * which means get vector address.This is what i was told. Iam not sure how i should refer to it. I am sure there are more mistakes in my code. Could please someone help me or explain me how to initialize vector in constructor and how to add a value so I can use the vector in the menthod?? Iam using Visual Studio PRO 2010. Many thanks for replies.
Search.h
// pragma once
#include "std_lib_facilities.h"
#include <vector>
class Search
{
public:
Search();
Search(int dd, int mm, int year,vector<string>* dat);
vector<string> get_result ();
~Search(void);
private:
int d;
int m;
int y;
vector<string> data;
};
Search.cpp
#include "Search.h"
#include <vector>
#include "std_lib_facilities.h"
Search::Search()
:d(1), m(1), y(2000), data(){} //data() is the vector but iam not sure if ihave set the value corectly
Search::Search(int dd, int mm, int year,vector<string>*dat)
:d(dd),m(mm),y(year), data(dat){}//no instance of constructor matches the construcor list -- this is the error iam getting
//iam trying to initiliaze the varibale data of type vector.But i dont know how to do it.
Search::~Search(void)
{
}
vector<string> Search::get_result () {// implementation where i need to use the data stored in a vector
}
//main program
#include "std_lib_facilities.h"
#include <string>
#include <sstream>
#include <stdio.h>
#include "Search.h"
#include <vector>
int main(){
int day, month, year; //iam gonna ask user to input these
day=20;
month=12;
year=2014;
vector<string>flight_info;
ifstream inputFile("flight.txt");
// test file open
if (inputFile) {
string value;
// read the elements in the file into a vector
while ( inputFile >> value ) {
flight_info.push_back(value);//this is the vector i want to pass to class Search
}
}
Search search(day,month,year,flight_info)
//this where i want to create object of Search class but iam gettin error -no instance of constructor matches the `enter code here`construcor list.
}
This defines a vector:
vector<string>flight_info;
This defined a vector member variable:
vector<string> data;
This invoke a constructor by passing the vector to it:
Search search(day,month,year,flight_info)
But this constructor expects a pointer to a vector!
Search(int dd, int mm, int year,vector<string>* dat);
You don't need to pass any of the standard containers around by pointer (and you're probably doing something wrong if you find yourself trying to).
You can rewrite your constructor to be Search(int dd, int mm, int year,vector<string> dat) to resolve your error. You only need to change the prototype of your constructor, because data(dat) will already correctly construct the member vector.