Search Results

Search found 976 results on 40 pages for 'typedef'.

Page 8/40 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Copy vector of values to vector of pairs in one line

    - by Kirill V. Lyadvinsky
    I have the following types: struct X { int x; X( int val ) : x(val) {} }; struct X2 { int x2; X2() : x2() {} }; typedef std::pair<X, X2> pair_t; typedef std::vector<pair_t> pairs_vec_t; typedef std::vector<X> X_vec_t; I need to initialize instance of pairs_vec_t with values from X_vec_t. I use the following code and it works as expected: int main() { pairs_vec_t ps; X_vec_t xs; // this is not empty in the production code ps.reserve( xs.size() ); { // I want to change this block to one line code. struct get_pair { pair_t operator()( const X& value ) { return std::make_pair( value, X2() ); } }; std::transform( xs.begin(), xs.end(), back_inserter(ps), get_pair() ); } return 0; } What I'm trying to do is to reduce my copying block to one line with using boost::bind. This code is not working: for_each( xs.begin(), xs.end(), boost::bind( &pairs_vec_t::push_back, ps, boost::bind( &std::make_pair, _1, X2() ) ) ); I know why it is not working, but I want to know how to make it working without declaring extra functions and structs?

    Read the article

  • How to get at contents of placeholder::_1

    - by sheepsimulator
    I currently have the following code: using boost::bind; typedef boost::signal<void(EventDataItem&)> EventDataItemSignal; class EventDataItem { ... EventDataItemSignal OnTrigger; ... } typedef std::list< shared_ptr<EventDataItem> > DataItemList; typedef std::list<boost::signals::connection> ConnectionList; class MyClass { void OnStart() { DataItemList dilItems; ConnectionList clConns; DataItemList::iterator iterDataItems; for(iterDataItems = dilItems.begin(); iterDataItems != dilItems.end(); iterDataItems++) { // Create Connections from Triggers clConns.push_back((*iterDataItems)->OnTrigger.connect( bind(&MyClass::OnEventTrigger, this))); } } void OnEventTrigger() { // ... Do stuff on Trigger... } } I'd like to change MyClass::OnStart to use std::transform to achieve the same thing: void MyClass::OnStart() { DataItemList dilItems; ConnectionList clConns; // Resize connection list to match number of data items clConns.resize(dilItems.size()); // Build connection list from Items // note: errors on the placeholder _1->OnTrigger std::transform(dilItems.begin(), dilItems.end(), clConns.begin(), bind(&EventDataItemSignal::connect, _1->OnTrigger, bind(&MyClass::Stuff, this))); } However, my hiccup is _1-OnTrigger. How can I reference OnTrigger from placeholder _1?

    Read the article

  • Get the signed/unsigned variant of an integer template parameter without explicit traits

    - by Blair Holloway
    I am looking to define a template class whose template parameter will always be an integer type. The class will contain two members, one of type T, and the other as the unsigned variant of type T -- i.e. if T == int, then T_Unsigned == unsigned int. My first instinct was to do this: template <typename T> class Range { typedef unsigned T T_Unsigned; // does not compile public: Range(T min, T_Unsigned range); private: T m_min; T_Unsigned m_range; }; But it doesn't work. I then thought about using partial template specialization, like so: template <typename T> struct UnsignedType {}; // deliberately empty template <> struct UnsignedType<int> { typedef unsigned int Type; }; template <typename T> class Range { typedef UnsignedType<T>::Type T_Unsigned; /* ... */ }; This works, so long as you partially specialize UnsignedType for every integer type. It's a little bit of additional copy-paste work (slash judicious use of macros), but serviceable. However, I'm now curious - is there another way of determining the signed-ness of an integer type, and/or using the unsigned variant of a type, without having to manually define a Traits class per-type? Or is this the only way to do it?

    Read the article

  • Simple dynamic memory allocation bug.

    - by M4design
    I'm sure you (pros) can identify the bug's' in my code, I also would appreciate any other comments on my code. BTW, the code crashes after I run it. #include <stdlib.h> #include <stdio.h> #include <stdbool.h> typedef struct { int x; int y; } Location; typedef struct { bool walkable; unsigned char walked; // number of times walked upon } Cell; typedef struct { char name[40]; // Name of maze Cell **grid; // 2D array of cells int rows; // Number of rows int cols; // Number of columns Location entrance; } Maze; Maze *maz_new() { int i = 0; Maze *mazPtr = (Maze *)malloc(sizeof (Maze)); if(!mazPtr) { puts("The memory couldn't be initilised, Press ENTER to exit"); getchar(); exit(-1); } else { // allocating memory for the grid mazPtr->grid = (Cell **) malloc((sizeof (Cell)) * (mazPtr->rows)); for(i = 0; i < mazPtr->rows; i++) mazPtr->grid[i] = (Cell *) malloc((sizeof (Cell)) * (mazPtr->cols)); } return mazPtr; } void maz_delete(Maze *maz) { int i = 0; if (maz != NULL) { for(i = 0; i < maz->rows; i++) free(maz->grid[i]); free(maz->grid); } } int main() { Maze *ptr = maz_new(); maz_delete(ptr); getchar(); return 0; } Thanks in advance.

    Read the article

  • undefined reference to function, despite giving reference in c

    - by Jamie Edwards
    I'm following a tutorial, but when it comes to compiling and linking the code I get the following error: /tmp/cc8gRrVZ.o: In function `main': main.c:(.text+0xa): undefined reference to `monitor_clear' main.c:(.text+0x16): undefined reference to `monitor_write' collect2: ld returned 1 exit status make: *** [obj/main.o] Error 1 What that is telling me is that I haven't defined both 'monitor_clear' and 'monitor_write'. But I have, in both the header and source files. They are as follows: monitor.c: // monitor.c -- Defines functions for writing to the monitor. // heavily based on Bran's kernel development tutorials, // but rewritten for JamesM's kernel tutorials. #include "monitor.h" // The VGA framebuffer starts at 0xB8000. u16int *video_memory = (u16int *)0xB8000; // Stores the cursor position. u8int cursor_x = 0; u8int cursor_y = 0; // Updates the hardware cursor. static void move_cursor() { // The screen is 80 characters wide... u16int cursorLocation = cursor_y * 80 + cursor_x; outb(0x3D4, 14); // Tell the VGA board we are setting the high cursor byte. outb(0x3D5, cursorLocation >> 8); // Send the high cursor byte. outb(0x3D4, 15); // Tell the VGA board we are setting the low cursor byte. outb(0x3D5, cursorLocation); // Send the low cursor byte. } // Scrolls the text on the screen up by one line. static void scroll() { // Get a space character with the default colour attributes. u8int attributeByte = (0 /*black*/ << 4) | (15 /*white*/ & 0x0F); u16int blank = 0x20 /* space */ | (attributeByte << 8); // Row 25 is the end, this means we need to scroll up if(cursor_y >= 25) { // Move the current text chunk that makes up the screen // back in the buffer by a line int i; for (i = 0*80; i < 24*80; i++) { video_memory[i] = video_memory[i+80]; } // The last line should now be blank. Do this by writing // 80 spaces to it. for (i = 24*80; i < 25*80; i++) { video_memory[i] = blank; } // The cursor should now be on the last line. cursor_y = 24; } } // Writes a single character out to the screen. void monitor_put(char c) { // The background colour is black (0), the foreground is white (15). u8int backColour = 0; u8int foreColour = 15; // The attribute byte is made up of two nibbles - the lower being the // foreground colour, and the upper the background colour. u8int attributeByte = (backColour << 4) | (foreColour & 0x0F); // The attribute byte is the top 8 bits of the word we have to send to the // VGA board. u16int attribute = attributeByte << 8; u16int *location; // Handle a backspace, by moving the cursor back one space if (c == 0x08 && cursor_x) { cursor_x--; } // Handle a tab by increasing the cursor's X, but only to a point // where it is divisible by 8. else if (c == 0x09) { cursor_x = (cursor_x+8) & ~(8-1); } // Handle carriage return else if (c == '\r') { cursor_x = 0; } // Handle newline by moving cursor back to left and increasing the row else if (c == '\n') { cursor_x = 0; cursor_y++; } // Handle any other printable character. else if(c >= ' ') { location = video_memory + (cursor_y*80 + cursor_x); *location = c | attribute; cursor_x++; } // Check if we need to insert a new line because we have reached the end // of the screen. if (cursor_x >= 80) { cursor_x = 0; cursor_y ++; } // Scroll the screen if needed. scroll(); // Move the hardware cursor. move_cursor(); } // Clears the screen, by copying lots of spaces to the framebuffer. void monitor_clear() { // Make an attribute byte for the default colours u8int attributeByte = (0 /*black*/ << 4) | (15 /*white*/ & 0x0F); u16int blank = 0x20 /* space */ | (attributeByte << 8); int i; for (i = 0; i < 80*25; i++) { video_memory[i] = blank; } // Move the hardware cursor back to the start. cursor_x = 0; cursor_y = 0; move_cursor(); } // Outputs a null-terminated ASCII string to the monitor. void monitor_write(char *c) { int i = 0; while (c[i]) { monitor_put(c[i++]); } } void monitor_write_hex(u32int n) { s32int tmp; monitor_write("0x"); char noZeroes = 1; int i; for (i = 28; i > 0; i -= 4) { tmp = (n >> i) & 0xF; if (tmp == 0 && noZeroes != 0) { continue; } if (tmp >= 0xA) { noZeroes = 0; monitor_put (tmp-0xA+'a' ); } else { noZeroes = 0; monitor_put( tmp+'0' ); } } tmp = n & 0xF; if (tmp >= 0xA) { monitor_put (tmp-0xA+'a'); } else { monitor_put (tmp+'0'); } } void monitor_write_dec(u32int n) { if (n == 0) { monitor_put('0'); return; } s32int acc = n; char c[32]; int i = 0; while (acc > 0) { c[i] = '0' + acc%10; acc /= 10; i++; } c[i] = 0; char c2[32]; c2[i--] = 0; int j = 0; while(i >= 0) { c2[i--] = c[j++]; } monitor_write(c2); } monitor.h: // monitor.h -- Defines the interface for monitor.h // From JamesM's kernel development tutorials. #ifndef MONITOR_H #define MONITOR_H #include "common.h" // Write a single character out to the screen. void monitor_put(char c); // Clear the screen to all black. void monitor_clear(); // Output a null-terminated ASCII string to the monitor. void monitor_write(char *c); #endif // MONITOR_H common.c: // common.c -- Defines some global functions. // From JamesM's kernel development tutorials. #include "common.h" // Write a byte out to the specified port. void outb ( u16int port, u8int value ) { asm volatile ( "outb %1, %0" : : "dN" ( port ), "a" ( value ) ); } u8int inb ( u16int port ) { u8int ret; asm volatile ( "inb %1, %0" : "=a" ( ret ) : "dN" ( port ) ); return ret; } u16int inw ( u16int port ) { u16int ret; asm volatile ( "inw %1, %0" : "=a" ( ret ) : "dN" ( port ) ); return ret; } // Copy len bytes from src to dest. void memcpy(u8int *dest, const u8int *src, u32int len) { const u8int *sp = ( const u8int * ) src; u8int *dp = ( u8int * ) dest; for ( ; len != 0; len-- ) *dp++ =*sp++; } // Write len copies of val into dest. void memset(u8int *dest, u8int val, u32int len) { u8int *temp = ( u8int * ) dest; for ( ; len != 0; len-- ) *temp++ = val; } // Compare two strings. Should return -1 if // str1 < str2, 0 if they are equal or 1 otherwise. int strcmp(char *str1, char *str2) { int i = 0; int failed = 0; while ( str1[i] != '\0' && str2[i] != '\0' ) { if ( str1[i] != str2[i] ) { failed = 1; break; } i++; } // Why did the loop exit? if ( ( str1[i] == '\0' && str2[i] != '\0' || (str1[i] != '\0' && str2[i] =='\0' ) ) failed =1; return failed; } // Copy the NULL-terminated string src into dest, and // return dest. char *strcpy(char *dest, const char *src) { do { *dest++ = *src++; } while ( *src != 0 ); } // Concatenate the NULL-terminated string src onto // the end of dest, and return dest. char *strcat(char *dest, const char *src) { while ( *dest != 0 ) { *dest = *dest++; } do { *dest++ = *src++; } while ( *src != 0 ); return dest; } common.h: // common.h -- Defines typedefs and some global functions. // From JamesM's kernel development tutorials. #ifndef COMMON_H #define COMMON_H // Some nice typedefs, to standardise sizes across platforms. // These typedefs are written for 32-bit x86. typedef unsigned int u32int; typedef int s32int; typedef unsigned short u16int; typedef short s16int; typedef unsigned char u8int; typedef char s8int; void outb ( u16int port, u8int value ); u8int inb ( u16int port ); u16int inw ( u16int port ); #endif //COMMON_H main.c: // main.c -- Defines the C-code kernel entry point, calls initialisation routines. // Made for JamesM's tutorials <www.jamesmolloy.co.uk> #include "monitor.h" int main(struct multiboot *mboot_ptr) { monitor_clear(); monitor_write ( "hello, world!" ); return 0; } here is my makefile: C_SOURCES= main.c monitor.c common.c S_SOURCES= boot.s C_OBJECTS=$(patsubst %.c, obj/%.o, $(C_SOURCES)) S_OBJECTS=$(patsubst %.s, obj/%.o, $(S_SOURCES)) CFLAGS=-nostdlib -nostdinc -fno-builtin -fno-stack-protector -m32 -Iheaders LDFLAGS=-Tlink.ld -melf_i386 --oformat=elf32-i386 ASFLAGS=-felf all: kern/kernel .PHONY: clean clean: -rm -f kern/kernel kern/kernel: $(S_OBJECTS) $(C_OBJECTS) ld $(LDFLAGS) -o $@ $^ $(C_OBJECTS): obj/%.o : %.c gcc $(CFLAGS) $< -o $@ vpath %.c source $(S_OBJECTS): obj/%.o : %.s nasm $(ASFLAGS) $< -o $@ vpath %.s asem Hopefully this will help you understand what is going wrong and how to fix it :L Thanks in advance. Jamie.

    Read the article

  • How to iterate over modifed std::map values?

    - by Frank
    I have an std::map, and I would like to define an iterator that returns modified values. Typically, a std::map<int,double>::iterator iterates over std::pair<int,double>, and I would like the same behavior, just the double value is multiplied by a constant. I tried it with boost::transform_iterator, but it doesn't compile: #include <map> #include <boost/iterator/transform_iterator.hpp> #include <boost/functional.hpp> typedef std::map<int,double> Map; Map m; m[100] = 2.24; typedef boost::binder2nd< std::multiplies<double> > Function; typedef boost::transform_iterator<Function, Map::value_type*> MultiplyIter; MultiplyIter begin = boost::make_transform_iterator(m.begin(), Function(std::multiplies<double>(), 4)); // now want to similarly create an end iterator // and then iterate over the modified map The error is: error: conversion from 'boost ::transform_iterator< boost::binder2nd<multiplies<double> >, gen_map<int, double>::iterator , boost::use_default, boost::use_default >' to non-scalar type 'boost::transform_iterator< boost::binder2nd<multiplies<double> >, pair<const int, double> * , boost::use_default, boost::use_default >' requested What is gen_map and do I really need it? I adapted the transform_iterator tutorial code from here to write this code ...

    Read the article

  • template style matrix implementation in c

    - by monkeyking
    From time to time I use the following code for generating a matrix style datastructure typedef double myType; typedef struct matrix_t{ |Compilation started at Mon Apr 5 02:24:15 myType **matrix; | size_t x; |gcc structreaderGeneral.c -std=gnu99 -lz size_t y; | }matrix; |Compilation finished at Mon Apr 5 02:24:15 | | matrix alloc_matrix(size_t x, size_t y){ | if(0) | fprintf(stderr,"\t-> Alloc matrix with dim (%lu,%lu) byteprline=%lu bytetotal:%l\| u\n",x,y,y*sizeof(myType),x*y*sizeof(myType)); | | myType **m = (myType **)malloc(x*sizeof(myType **)); | for(size_t i=0;i<x;i++) | m[i] =(myType *) malloc(y*sizeof(myType *)); | | matrix ret; | ret.x=x; | ret.y=y; | ret.matrix=m; | return ret; | } And then I would change my typedef accordingly if I needed a different kind of type for the entries in my matrix. Now I need 2 matrices with different types, an easy solution would be to copy/paste the code, but is there some way to do a template styled implementation. Thanks

    Read the article

  • How to use boost::transform_iterator to iterate over modifed std::map values?

    - by Frank
    I have an std::map, and I would like to define an iterator that returns modified values. Typically, a std::map<int,double>::iterator iterates over std::pair<int,double>, and I would like the same behavior, just the double value is multiplied by a constant. I tried it with boost::transform_iterator, but it doesn't compile: #include <map> #include <boost/iterator/transform_iterator.hpp> #include <boost/functional.hpp> typedef std::map<int,double> Map; Map m; m[100] = 2.24; typedef boost::binder2nd< std::multiplies<double> > Function; typedef boost::transform_iterator<Function, Map::value_type*> MultiplyIter; MultiplyIter begin = boost::make_transform_iterator(m.begin(), Function(std::multiplies<double>(), 4)); // now want to similarly create an end iterator // and then iterate over the modified map The error is: error: conversion from 'boost ::transform_iterator< boost::binder2nd<multiplies<double> >, gen_map<int, double>::iterator , boost::use_default, boost::use_default >' to non-scalar type 'boost::transform_iterator< boost::binder2nd<multiplies<double> >, pair<const int, double> * , boost::use_default, boost::use_default >' requested What is gen_map and do I really need it? I adapted the transform_iterator tutorial code from here to write this code ...

    Read the article

  • error: invalid type argument of '->' (have 'struct node')

    - by Roshan S.A
    Why cant i access the pointer "Cells" like an array ? i have allocated the appropriate memory why wont it act like an array here? it works like an array for a pointer of basic data types. #include<stdio.h> #include<stdlib.h> #include<ctype.h> #define MAX 10 struct node { int e; struct node *next; }; typedef struct node *List; typedef struct node *Position; struct Hashtable { int Tablesize; List Cells; }; typedef struct Hashtable *HashT; HashT Initialize(int SIZE,HashT H) { int i; H=(HashT)malloc(sizeof(struct Hashtable)); if(H!=NULL) { H->Tablesize=SIZE; printf("\n\t%d",H->Tablesize); H->Cells=(List)malloc(sizeof(struct node)* H->Tablesize); should it not act like an array from here on? if(H->Cells!=NULL) { for(i=0;i<H->Tablesize;i++) the following lines are the ones that throw the error { H->Cells[i]->next=NULL; H->Cells[i]->e=i; printf("\n %d",H->Cells[i]->e); } } } else printf("\nError!Out of Space"); } int main() { HashT H; H=Initialize(10,H); return 0; } The error I get is as in the title-error: invalid type argument of '->' (have 'struct node').

    Read the article

  • Boost multi_index_container crash in release mode

    - by Zan Lynx
    I have a program that I just changed to using a boost::multi_index_container collection. After I did that and tested my code in debug mode, I was feeling pretty good about myself. However, then I compiled a release build with NDEBUG set, and the code crashed. Not immediately, but sometimes in single-threaded tests and often in multi-threaded tests. The segmentation faults happen deep inside boost insert and rotate functions related to the index updates and they are happening because a node has NULL left and right pointers. My code looks a bit like this: struct Implementation { typedef std::pair<uint32_t, uint32_t> update_pair_type; struct watch {}; struct update {}; typedef boost::multi_index_container< update_pair_type, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< boost::multi_index::tag<watch>, boost::multi_index::member<update_pair_type, uint32_t, &update_pair_type::first> >, boost::multi_index::ordered_non_unique< boost::multi_index::tag<update>, boost::multi_index::member<update_pair_type, uint32_t, &update_pair_type::second> > > > update_map_type; typedef std::vector< update_pair_type > update_list_type; update_map_type update_map; update_map_type::iterator update_hint; void register_update(uint32_t watch, uint32_t update); void do_updates(uint32_t start, uint32_t end); }; void Implementation::register_update(uint32_t watch, uint32_t update) { update_pair_type new_pair( watch_offset, update_offset ); update_hint = update_map.insert(update_hint, new_pair); if( update_hint->second != update_offset ) { bool replaced _unused_ = update_map.replace(update_hint, new_pair); assert(replaced); } }

    Read the article

  • How do I cast a void pointer to a struct in C?

    - by Rowhawn
    In a project I'm writing code for, I have a void pointer, "implementation", which is a member of a "Hash_map" struct, and points to an "Array_hash_map" struct. The concepts behind this project are not very realistic, but bear with me. The specifications of the project ask that I cast the void pointer "implementation" to an "Array_hash_map" before I can use it in any functions. My question, specifically is, what do I do in the functions to cast the void pointers to the desired struct? Is there one statement at the top of each function that casts them or do I make the cast every time I use "implementation"? Here are the typedefs the structs of a Hash_map and Array_hash_map as well as a couple functions making use of them. typedef struct { Key_compare_fn key_compare_fn; Key_delete_fn key_delete_fn; Data_compare_fn data_compare_fn; Data_delete_fn data_delete_fn; void *implementation; } Hash_map; typedef struct Array_hash_map{ struct Unit *array; int size; int capacity; } Array_hash_map; typedef struct Unit{ Key key; Data data; } Unit; functions: /* Sets the value parameter to the value associated with the key parameter in the Hash_map. */ int get(Hash_map *map, Key key, Data *value){ int i; if (map == NULL || value == NULL) return 0; for (i = 0; i < map->implementation->size; i++){ if (map->key_compare_fn(map->implementation->array[i].key, key) == 0){ *value = map->implementation->array[i].data; return 1; } } return 0; } /* Returns the number of values that can be stored in the Hash_map, since it is represented by an array. */ int current_capacity(Hash_map map){ return map.implementation->capacity; }

    Read the article

  • Providing less than operator for one element of a pair

    - by Koszalek Opalek
    What would be the most elegant way too fix the following code: #include <vector> #include <map> #include <set> using namespace std; typedef map< int, int > row_t; typedef vector< row_t > board_t; typedef row_t::iterator area_t; bool operator< ( area_t const& a, area_t const& b ) { return( a->first < b->first ); }; int main( int argc, char* argv[] ) { int row_num; area_t it; set< pair< int, area_t > > queue; queue.insert( make_pair( row_num, it ) ); // does not compile }; One way to fix it is moving the definition of less< to namespace std (I know, you are not supposed to do it.) namespace std { bool operator< ( area_t const& a, area_t const& b ) { return( a->first < b->first ); }; }; Another obvious solution is defining less than< for pair< int, area_t but I'd like to avoid that and be able to define the operator only for the one element of the pair where it is not defined.

    Read the article

  • C++. How to define template parameter of type T for class A when class T needs a type A template parameter?

    - by jaybny
    Executor class has template of type P and it takes a P object in constructor. Algo class has a template E and also has a static variable of type E. Processor class has template T and a collection of Ts. Question how can I define Executor< Processor<Algo> > and Algo<Executor> ? Is this possible? I see no way to defining this, its kind of an "infinite recursive template argument" See code. template <class T> class Processor { map<string,T> ts; void Process(string str, int i) { ts[str].Do(i); } } template <class P> class Executor { Proc &p; Executor(P &p) : Proc(p) {} void Foo(string str, int i) { p.Process(str,i); } Execute(string str) { } } template <class E> class Algo { static E e; void Do(int i) {} void Foo() { e.Execute("xxx"); } } main () { typedef Processor<Algo> PALGO; // invalid typedef Executor<PALGO> EPALGO; typedef Algo<EPALGO> AEPALGO; Executor<PALGO> executor(PALGO()); AEPALGO::E = executor; }

    Read the article

  • What is the rationale to not allow overloading of C++ conversions operator with non-member function

    - by Vicente Botet Escriba
    C++0x has added explicit conversion operators, but they must always be defined as members of the Source class. The same applies to the assignment operator, it must be defined on the Target class. When the Source and Target classes of the needed conversion are independent of each other, neither the Source can define a conversion operator, neither the Target can define a constructor from a Source. Usually we get it by defining a specific function such as Target ConvertToTarget(Source& v); If C++0x allowed to overload conversion operator by non member functions we could for example define the conversion implicitly or explicitly between unrelated types. template < typename To, typename From > operator To(const From& val); For example we could specialize the conversion from chrono::time_point to posix_time::ptime as follows template < class Clock, class Duration> operator boost::posix_time::ptime( const boost::chrono::time_point<Clock, Duration>& from) { using namespace boost; typedef chrono::time_point<Clock, Duration> time_point_t; typedef chrono::nanoseconds duration_t; typedef duration_t::rep rep_t; rep_t d = chrono::duration_cast<duration_t>( from.time_since_epoch()).count(); rep_t sec = d/1000000000; rep_t nsec = d%1000000000; return posix_time::from_time_t(0)+ posix_time::seconds(static_cast<long>(sec))+ posix_time::nanoseconds(nsec); } And use the conversion as any other conversion. For a more complete description of the problem, see here or on my Boost.Conversion library.. So the question is: What is the rationale to non allow overloading of C++ conversions operator with non-member functions?

    Read the article

  • pointer to a structure in a nested structure

    - by dpka6
    I have a 6 levels of nested structures. I am having problem with last three levels. The program compiles fine but when I run it crashes with Segmentation fault. There is some problem in assignment is what I feel. Kindly point out the error. typedef struct { char addr[6]; int32_t rs; uint16_t ch; uint8_t ap; } C; typedef struct { C *ap_info; } B; typedef struct { union { B wi; } u; } A; function1(char addr , int32_t rs, uint16_t ch, uint8_t ap){ A la; la.u.wi.ap_info->addr[6] = addr; la.u.wi.ap_info->rs = rs; la.u.wi.ap_info->ch = ch; la.u.wi.ap_info->ap = ap; }

    Read the article

  • Interpretation of int (*a)[3]

    - by kapuzineralex
    When working with arrays and pointers in C, one quickly discovers that they are by no means equivalent although it might seem so at a first glance. I know about the differences in L-values and R-values. Still, recently I tried to find out the type of a pointer that I could use in conjunction with a two-dimensional array, i.e. int foo[2][3]; int (*a)[3] = foo; However, I just can't find out how the compiler "understands" the type definition of a in spite of the regular operator precedence rules for * and []. If instead I were to use a typedef, the problem becomes significantly simpler: int foo[2][3]; typedef int my_t[3]; my_t *a = foo; At the bottom line, can someone answer me the questions as to how the term int (*a)[3] is read by the compiler? int a[3] is simple, int *a[3] is simple as well. But then, why is it not int *(a[3])? EDIT: Of course, instead of "typecast" I meant "typedef" (it was just a typo).

    Read the article

  • C++ STL: How to iterate vector while requiring access to element and its index?

    - by Ashwin
    I frequently find myself requiring to iterate over STL vectors. While I am doing this I require access to both the vector element and its index. I used to do this as: typedef std::vector<Foo> FooVec; typedef FooVec::iterator FooVecIter; FooVec fooVec; int index = 0; for (FooVecIter i = fooVec.begin(); i != fooVec.end(); ++i, ++index) { Foo& foo = *i; if (foo.somethingIsTrue()) // True for most elements std::cout << index << ": " << foo << std::endl; } After discovering BOOST_FOREACH, I shortened this to: typedef std::vector<Foo> FooVec; FooVec fooVec; int index = -1; BOOST_FOREACH( Foo& foo, fooVec ) { ++index; if (foo.somethingIsTrue()) // True for most elements std::cout << index << ": " << foo << std::endl; } Is there a better or more elegant way to iterate over STL vectors when both reference to the vector element and its index is required? I am aware of the alternative: for (int i = 0; i < fooVec.size(); ++i) But I keep reading about how it is not a good practice to iterate over STL containers like this.

    Read the article

  • Why does Go not seem to recognize size_t in a C header file?

    - by Graeme Perrow
    I am trying to write a go library that will act as a front-end for a C library. If one of my C structures contains a size_t, I get compilation errors. AFAIK size_t is a built-in C type, so why wouldn't go recognize it? My header file looks like: typedef struct mystruct { char * buffer; size_t buffer_size; size_t * length; } mystruct; and the errors I'm getting are: gcc failed: In file included from <stdin>:5: mydll.h:4: error: expected specifier-qualifier-list before 'size_t' on input: typedef struct { char *p; int n; } _GoString_; _GoString_ GoString(char *p); char *CString(_GoString_); #include "mydll.h" I've even tried adding either of // typedef unsigned long size_t or // #define size_t unsigned long in the .go file before the // #include, and then I get "gcc produced no output". I have seen these questions, and looked over the example with no success.

    Read the article

  • Int Showing as Long Odd Value

    - by Josh Kahane
    Hi I am trying to send an int in my iphone game for game center multiplayer. The integer is coming up and appearing as an odd long integer value rather than the expected one. I have this in my .h: typedef enum { kPacketTypeScore, } EPacketTypes; typedef struct { EPacketTypes type; size_t size; } SPacketInfo; typedef struct { SPacketInfo packetInfo; int score; } SScorePacket; Then .m: Sending data: scoreData *score = [scoreData sharedData]; SScorePacket packet; packet.packetInfo.type = kPacketTypeScore; packet.packetInfo.size = sizeof(SScorePacket); packet.score = score.score; NSData* dataToSend = [NSData dataWithBytes:&packet length:packet.packetInfo.size]; NSError *error; [self.myMatch sendDataToAllPlayers: dataToSend withDataMode: GKMatchSendDataUnreliable error:&error]; if (error != nil) { // handle the error } Receiving: SPacketInfo* packet = (SPacketInfo*)[data bytes]; switch (packet->type) { case kPacketTypeScore: { SScorePacket* scorePacket = (SScorePacket*)packet; scoreData *score = [scoreData sharedData]; [scoreLabel setString:[NSString stringWithFormat:@"You: %d Challenger: %d", score.score, scorePacket]]; break; } default: CCLOG(@"received unknown packet type %i (size: %u)", packet->type, packet->size); break; } Any ideas? Thanks.

    Read the article

  • What are the C# equivalent of these C++ structs

    - by Otake
    typedef union _Value { signed char c; unsigned char b; signed short s; unsigned short w; signed long l; unsigned long u; float f; double *d; char *p; } Value; typedef struct _Field { WORD nFieldId; BYTE bValueType; Value Value; } Field; typedef struct _Packet { WORD nMessageType; WORD nSecurityType; BYTE bExchangeId; BYTE bMarketCenter; int iFieldCount; char cSymbol[20]; Field FieldArr[1]; } Packet; What are the C# equivalent of these C++ structs? I am migrating some code from C++ to C# and having problems to migrate these structures. I had tried a few things but I always ended up having marshalling problems.

    Read the article

  • Problem with incomplete type while trying to detect existence of a member function

    - by abir
    I was trying to detect existence of a member function for a class where the function tries to use an incomplete type. The typedef is struct foo; typedef std::allocator<foo> foo_alloc; The detection code is struct has_alloc { template<typename U,U x> struct dummy; template<typename U> static char check(dummy<void* (U::*)(std::size_t),&U::allocate>*); template<typename U> static char (&check(...))[2]; const static bool value = (sizeof(check<foo_alloc>(0)) == 1); }; So far I was using incomplete type foo with std::allocator without any error on VS2008. However when I replaced it with nearly an identical implementation as template<typename T> struct allocator { T* allocate(std::size_t n) { return (T*)operator new (sizeof(T)*n); } }; it gives an error saying that as T is incomplete type it has problem instantiating allocator<foo> because allocate uses sizeof. GCC 4.5 with std::allocator also gives the error, so it seems during detection process the class need to be completely instantiated, even when I am not using that function at all. What I was looking for is void* allocate(std::size_t) which is different from T* allocate(std::size_t). My questions are (I have three questions, but as they are correlated , so I thought it is better not to create three separate questions). Why MS std::allocator doesn't check for incomplete type foo while instantiating? Are they following any trick which can be implemented ? Why the compiler need to instantiate allocator<T> to check the existence of the function when sizeof is not used as sfinae mechanism to remove/add allocate in the overload resolutions set? It should be noted that, if I remove the generic implementation of allocate leaving the declaration only, and specialized it for foo afterwards such as struct foo{}; template< struct allocator { foo* allocate(std::size_t n) { return (foo*)operator new (sizeof(foo)*n); } }; after struct has_alloc it compiles in GCC 4.5 while gives error in VS2008 as allocator<T> is already instantiated and explicit specialization for allocator<foo> already defined. Is it legal to use nested types for an std::allocator of incomplete type such as typedef foo_alloc::pointer foo_pointer; ? Though it is practically working for me, I suspect the nested types such as pointer may depend on completeness of type it takes. It will be good to know if there is any possible way to typedef such types as foo_pointer where the type pointer depends on completeness of foo. NOTE : As the code is not copy paste from editor, it may have some syntax error. Will correct it if I find any. Also the codes (such as allocator) are not complete implementation, I simplified and typed only the portion which I think useful for this particular problem.

    Read the article

  • Dynamic obfuscation by self-modifying code

    - by Fallout2
    Hi all, Here what's i am trying to do: assume you have two fonction void f1(int *v) { *v = 55; } void f2(int *v) { *v = 44; } char *template; template = allocExecutablePages(...); char *allocExecutablePages (int pages) { template = (char *) valloc (getpagesize () * pages); if (mprotect (template, getpagesize (), PROT_READ|PROT_EXEC|PROT_WRITE) == -1) { perror (“mprotect”); } } I would like to do a comparison between f1 and f2 (so tell what is identical and what is not) (so get the assembly lines of those function and make a line by line comparison) And then put those line in my template. Is there a way in C to do that? THanks Update Thank's for all you answers guys but maybe i haven't explained my need correctly. basically I'm trying to write a little obfuscation method. The idea consists in letting two or more functions share the same location in memory. A region of memory (which we will call a template) is set up containing some of the machine code bytes from the functions, more specifically, the ones they all have in common. Before a particular function is executed, an edit script is used to patch the template with the necessary machine code bytes to create a complete version of that function. When another function assigned to the same template is about to be executed, the process repeats, this time with a different edit script. To illustrate this, suppose you want to obfuscate a program that contains two functions f1 and f2. The first one (f1) has the following machine code bytes Address Machine code 0 10 1 5 2 6 3 20 and the second one (f2) has Address Machine code 0 10 1 9 2 3 3 20 At obfuscation time, one will replace f1 and f2 by the template Address Machine code 0 10 1 ? 2 ? 3 20 and by the two edit scripts e1 = {1 becomes 5, 2 becomes 6} and e2 = {1 becomes 9, 2 becomes 3}. #include <stdlib.h> #include <string.h> typedef unsigned int uint32; typedef char * addr_t; typedef struct { uint32 offset; char value; } EDIT; EDIT script1[200], script2[200]; char *template; int template_len, script_len = 0; typedef void(*FUN)(int *); int val, state = 0; void f1_stub () { if (state != 1) { patch (script1, script_len, template); state = 1; } ((FUN)template)(&val); } void f2_stub () { if (state != 2) { patch (script2, script_len, template); state = 2; } ((FUN)template)(&val); } int new_main (int argc, char **argv) { f1_stub (); f2_stub (); return 0; } void f1 (int *v) { *v = 99; } void f2 (int *v) { *v = 42; } int main (int argc, char **argv) { int f1SIZE, f2SIZE; /* makeCodeWritable (...); */ /* template = allocExecutablePages(...); */ /* Computed at obfuscation time */ diff ((addr_t)f1, f1SIZE, (addr_t)f2, f2SIZE, script1, script2, &script_len, template, &template_len); /* We hide the proper code */ memset (f1, 0, f1SIZE); memset (f2, 0, f2SIZE); return new_main (argc, argv); } So i need now to write the diff function. that will take the addresses of my two function and that will generate a template with the associated script. So that is why i would like to compare bytes by bytes my two function Sorry for my first post who was not very understandable! Thank you

    Read the article

  • std::basic_string full specialization (g++ conflict)

    - by SoapBox
    I am trying to define a full specialization of std::basic_string< char, char_traits<char>, allocator<char> > which is typedef'd (in g++) by the <string> header. The problem is, if I include <string> first, g++ sees the typedef as an instantiation of basic_string and gives me errors. If I do my specialization first then I have no issues. I should be able to define my specialization after <string> is included. What do I have to do to be able to do that? My Code: #include <bits/localefwd.h> //#include <string> // <- uncommenting this line causes compilation to fail namespace std { template<> class basic_string< char, char_traits<char>, allocator<char> > { public: int blah() { return 42; } size_t size() { return 0; } const char *c_str() { return ""; } void reserve(int) {} void clear() {} }; } #include <string> #include <iostream> int main() { std::cout << std::string().blah() << std::endl; } The above code works fine. But, if I uncomment the first #include <string> line, I get the following compiler errors: blah.cpp:7: error: specialization of ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ after instantiation blah.cpp:7: error: redefinition of ‘class std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ /usr/include/c++/4.4/bits/stringfwd.h:52: error: previous definition of ‘class std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ blah.cpp: In function ‘int main()’: blah.cpp:22: error: ‘class std::string’ has no member named ‘blah’ Line 52 of /usr/include/c++/4.4/bits/stringfwd.h: template<typename _CharT, typename _Traits = char_traits<_CharT>, typename _Alloc = allocator<_CharT> > class basic_string; As far as I know this is just a forward delcaration of the template, NOT an instantiation as g++ claims. Line 56 of /usr/include/c++/4.4/bits/stringfwd.h: typedef basic_string<char> string; As far as I know this is just a typedef, NOT an instantiation either. So why are these lines conflicting with my code? What can I do to fix this other than ensuring that my code is always included before <string>?

    Read the article

  • organization of DLL linked functions

    - by m25
    So this is a code organization question. I got my basic code working but when I expand it will be terrible. I have a DLL that I don't have a .lib for. Therefore I have to use the whole loadLibrary()/getprocaddress() combo. it works great. But this DLL that i'm referencing at 100+ functions. my current process is (1) typedef a type for the function. or typedef short(_stdcall *type1)(void); then (2) assign a function name that I want to use such as type1 function_1, then (3) I do the whole LoadLibrary, then do something like function_1 = (type1)GetProcAddress(hinstLib, "_mangled_funcName@5"); normally I would like to do all of my function definitions in a header file but because I have to do use the load library function, its not that easy. the code will be a mess. Right now i'm doing (1) and (2) in a header file and was considering making a function in another .cpp file to do the load library and dump all of the (3)'s in there. I considered using a namespace for the functions so I can use them in the main function and not have to pass over to the other function. Any other tips on how to organize this code to where it is readable and organized? My goals are to be able to use function_1 as a regular function in the main code. if I have to a ref::function_1 that would be okay but I would prefer to avoid it. this code for all practical purposes is just plane C at the moment. thanks in advance for any advice!

    Read the article

  • Parallelize code using CUDA [migrated]

    - by user878944
    If I have a code which takes struct variable as input and manipulate it's elements, how can I parallelize this using CUDA? void BackpropagateLayer(NET* Net, LAYER* Upper, LAYER* Lower) { INT i,j; REAL Out, Err; for (i=1; i<=Lower->Units; i++) { Out = Lower->Output[i]; Err = 0; for (j=1; j<=Upper->Units; j++) { Err += Upper->Weight[j][i] * Upper->Error[j]; } Lower->Error[i] = Net->Gain * Out * (1-Out) * Err; } } Where NET and LAYER are structs defined as: typedef struct { /* A LAYER OF A NET: */ INT Units; /* - number of units in this layer */ REAL* Output; /* - output of ith unit */ REAL* Error; /* - error term of ith unit */ REAL** Weight; /* - connection weights to ith unit */ REAL** WeightSave; /* - saved weights for stopped training */ REAL** dWeight; /* - last weight deltas for momentum */ } LAYER; typedef struct { /* A NET: */ LAYER** Layer; /* - layers of this net */ LAYER* InputLayer; /* - input layer */ LAYER* OutputLayer; /* - output layer */ REAL Alpha; /* - momentum factor */ REAL Eta; /* - learning rate */ REAL Gain; /* - gain of sigmoid function */ REAL Error; /* - total net error */ } NET; What I could think of is to first convert the 2d Weight into 1d. And then send it to kernel to take the product or just use the CUBLAS library. Any suggestions?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >