w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Storing from std::vector to std::set where vector contains a structure but std::set contains only one element from the struct
You have to visit every node, but you can hide the iteration away in std::transform struct StringFromInfo { std::string operator()(const Info& info) { return info.code; } }; std::transform(infVect.begin(), infVect.end(), std::back_inserter(uniqueCodes), StringFromInfo());

Categories : C++

C# - Storing a struct inside a struct of same type
You cannot store a struct of type X inside a struct of type X. However, you probably don't want to do this anyway, because in general, structs (and classes, for that matter) should only store the data they need to be complete. Instead, you can have a function that builds and returns the 'normalized' version of the struct: public struct Vector3 { float x,y,z; public Vector3 Normalized { get { ... build the normalized struct and return it ... } } }

Categories : C#

Unable to populate vector inside struct
I would recommend that you store a node instead of a node* in your vector so you don't have to manage the memory on your own. this is C++ so you don't have to malloc the space for a node you can use new like so: Node * n = new Node(); New is much better because it calls the constructor and allocates space, whereas malloc just does the latter. You haven't shown much of your code, but I would restructure the node class like this. struct node{ double startPoint; double endPoint; vector<node> children; node(){} //add default constrcutor void addChild(node aNode){ children.push_back(aNode); } node & operator=(const node & n) { startPoint = n.startPoint; endPoint = n.endPoint; return *this; } node(double start,

Categories : C++

Display a struct vector values based on 1 type
Why this won't work Your proposed solution simply won't work as intended. Consider three elements that are considered duplicates in consecutive subsequence (I am using numbers to simplify the concept): [1,1,1] The iterator will first compare 1 to 1, and then push_back the first one. Then it will compare second 1 to the third one, which again returns true, and the result that was supposed to have no duplicates ends up: [1,1] So it's clearly not something you want to do. In general, it looks like a rather weird problem, but so solve this one part you've posted here, I suggest using std::multiset. A better solution Create a comparator that tests for the name field just like you do here. Then, recovering unique fields is rather simple: std::multiset<AccDetail> s; for (

Categories : C++

How to access textbox values inside tabItems for storing
You should give names to inner tabs and then search tham using their names. Here you can find some explanation: find control by name

Categories : C#

How to access a struct member when iterating a vector of structs with vector::operator[]
You don't change the value of i here, so it is 0: int i = 0; if ( i + 1 < line.token_list.size() ) { token_line_number = line.token_list[i+i].line_number; // i has not been changed from 0 Remember that 0+0 is 0. So line.token_list[i+i] is line.token_list[0].

Categories : C++

Is there a way to use a pointer to struct inside the struct without naming the struct?
It is not possible to do what you are doing. The compiler has no idea what dll_node is as it determines the amount of bytes the structure will require when allocated. Do this: struct node; typedef struct node dll_node; struct node { dll_node *next; dll_node *prev; size_t elem_size; void *data; }; ... or a method I personally like to use (as you are often dealing with pointers to structs): struct node; typedef struct node *dll_node; struct node { dll_node next; dll_node prev; size_t elem_size; void *data; };

Categories : C

How do I declare a vector of a struct within that same struct?
What you have is not standards compliant (thanks to @jonathanwakely for confirming that). So it is undefined behaviour, even if it compiles on some popular platforms. The boost container library has some standard library-like containers that do support this, so you could in principle modify your struct to use one of these: #include <boost/container/vector.hpp> struct tnode { int data; boost::container::vector<tnode> children; GLfloat x; //x coordinate of node GLfloat y; //y coordinate of node };

Categories : C++

Vectorized change of all but first same/repeated values in vector b based on values from vector a
I'm not sure if I really understand what you're trying to do, but if do understand I think I have a vectorized solution for you. > f <- function(a,b){ + b[unique(c(which(a[-length(a)] == 0 & b[-1] != 0) + 1,which(b[-length(b)] == b[-1] & b[-1] != 0)))] <- 0 + return(b) + } > f(a,b) [1] 0 0 -1 0 0 0 0 0 0 0 0 0 -1 0 1 0 0 -1 0 0 1 0 0 0 0 0 0 Here was my rational. I think you want to set values of b to zero based on two different scenarios: 1) When non-zero values of b repeat. If so this should find those indices: which(b[-length(b)] == b[-1] & b[-1] != 0) 2) When non-zero values of b occur when the previous index of a was zero. If so this should do the trick: which(a[-length(a)] == 0 & b[-1] != 0) + 1 Hopefully I didn't mis

Categories : R

double pointer to struct inside struct
You should either have initGraph() take (**graph) or return the graph. Since the malloc address of graph is local to initGraph. Something like: void initGraph(tGraph **graph, int size) { tgraph *temp; temp = (tGraph*)malloc(sizeof(tGraph*)); temp->cities = (tCity**)malloc(sizeof(tCity*) * size); temp->size = size; *graph = temp; }

Categories : C

Initializing a struct array inside a struct
bq.cards is array of structs, you don't have to malloc it. You can initialize the entire array as: memset(bq.cards, 0, sizeof(bq.cards)); If you want to initialize bq do memset(&bq, 0, sizeof(bq));

Categories : C

storing multiple arrays within a struct in C
If they are 1-D arrays, best way to allocate memory is through malloc. Again, since they are 1-D you can access them via array notation, being careful no to exceed the bounds given by total_nodes and total_tasks. Use free to free up arrays when deleting nodes. If array nodes gets bigger, use realloc to make the array bigger and keep the old pointers in place.

Categories : C

int array inside a struct inside a struct
struct that contains an array of structs that contain a array of integers. no pointers, as u asked #define SIZE (8) typedef struct { struct data { int idata[SIZE]; }; struct data arr[SIZE]; }record; //or struct data { int idata[SIZE]; }; typedef struct data arr[SIZE];

Categories : C

Best practice for storing an array of struct of undefined length
std::vector<MyStruct> is the better option. There is also another option, which is very close to vector in some way, is called std::deque. Have a look at it; maybe it will help you, or at least increase your awareness of standard containers. The online doc says, As opposed to std::vector, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays. The storage of a deque is automatically expanded and contracted as needed. Expansion of a deque is cheaper than the expansion of a std::vector because it does not involve copying of the existing elements to a new memory location. Although, std::deque doesn't store elements in contiguous memory, it works with RandomAccessIterator — pretty much like

Categories : C++

Storing C struct array to core data or on disk?
I thought NSValue could be used by using value:withObjCType:. But according to the documentation variable length types cannot be used. The type you specify must be of constant length. You cannot store C strings, variable-length arrays and structures, and other data types of indeterminate length in an NSValue—you should use NSString or NSData objects for these types. Assuming this: //Sample data typedef struct { CGFloat lat; CGFloat longi; }Location; Location list[2]; Location get[2]; Location l1; l1.lat = 10.0; l1.longi = 4.0; Location l2; l2.lat = 3.0; l2.longi = 4.0f; list[0] = l1; list[1] = l2; You can use NSData the following way for your requirement: //This is the part you want //create NSData NSData *data = [NSData dataWithBytes:list length:sizeof(l

Categories : IOS

Summing Values of One Vector Conditional on Values of Another Vector
Use ifelse instead of if The ifelse function performs elementwise conditional evaluation upon a vector: Example: x<-3 y<-c(1,2,3) ifelse ifelse(x==y,"good","bad") [1] "bad" "bad" "good" if if (x ==y) "good" else "bad" [1] "bad" Warning message: In if (x == y) "good" else "bad" : the condition has length > 1 and only the first element will be used

Categories : R

Proper Qt data structure for storing and accessing struct pointers
If you want to use QHash for fast lookups, the hash's key type must be the same as the search token type. For example, if you want to find elements by Statistics value, your hash should be QHash<Statistics, MyStruct*>.

Categories : C++

Does initializing a Vector with an array of values in AS3 partially defeat the purpose of a Vector?
Actually, you can use the new <T>[] syntax to create a new Vector with initial content: var vec:Vector.<Space> = new <Space>[/* your, items */]; // --------------------------^ Notice the lack of 'Vector.' before here. Your example uses the global Vector() method to create a Vector from an array.

Categories : Arrays

istream for a struct with a vector member
add a "hit key to continue" and put the test1 var inside the loop should prevent the "vector-mix up" do { Test test1; cin >> test1; cout << test1; } while (getchar() == 'c')

Categories : C++

Using a fixed length vector in a struct - C++
To construct objects in a struct (or class) you need to write a constructor. Like this struct CharStack { CharStack() : data(87) {} int sp; std::vector<char> data; } S; It's just how C++ syntax is.

Categories : C++

why constant size of struct despite having a vector of int
A vector will store its elements in dynamically allocated memory (on the heap). Internally, this might be represented as: T* elems; // Pointer memory. size_t count; // Current number of elements. size_t capacity; // Total number of elements that can be held. so the sizeof(std::vector) is unaffected by the number of elements it contains as it calculating the sizeof its contained members (in this simple example roughly sizeof(T*) + (2 * sizeof(size_t))).

Categories : C++

Serializing Struct of vectors of vector
std::vector allocates memory when inserting data. So file.write((char*)&DnaTbl, sizeof(DnaTbl)); only saves the "metadata" of std::vector<TDnaTbl> and leaves out the data you inserted, which is stored somewhere else in memory. You would have to iterate over the vector and save the element count and the element-data manually.

Categories : C++

Storing a vector in a DLL data segment
http://msdn.microsoft.com/en-us/library/h90dkhs0(v=vs.90).aspx And how is an std::vector<> initialized? yes it is a terrible idea to use a shared data segment. Since the code executing is within the process space of that program you are going to default to allocating memory for your vector from that processes address space. In which any other process will throw an exception trying to read or write to. You can write your own _alloc to pull from system shared memory, but this wont resolve your initialization issues. The recommended method for ipc is via memory mapped files, and mutex's. To get this to work the way you desire is going to require a good deal of code. Get comfortable looking through the Std:Vector code until you can derive a class from that template, or choose a fa

Categories : C++

Fast way of getting a specific struct object from an std::vector
Use a std::map instead: class ItemData { public: std::map<unsigned, Item> m_Items; private: void load() { // Parse a JSON string to fill up m_Items vector with // Item objects. } const Item getItem(unsigned id) const { std::map<unsigned, Item>::const_iterator it = m_Items.find(id); if (it != m_Items.end()) return it->second; return Item(); } }; You could consider std::unordered_map as well.

Categories : C++

write and read a 3d vector of struct in file C++
It's not very clear what is relationTable for you. If you want to save your structure into a file, the easier way is to use boost::serialization see : How do you serialize an object in C++? you can do something like this : #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/map.hpp> include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> namespace boost { namespace serialization { template<class Archive> void serialize(Archive & ar, Block& b, const unsigned int version) { ar & b.numbers; ar & b.bits; ar & b.states; ar & b.off; } void save_Block(const Block &b, const char * filename){ // make an archive std::ofstream

Categories : C++

passing a vector member (struct) to a function
It's most likely because you have using namespace std; in your code. This makes the compiler think you are referencing std::distance instead of your function. The obvious solution, and what I really recommend, is to stop with using namespace std; in your code. In the meantime you could try calling your function using the global scope, like x1 = ::distance (p[0],p[1]);

Categories : C++

glvertexpointer std::vector, struct memory opengl
If you use a struct like that your vertices are no longer tightly packed and you need to specify a stride: glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 3, GL_FLOAT, sizeof( Vertex ), &verts[0].pos ); glDrawArrays( GL_TRIANGLES, 0, 3 ); glDisableClientState(GL_VERTEX_ARRAY); Like so: #include <GL/glut.h> #include <vector> struct Vertex { float pos[3]; float tex[2]; float norm[3]; int index_mtl; }; std::vector< Vertex > verts; void display() { glClear( GL_COLOR_BUFFER_BIT ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( -2, 2, -2, 2, -1, 1 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glColor3ub( 255, 0, 0 ); glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 3, GL_FLOAT, si

Categories : C++

no need to delete struct memory in vector?
Yes, there is a memory leak: the pointer to the created structure is lost after the vector is destroyed, and the memory is never released. Unless someone performs a delete for each element of rsVec before clearing or destroying the vector.

Categories : C++

Use a member of struct vector in nested classes
Well, ConnectedGrids is a vector, you declared it as vector<connectedGrids> ConnectedGrids; So, which of the connectedGrids structures inside that vector did you want to modify?

Categories : C++

Make an int vector receive the values from a vector of a class that has an int
Use std::transform: std::transform( std::begin(circles), std::end(circles), std::back_inserter(sizes), [](const circle &c) {return c.radius;} );

Categories : C++

Storing objects in a vector at the time of construction
As it stands you code doesn't compile. First the class needs a semicolon at the end vector<trialclass> vektor; class trialclass { public: trialclass() { vektor.push_back(*this); } }; ^^^ Second, the declaration of vektor doesn't know what a trialclass is. This rearrangement gets around the problem class trialclass { public: trialclass(); }; std::vector<trialclass> vektor; trialclass::trialclass() { vektor.push_back(*this); } This compiles and "works" in the sense that vektor ends up with a item in for each trialclass constructed, but note these are copies of the trialclass

Categories : C++

Good way to initialise a vector of vectors of struct (each with an initial value)?
Unless this is a syntax I'm unfamiliar with, what you tried is actually using the comma operator, so (NUM_COLUMNS, (NUM_ROWS, (3,3))) becomes (NUM_COLUMNS,3), which passes 3 as the value to construct the vectors from (which will in turn call the vector's constructor with an int, giving you vectors of 3 default-initialised elements) I think what you need to do is this: // C++11 vanish_vectors(NUM_COLUMNS, std::vector<Vanish>(NUM_ROWS, {3,3})) // or for older C++ (you will also need to give Vanish a constructor) vanish_vectors(NUM_COLUMNS, std::vector<Vanish>(NUM_ROWS, Vanish(3, 3))) // or (as noted in the comments) to keep Vanish as POD in pre-C++11: vanish_vectors(NUM_COLUMNS, std::vector<Vanish>(NUM_ROWS, makeVanish(3, 3))) // with a function like this: Vanish makeVa

Categories : C++

Initializing struct vector with brace-enclosed initializer list
you need one more {} actually vector<Vertex> data = {{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f}}}; one '{' for vector, one for struct, one (couple of) for struct member-arrays...

Categories : C++

Insert a dynamically created struct item into a vector of structs
std::vector<struct instFunDescLeg> bp; should be written std::vector<instFunDescLeg> bp; Your struct is fairly simple, so I see no need to store a vector of pointers to it with what you are provided. If there is some hidden requirement that would force you to use pointers, try to hide them behind smart pointer classes (e.g. unique_ptr).

Categories : C++

C++ Storing vector from a file using reserve and possibly emplace_back
Rather than waste time counting the lines ahead of time, I would just reserve() an initial value, then start pushing the actual lines, and if you happen to push the reserved number of items then just reserve() some more space before continuing with more pushing, repeating as needed.

Categories : C++

struct tm inside another struct - c
These date functions are based on the epoch year: 1970. You're using a 1967 year. As an aside: Dennis Ritchie wanted the epoch at 1970 so that the values (both negative and positive) would span his entire life. (Or so he once said in an interview.)

Categories : C

I have a vector whose elements contain multiple numbers. How do I sum numbers inside each element and create a new vector?
Try this: > sapply(strsplit(as.character(vec), ","), function(x) sum(as.numeric(x))) [1] 7 5 10 The basic idea is to split the character vector, extract the numeric values, and calculate the sum. strsplit doesn't work on factors, so if you actually have factors, you'll need to convert them to characters first. Similarly, sum won't work on the resulting characters, so you need to convert that to numeric first.

Categories : R

C - function inside struct
This will only work in C++. Functions in structs are not a feature of C. Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++. Convert your source to a .cpp file and make sure you are compiling accordingly. If you need to stick to C, the code below is (sort of) the equivalent: typedef struct client_t client_t, *pno; struct client_t { pid_t pid; char password[TAM_MAX]; // -> 50 chars pno next; }; pno AddClient(pno *pclient) { /* code */ } int main() { client_t client; //code .. AddClient(client); }

Categories : C

Accessing data inside a struct
You just need to do it like this: x=obs.data->time; (This assumes of course that you have initialised obs.data to point at a valid instance of obsd_t.)

Categories : C

C++ : Scope of struct inside a class
As mentioned in the comments, I needed to insert the keyword typename in front of the declaration of temp -: typename mystack<T>::mystack_node *temp = a.stack_top;

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.