question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
7,922,228
7,922,291
how to perform a index search from an array
im trying to perform an index search for string, it runs but the problem is that it only prints out i[0] which is my first entry. if i lookup another entry it doesn't work. Please help.. void clist(string fn[],string ln[], int size); int search_list(const string fn[],const string ln[], int size, string find); int ...
You are making a loop and explicitly telling it to break out of it after the first iteration. Try writting it like this: bool found = false; for(int i=0;i<size;i++){ if(fn[i] == search){ // No need to check for(i < size) found = true; cout<<"Result found "<<fn[i]<<" "<<ln[i]<<endl; break; } } if(!found) c...
7,922,545
7,922,598
What is the best equivalent of objective-c NSString * in C++?
I am porting an objective-c application to C++ and am fairly new in either language. In the class I'm handling right now there are quite many fields that are string literals NSString or pointers to string NSString *. What is the best equivalent of those fields in C++: std::string, std::string * or const char *? Initial...
NSString is an immutable string, so const std::string is the right choice. If you use it as reference everywhere, you wouldn't have copies.
7,922,632
7,922,681
Return the enumeration instead of the index
I have a simple class that uses an enum for "status". When I use the getStatus member function, it does indeed return "Busy" but when I print the value, it shows a "1". How can I print "Busy" instead of 1? http://codepad.org/9NDlxxyU demonstration #include <iostream> using namespace std; enum Status{Idle, Busy}; cl...
A fully working edit is live here: http://ideone.com/WFo4g Add: std::ostream& operator<<(std::ostream& os, const Status status) { switch (status) { case Idle: return os << "Idle"; case Busy: return os << "Busy"; default: return os << "Status:" << status; } return os << "<error...
7,922,650
7,922,951
wxWidgets reading from socket
I am having problems converting what is being read from a socket in wxWidgets to a wxString. I am doing like so: wxChar * readBuffer = new wxChar[256]; wxSocketClient * connection = new wxSocketClient(); connection->Connect(addr, true); connection->Read(readBuffer, 256); wxString wasRead(readBuffer); std::cout << wasRe...
Your readBuffer might well not be null terminated. In fact, it might contain only a partial message. The simplest 'fix' is to ensure that it is null terminated You can use LastCount() to determine number of bytes actually read. However, the real fix is to set up a simple protocol between your server and client, so tha...
7,922,665
7,922,716
Converting malloc to new
I am compiling using g++. This is valid but I want to convert to the C++ operators new() and delete() because this is considered best practice. int *scratch = (int *)malloc(size * sizeof(int)); free(scratch); What is the equivalent using new and delete? This is my guess. int **scratch = new int*[size]; delete[...
You probably want to do: std::vector<int> scratch(size); But for the record, what you tried should be: int* scratch = new int[size]; delete[] scratch; Note that if size is known at compile-time, you also simply do: int scratch[size]; Edit For an array of pointers to int, the desired syntax is: int** scratch = new in...
7,922,804
7,923,824
code challenge questions for a game during lunch
So, I will be hosting a lunch and I am looking for an interesting activity. I remember having seen a google tech talk video that, in the beginning, had a series of "what will this code do" puzzles in c or c++, and I thought it would be a good idea to do something similar. Do you know which that video was, as I cannot ...
Figure out what this will print: #include <stdio.h> char *c[]= { "ENTER", "NEW", "POINT", "FIRST" }; char **cp[]={c+3,c+2,c+1,c}; char ***cpp=cp; int main(void) { printf("%s",**++cpp); printf("%s ",*--*++cpp+3); printf("%s",*cpp[-2]+3); printf("%s\n",c...
7,922,843
10,296,624
Numerical recipes / Multidimensional root search (using newt) : How to minimize the maximum error
This question is related to the "numerical recipes in C++" book, so it will be reserved to people knowing a little about it as well as about multidimensional optimization. I am writing a program that needs to search for a multidimensional root, and in order to solve it, I am using the multidimensional newton root findi...
You try to minimize F(x) by solving f(x)=0 where x is an m-dimensional vector and f maps this to an n-dimensional vector. Your optimization problem is underdetermined if m < n (in your case 11 < 14). For such systems, the generic way to solve them is to minimize a vector norm on x. You can do this by minimizing the sy...
7,922,937
7,922,954
Allow stringstream and outstream as parameter
I'm trying to write a function that writes information to a stream. I need to be able to pass it either a stringstream or an ostream. I tried declaring the function with F(std::ios* out), but then later when I use the << operator to write to it, I get this error: error: no match for operator<<. How should I be declarin...
I think you are looking for c++ references void F(std::ostream& out) { } would do the trick; Note that this will assume char streams, otherwise: template <typename Char/*=char*/, typename Traits/*=std::char_traits<CharT> */> void F(std::basic_ostream<Char, Traits>& os) { }
7,923,165
7,923,191
C++ cin vs. C sscanf
So i wrote this in C, so sscanf scans in s but then discards it, then scans in d and stores it. So if the input is "Hello 007", Hello is scanned but discarded and 007 is stored in d. static void cmd_test(const char *s) { int d = maxdepth; sscanf(s, "%*s%d", &d); } So, my question is how can I do the same thing...
#include <string> #include <sstream> static void cmd_test(const char *s) { std::istringstream iss(s); std::string dummy; int d = maxdepth; iss >> dummy >> d; }
7,923,208
7,923,271
C++: Unresolved externals driving me nuts
I'm taking a class on C++ and this is driving me berserk. The funnest part is that no guide seems to tell me exactly what to do and no question seems to address the problem here. It's probably due in part to the issue of multiple C++ compilers. I'm using Visual Studio 2010 and I'm just trying to build a class with oper...
You are clearly learning things. I took the time to fix a number of 'minor' issues that will really be hampering your progress; I hope my stenographic explanations will put you on the right path. You are redefining the class in a cpp file; this is not proper C++ (declare the class in the header, define the implementat...
7,923,278
7,923,870
SQLite: how to SELECT a range of records?
I want to create a DB table and a set of commands for it. So currently I have this->command_create_files_table = "CREATE TABLE IF NOT EXISTS files (encoded_url varchar(300) UNIQUE NOT NULL primary key, file_name varchar(150) NOT NULL, user_name varchar(65) NOT NULL, is_public BOOLEAN NOT NULL, modified DATETIME NOT NUL...
SELECT fields_you_want_to_select FROM filesTbl WHERE DATETIME > start_of_range AND DATETIME < end_of_range LIMIT 25
7,923,369
7,923,419
When is the "typename" keyword necessary?
Possible Duplicate: Officially, what is typename for? Where and why do I have to put the template and typename keywords? consider the code below: template<class K> class C { struct P {}; vector<P> vec; void f(); }; template<class K> void C<K>::f() { typename vector<P>::iterator p = vec.begin(); } Wh...
Short answer: Whenever referring to a nested name that is a dependent name, i.e. nested inside a template instance with unknown parameter. Long answer: There are three tiers of entities in C++: values, types, and templates. All of those can have names, and the name alone doesn't tell you which tier of entity it is. Rat...
7,923,392
7,923,438
C++ Extern Class Declaration
I wrote a little test program to show here. Here is the source code. main.cpp: #include "core.h" Core core; int main() { core.coreFunction(); } core.h: #ifndef CORE_H__ #define CORE_H__ #include "definitions.h" #include "window.h" class Core { public: Window window; void coreFunction() { window.windowF...
You are including the window.h header before the "extern Core core;" line. Try adding that line just before the class Window line on the window.h header: window.h #ifndef WINDOW_H__ #define WINDOW_H__ extern Core core; class Window {...} Instead of using Core as a global variable, you can move core as a static membe...
7,923,454
7,923,491
C++ Template Metaprogramming Specialization Ambiguity
So I'm just starting out with template metaprogramming and I have been writing a string class. I implemented ToString, Concat, CharAt, and Length without too many template-related problems. I was trying to implement Substring as follows: struct Null; // String class definition template <char C, class S> struct String ...
Here you define a Substring with 0, 0 and any class S: template <class S> struct Substring<0, 0, S> { typedef Null substr; }; Here you define a Substring with I, L and a String< C, S >: template <int I, int L, char C, class S> struct Substring<I, L, String<C, S> > { typedef typename Substring<I-1, L, S>::substr su...
7,923,485
7,923,607
Simplest QT TCP client
I would like to connect to a listening server and transmit some data. I looked at the examples available but they seem to have extra functions that do not seem very helpful to me (i.e. connect, fortune, etc.). This is the code I have so far: QTcpSocket t; t.connectToHost("127.0.0.1", 9000); Assuming the server is list...
very simple with QTcpSocket. Begin as you did... void MainWindow::connectTcp() { QByteArray data; // <-- fill with data _pSocket = new QTcpSocket( this ); // <-- needs to be a member variable: QTcpSocket * _pSocket; connect( _pSocket, SIGNAL(readyRead()), SLOT(readTcpData()) ); _pSocket->connectToHost...
7,923,602
7,923,623
Initializing global variable class
Apologies for such a basic question but I can't figure it out. I know you can initialize a class like this: QFile file("C:\\example"); But how would you initialize it from a global variable? For example: QFile file; //QFile class int main() { file = ?? //need to initialize 'file' with the QFile class }
1. Straightforward answer If the class is assignable/copy constructible you can just write QFile file; //QFile class int main() { file = QFile("C:\\example"); } 2. Use indirection If not, you'll have to resort to other options: QFile* file = 0; int main() { file = new QFile("C:\\example"); // delete...
7,923,749
7,923,868
STL Set of pointers. Copy constructor issue
I am developing a project in C++ under Ubuntu 11.10 using the latest version of NetBeans. I'll only post minimal parts of the code relevant to the problem. Let's say I have the following code for a graph kind of problem: typedef map<Node*, double, DereferenceCompare> Transitions; class Node { int _nodeNumber; ...
I've done this exact same thing before. It's tricky: Network::Network(const Network& b) { //old to new mapping std::unordered_map<Node*, Node*> mapper(b._network.size()); // duplicate all nodes without links for(auto iter = b.begin(); iter != b.end(); ++iter) { Node* new_node = new Node(); ...
7,923,838
7,923,951
delayed initialization?
could somebody please explain why this happens? I have written the following: 1) a WindowManager class which is implemented as a singleton and has an Instance() method, defined like so: static WindowManager * instance_; //... WindowManager * WindowManager::instance_ = 0; WindowManager & WindowManager::Instance() { ...
Here you have quick example which illustrates the problem: #include <iostream> #include <vector> using namespace std; struct T { int id; T(int id) : id(id) { cout << "created " << id << endl; } T(T const& t) : id(t.id) { cout << "copy: " << t.id << endl; } void print(char const* m) ...
7,923,858
7,923,940
How to return more than one token on Bison parser?
My grammar is something like this decl: attributes; {/*create an object here with the attributes $$?*/ } attributes: | att1 attributes {$$ = $1;} | att2 attributes {$$ = $1;} | attn attributes {$$ = $1;}; I want to get all the attributes entered by the user, some of them are optional and the...
You need to return a structure in your $$ variable; assign to its members as you need to. Here's an example from some code I have handy: struct value_list { char *value; struct value_list *next; }; # ... valuelist: TOK_VALUE { struct value_list *new = calloc(1, sizeof(struct value_list)); ...
7,923,883
7,923,908
Converting int to string without using itoa
#include <stdio.h> //#include <<strong class="highlight">string</strong>.h> // Function declarations // typedef __w64 unsigned int size_t size_t strlen(const char *); char *strrev(char *); char *itoa(int, char *, int); int main() { int num = 123; char buf[5]; itoa(num, buf, 10); printf("%s\n", buf);...
It looks like you've somehow gotten HTML markup into your C++ source code: s = <strong class="highlight">string</strong>; while (*s) s++; return s - <strong class="highlight">string</strong>; I would have gone ahead and fixed it, but the error message refers to a < character, so I think that's your actual problem....
7,923,964
7,924,009
how to find a socket's ip address c++/c
I want to know how to get the IP address of a client who connects to a socket on a server using accept. How would I do this? getpeername returns a wrong IP address, and I can't seem to find another way to do it. On the server, after accept returns, I'm doing this: char buf[INET_ADDRSTRLEN]; str...
The 2nd parameter of accept has this information.
7,923,967
7,931,096
Weird Issue with cvStartFindContours?
Whenever I pass in an image to cvStartFindContours, instead of finding the contours, my image turns completely black. I have absolutely no idea why. I know this isn't caused by another part of the code even if I comment everything out, but leave in the function call to cvStartFindContours, my image still turns black. H...
I have been bitten by this as well. From the OpenCV documentation for findContours: image – Source, an 8-bit single-channel image. Non-zero pixels are treated as 1’s. Zero pixels remain 0’s, so the image is treated as binary . You can use compare() , inRange() , threshold() , adaptiveThreshold() , Canny() , and ...
7,924,010
7,924,068
Returning abstract type in base class
In a design of a class hierarchy, I'm using an abstract base class that declares various methods that the derived classes would implement. In a sense, the base class is as close to an interface as you can get in C++. However, there is an specific issue. Consider the code below which declares our interface class: class ...
Interface::method() cannot return an Interface instance without using a pointer or reference. Returning a non-pointer, non-reference Interface instance requires instantiating an instance of Interface itself, which is illegal because Interface is abstract. If you want the base class to return an object instance, you h...
7,924,217
7,924,295
Virtual Destructor needed when using Cloaking pattern?
If I have the following 3 classes to hide the data type and store information, do I need a virtual destructor? I was led to believe no, but now I am not sure. I would rather not include it if possible for preformance reasons. Classes stripped down for example sake. #include <memory> class DarkHideInterface { public...
With auto_ptr, I think you need the virtual destructor, since the delete will happen polymorphically - in other words, internally auto_ptr will ultimately call delete on the stored DarkHideInterface*. If DarkHideInterface doesn't have a virtual destructor and the pointer points to a DarkHideInterfaceImpl instance, then...
7,924,228
7,925,160
wxWidgets socket telnet
I am trying to communicate with a telnet server via socket programming with wxWidgets however, after I connect to the server I don't get any message back, even though I know there is a welcome message from the server, I just get nothing, is there a certain message I have to send to initiate a telnet session with the se...
The following program connects to a telnet server and prints the data it receives. Notice that the data is binary, not text -- you need to study the RFC854 to understand how to parse the telnet protocol. #include <wx/wx.h> #include <wx/socket.h> #include <iostream> #include <iomanip> int main () { wxInitialize(); ...
7,924,317
7,924,345
How to overload stream operators in C++
I need class to overload stream operators << (inserter) and >> (extractor) that insert or extract a private integer variable
One option would be the following: #include <iostream> class C { private: int i; friend std::ostream& operator<<(std::ostream& os, const C& rhs) { os << rhs.i; return os; } friend std::istream& operator>>(std::istream& is, C& rhs) { is >> rhs.i; return is; ...
7,924,630
7,925,461
Multiple fork() Children with pipes
I am trying to make a program in C++ that is creating childs with fork(). It should take childs number from argv and create these childs,every child is creating another one and communicate each other with pipes .... Example ./a.exe 2 **OUTPUT** P1 exists P2 created Write message: Hello P1 sending message (“Hello”) to ...
You have multiple problems in the code you show, and there is code missing as diagnosed in a comment. One problem is that you close both ends of the only pipe in the first child, and then close it a second time (but fortunately you ignore the error). More seriously, any subsequent children only have a closed pipe to w...
7,924,694
7,924,718
Need help do-while loop program? (C++)
I am trying to create a program that will take user inputs(marks) and output the average of these marks to a letter grade. I believe I have succeded in getting the program to calculate the average succesfully, however it will not output the right letter grade? Any suggestions? EDIT: Perhaps it is something in the calcu...
Couple of things to consider: Your grades assignment should consider the average and not marks. If you use marks, then the last entered value which is -1 to exit your do while loop will be used to grade which will always result in F grade. Add endl to all your cout statements after the do-while loop. The output strea...
7,924,762
7,925,921
Boost::this_thread::get_id() without string operation
i'm in a situation where i need to get boost::thread::id into a variable, but this variable is NOT a string, neither a string operation is allowed. is that possible? maybe something like char *tid = (casting something) boost::this_thread::get_id() this is c++ on unix system. the reason why avoiding using string operati...
What about: std::ostringstream oss; oss << boost::thread::get_id(); std::string idAsString = oss.str(); See the documentation on boost::thread::id Update: Since you already use boost, why not use: std::string id = boost::lexical_cast<std::string>(boost::thread::get_id()); Also, as you are doing this only at the begin...
7,924,826
7,924,980
how can I get the fastest iteration possible for some calculus intensive code?
Context I'm using a QLinkedList to store some class I wrote. The fact is I must iterate a lot over this list. By a lot I mean the program I write makes infinite calculus (well, you can still stop it manually) and I need to get through that QLinkedList for each iteration. Problem The problem is not if I'm iterating to m...
If you are profiling in debug mode, a lot of compilers disable inlineing. The begin() and end() times being high may not be "real". The method call times would be much higher than the equivalent inline operations. Something else I noticed in the full code, you're doing a sqrt in the inner loop. They can be fairly expe...
7,925,023
7,925,646
Need simple demo call Delphi DLL in C++
i don't work well with C++ but now i need build a function that call Delphi DLL and pass a string to DLL and get return new string. here is my Delphi DLL code: library testdll; uses System.Classes,Winapi.Windows,System.SysUtils; {$R *.res} function hello(name : PWideChar):PWideChar; var rs:PWideChar; begin rs:=PWi...
You are trying to concat a PWideChar to a String literal and return it as another PWideChar. That will not work as-is. You should not be returning a PWideChar anyway. That leads to memory management nightmares. A better design is to let the caller pass a buffer into the DLL to fill in instead, eg: library testdll; us...
7,925,096
7,968,419
DFS: How to indicate the nodes of the connected components in C++
I am making a problem of ACM competitions to determine the number of connected components that have an undirected graph G and vertices belonging to each component. 've Already done with a DFS algorithm, counting the number of connected components of undirected graph (the hard part of problem), but I can not think of an...
the solution is much easier, you must declare two arrays of size the number of vertices int vertexNodes [vertex] / / / array to store the nodes int vertexComponents [vertex] / / / array to store the number of components Then, when you call to DFS each vertex is stored in the array of vertices, and stored at that comp...
7,925,178
7,925,185
Convert console/empty project to a Win32 project
I originally started a project in Visual C++ 2010, which was an empty/Blank project. How do I convert this to a Win32 project so that there is no console ?
You're looking for the /SUBSYSTEM setting under linker options. Be sure to get both the Debug and Release configurations (or, leave the console enabled for Debug builds and send some useful information there)
7,925,217
7,925,244
Defining and calling a C++ function of a specialized template
I am currently learning C++ in-depth, and I have come across something that has stumped for a couple hours now. Why is it when I make a template and then specialize it, that I can't call or define that function for the specialized version? The compiler complains, and I have scoured Google for a possible hint as to what...
//specialization to type char template <> class C <char> { public: void echo(); }; //template<> <----- don't need to mention template<> here void C <char> :: echo() { cout << "HERE\n"; } P.s. Never say endl when you mean '\n'. What is the C++ iostream endl fiasco?
7,925,479
7,925,538
"IF" argument evaluation order?
if(a && b) { do something; } is there any possibility to evaluate arguments from right to left(b -> a)? if "yes", what influences the evaluation order? (i'm using VS2008)
The evaluation order is specified by the standard and is left-to-right. The left-most expression will always be evaluated first with the && clause. If you want b to be evaluated first: if(b && a) { //do something } If both arguments are methods and you want both of them to be evaluated regardless of their result: bo...
7,926,024
7,926,059
Destructor is called on unwanted object during assignment
myClassVar = MyClass(3); I expected destructor being called on the previously created myClassVar on the left. But it is actually being called on the new object that's created by MyClass(3). My full test code and output follows.. edit How do I fix the problem? Implement an assignment operator? MyClass actually has po...
Here's how the critical line breaks down: myClassVar = MyClass(3); First, MyClass(3) calls constructor and returns the object. Second, myClassVar = copies the object to myClassVar. Then the statement ends. The object (which is an immediate) is dead, and thus the destructor is invoked. EDIT : As for how to get around t...
7,926,119
7,926,757
CtrlList inserting item through postmessage treat notification
So here is my problem, i have a CtrlList, and I want to insert items via PostMessage (asyncron) therefore the message LVM_INSERT_MESSAGE, is going to be processed when it is his turn, but the problem is i need to allocate memory for LVITEM, so that i don't loose it before i insert the item. But after i loose the point...
Post a custom message to some other window, and in its handler add the item then free memory. If the list control is already subclassed, there is no need for other window and the message can be sent directly to the control.
7,926,313
7,926,327
Why does sun C++ compiler change symbol names when compiling with debug infos?
I have this source file: // ConstPointer.cpp const short * const const_short_p_const = 0; const short * const_short_p = 0; and compiled it with and without debug infos (SUN C++ Compiler 5.10): # CC ConstPointer.cpp -c -o ConstPointer.o # CC -g ConstPointer.cpp -c -o ConstPointer-debug.o Here are the symbol names of t...
Maybe this is linked to the fact that a global const variable is implicitely static in C++?
7,926,394
7,926,469
dollar sign in variable name?
I stumbled on some C++ code like this: int $T$S; First I thought that it was some sort of PHP code or something wrongly pasted in there but it compiles and runs nicely (on MSVC 2008). What kind of characters are valid for variables in C++ and are there any other weird characters you can use?
The only legal characters according to the standard are alphanumerics and the underscore. The standard does require that just about anything Unicode considers alphabetic is acceptable (but only as single code-point characters). In practice, implementations offer extensions (i.e. some do accept a $) and restrictions (...
7,926,678
12,161,086
Compile error with a template when building with GCC but not MSVC
On expression: typedef RDOCalcUnary<RDOValue, (&RDOValue::operator-), OperatorType::OT_ARITHM> RDOCalcUMinus; gcc shows the following errors: error: ‘rdoRuntime::RDOValue::operator-’ cannot appear in a constant-expression error: ‘&’ cannot appear in a constant-expression error: template argument 2 is invalid error:...
When you do the typedef don't use brackets: typedef RDOCalcUnary<RDOValue, &RDOValue::operator-, OperatorType::OT_ARITHM> RDOCalcUMinus; It works to me.
7,926,692
7,928,123
decltype of a class member variable, is it forbidden? Why?
I can write int a; decltype(a) b; but my compiler (Microsoft Visual Studio 2010, cl Version 16.00.40219.01) forbid me class A { int a; decltype(a) b;// error C2327: 'A::a' : is not a type name, static, or enumerator }; Also Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 gives a similar...
Yes that is valid. Within unevaluated operands (operands of decltype, sizeof, noexcept, ...) you can name nonstatic data members also outside of member functions. Those compilers you tried just don't support this feature yet.
7,926,725
7,927,562
Can I make floating point errors turn into C++ exceptions with MS tools?
I am used to programming in Delphi. In that system, a hardware floating point exception, e.g. division by zero, overflow, etc. results in a native Delphi exception being raised. The mechanism is that the hardware exception are not masked and those hardware exceptions are converted, by the Delphi RTL, into native Delphi...
How about this example converting SEH into C++ exceptions?
7,926,752
7,947,100
SFML RenderWindow Odd Characters
So I'm trying to get SFML to work with Visual C++ 2010, and it will open the window now, but it looks like this when it does. The window also doesn't respond when you try and move it or close it. Here's my code: //////////////////////////////////////////////////////////// // Headers //////////////////////////////////...
You have to poll events every frame to let the window respond to the operating system. If you don't, you won't move or close it. #include <SFML/Graphics.hpp> int main() { sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML Window"); while (App.IsOpened()) { App.Clear(); sf::Event event; ...
7,926,770
7,926,795
C++ Borland address of the variable
int main(int argc, char* argv[]) { int *pInt; int iParam = 423425; pInt = &iParam; std::cout<<&pInt<<std::endl; system("pause"); return 0; } Why am i getting address like 1250008 and not like 0x00000 ?
It returns you the addresss where pInt is located in virtual memory. It can be any address. The compiler is free to place an pointer at any address in the address space allocated to an process. If you mean to get the address in hex and not decimal, you need to do use I/O Manipulator like this: std::cout << hex << &pIn...
7,926,776
7,927,589
How to join type and mpl::vector into a new vector
I use the following construct to create a mpl vector of types. struct Struct1{ typedef int type; }; struct Struct2{ typedef float type; }; template<typename T> struct TypeReader{ typedef typename T::type type; }; int main() { typedef bm::vector<Struct1,Struct2> MPLVector; typedef bm::transform<MPLV...
I don't think this is possible with mpl::transform, since it would need to generate several elements in the resulting sequence from a single one in the source sequence. However, this can be done with mpl::fold, along with specialization with mpl::is_sequence: // Default case template < typename Seq, typename TWrapper, ...
7,926,829
7,930,400
Optimistic locking strategy with atomics in C++ and ordering
After reading up on c++0x's atomics and in combination with non locking queues I decided to have a go at playing with them. The idea was to write a single producer, multiple consumer queue with optimistic locking. The messages do not need to be consumed. Skipping is perfectly fine as long as that if a consumer reads i...
Perhaps, this is a bug: structures[next_index].data_a = i; structures[next_index].data_b = i; // **** The writer may be interrupted (preempted) here for a long time *** // at the same time the reader reads new data but old id (number of reads doesn't matter) structures[next_index].id.store(i, std::memory_...
7,926,980
7,927,051
How to elegantly handle exception-throwing constructors?
I sometimes wonder how to handle construction of objects which can throw in their constructor. I wonder how you do it. Consider the following snippet. I have a class, named TCPMessage, which represents a message my "server" receives over TCP. If the received message is invalid (i.e. the CRC32 calculated in the TCPMessa...
Your problem isn't exceptions, it's raw pointers and lack of RAII. Sanitizing your code a bit: void TCPConnection::handleRead( const boost::system::error_code& error, char* read_buffer ) { if (!error) { try { TCPMessage message(read_buffer); SeekurJrRC::Core::Driver& driver = boost::asio::use_serv...
7,926,992
7,927,089
shared_ptr chain/branch with a second deleter
I have a situation where I need to know when the user of a shared_ptr is done, that is, when the user has finally released all copies of it. Normally one just uses a deleter here, but there is a small catch in this case. The underlying object is already a shared_ptr! That is, in pseudo-code: shared_ptr<T> a( new T ); ...
I came up with one possible solution. Create a deleter function like this: void delete_func( int id, shared_ptr<T> underlying ); Then to chain the shared_ptr do this: shared_ptr<T> b( a.get(), bind( &delete_func, id, a ) ); This creates a new unattached shared_ptr with a custom deleter (my branch). One of the paramet...
7,927,396
7,927,995
how to set values of a CvPoint
I'm using a CvPoint structure in OpenCV and I need to assign a value to x and y fields of the structure. Here is my code: CvPoint* P1; P2[0].x=32; But the programs always block while trying to set the value. Any idea about how to set these values?
Well first of all P1 is a pointer to an object of type P1. In order to assign something to an object's member via its pointer you need to use the -> operator. If this pointer points to the beginning of an array you use the operator[] to access individual elements. This operator returns a reference for the given index, ...
7,927,764
7,928,010
specializing iterator_traits
I'd like to specialize std::iterator_traits<> for iterators of a container class template that does not have the usual nested typedefs (like value_type, difference_type, etc.) and whose source I shouldn't modify. Basically I'd like to do something like this: template <typename T> struct iterator_traits<typename Contai...
Yes. The compiler cannot deduce T from Container<T>::iterator because it is non-deducible context, which in other words means, given Container<T>::iterator, the value of T cannot uniquely and reliably be deduced (see this for detail explanation). The only solution to this problem is that you've to fully specialize iter...
7,927,808
8,468,747
vtkImageData blank cells or blank points using VTK
Is it possible to assign certain cells / points of the vtkImageData to be blank? The point is that cca. 90 % of my vtk domain is empty. The vtk files are huge just because they contain a lot of nothing.
Have you considered using another data structure besides vtkImageData? For sparse points, you could use vtkPolyData.
7,927,880
7,927,927
const reference public member to private class member - why does it work?
Recently, I found an interesting discussion on how to allow read-only access to private members without obfuscating the design with multiple getters, and one of the suggestions was to do it this way: #include <iostream> class A { public: A() : _ro_val(_val) {} void doSomething(int some_val) { _val = 10*some_va...
Before the constructor is called an appropriate amount of memory is reserved for the object on Freestore(if you use new) or on stack if you create object on local storage. This implies that the memory for _val is already allocated by the time you refer it in Member initializer list, Only that this memory is not properl...
7,927,974
7,935,133
SDL fake fullscreen mode on dual monitor setup under linux
Using SDL 1.3 I want to create fake fullscreen SDL_Window under linux. It is easy if i have only one display. I just got current display mode and created a window. SDL_GetDesktopDisplayMode(0, &mode); SDL_Window *win = SDL_CreateWindow("my window", 0,0,mode.w, mode.h, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL...
src/video/x11/SDL_x11modes.c checks some interesting #defines: SDL_VIDEO_DRIVER_X11_XINERAMA SDL_VIDEO_DRIVER_X11_XRANDR SDL_VIDEO_DRIVER_X11_XVIDMODE You might check include/SDL_config.h to see which path(s) your copy is following. Rebuilding with X11MODES_DEBUG defined may also be productive. EDIT: Tried test/testv...
7,927,994
7,928,031
Is it always safe to replace a built-in array with a std/tr1/boost::array?
boost::array (or the tr1or std version) offer some nice additional features over a built-in array. Up to now, our codebase only contains built-in arrays, for example (made up, but the style matches): WORD m_lastReadFlags[FLAGS_MAX]; ... WORD flagBuffer[FLAGS_MAX]; if (getFlags(flagBuffer)) { memcpy(m_lastReadFlags, f...
Yes, that should be fine, since the array class is precisely a wrapper for an automatic array. It has the same access syntax with square brackets, and if you need to get at the pointer, you know how to do it. You can even use std::copy everywhere and use iterators; chances are that that will be implemented by memcpy an...
7,928,033
7,928,649
Running a file whose handle is opened(C++ winapi)
I included a exe file as a resource in my c++ application and i need to run it, but i need to restrict it's access alot so the user can't copy it. I need to keep it's handle opened so external programs can't access it, and because i used FILE_FLAG_DELETE_ON_CLOSE as a flag, so it will delete if my application gets kill...
Since you can't lock the entire file, lock a very small part with LockFile. You'll need to find a byte range that Windows doesn't use. You might achieve this by adding a dummy resource to the EXE. (This does not require source code).
7,928,096
7,929,387
Is this a gcc optimization bug?
Here's my code: bool func(const MY_STRUCT *const ptr, some_struct *x, int y) { printf("IN: %p\n", ptr); // ok for (int i = 0; i < y; ++i) { if (ptr->foo(x[i].key) == 0) { return false; } } printf("OUT: %p\n", ptr); // ok return true; } void process(void) { ... ... ...
There is the (likely) possibility that you have a stack-smasher in func, which is overwriting ptr on the caller's stack. Make sure any array or structure accesses in func remain in bounds. If it weren't for my sour memories of gcc 3.x, I would say that this is nearly certainly what's actually going on. Even so, this...
7,928,147
7,928,166
C++ for loop: evaluation of condition
I have got a (stupid?) C / C++ question about a loop: for (size_t i = 0; i < std::distance(begin, end); ++i) { a.push_back(i); } begin and end are two iterator. My question is, is std::distance(begin, end) calculated for each element in the loop? Or is it better to use this version: size_t dist = std::distance(begin...
Second version is better. In the first one the condition is evaluated each time (no automatic asumption about the result being invariant).
7,928,308
7,928,983
Displaying another application on top of a directdraw full screen application
I am using a Full Screen application that is using DirectDraw functions for display and it is working fine. Now I want to show another application with its own window but the other application is hidden behind the full screen Direct Draw application when launched. I can access the other application only when I close th...
I looked into this some time ago and found that the way its done is to hook the DirectDraw APIs and insert your own rendering in there. Basically, after the other app is done drawing the scene and is about to present the backbuffer, your code jumps in and does its own thing. I never got it working myself, but that se...
7,928,458
7,928,496
Pointer with a pointer constructor
In C++, how can I achieve the following: // player.h #ifndef PLAYER_H #define PLAYER_H class Player { public: Player(Cake* cake); } #endif // player.cpp #include "cake.h" #include "player.h" Player::Player(Cake* cake) { } // cake.h #ifndef CAKE_H #define CAKE_H class Cake { public: Cake( ); } ...
This looks like a mistaken local initialization. Cake* cake(); Player* player(cake); needs to be rewritten to Cake* cake = new Cake(); Player* player = new Player(cake);
7,928,583
7,928,632
ostream error. Can anybody debug this?
I want the following values to be written into the file using ostream??? int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fputs ("fopen example",pFile); fclose (pFile); } pFile<< "r "<<" " <<"ggjjsss" <<'_'<<"gggjj"<< " " << "HLLO " <<endl; } I am getting the followi...
Since you are dealing with FILE, I would say it's an ofstream error rather than ostream error. :) FILE is a C-style file i/o for which operator << is not overloaded. You should use ofstream object for which the operator << is overloaded in the library. #include<fstream> ofstream File("myfile.txt"); File<< "r "<<" " <<...
7,928,648
7,928,706
Write function not using the seekp value
I'm trying to use C++ to write an entry in a specific place in a file so basicly I have ofstream ofs("file.dat", ios::binary | ios::app); ofs.seekp(220, ios::beg); ofs.write((char *)&i, sizeof(i)); But no matter what I do it always write at the end of the file. I suppose this is related to iso::app because according t...
Yes, it's the ios::app that's causing this behaviour. Replace it with ios::in | ios::out. edit: It wasn't clear from your question, but your comments suggest that you're trying to insert data in the middle of the file, rather than overwrite a portion of the file. If that is indeed the case, you pretty much have to use ...
7,928,871
7,929,138
Good practices regarding template specialization and inheritance
Template specialization does not take into account inheritance hierarchy. For example, if I specialize a template for Base and instantiate it with Derived, the specialization will not be chosen (see code (1) below). This can be a major hindrance, because it sometimes lead to violation of the Liskov substitution princip...
enable_if is more flexible I think you should really prefer the enable_if approach: it enables everything that you could require and more. E.g. there might be cases where a Derived class is Liskov-Subsitutable for a Base, but you [cannot assume/donot want to apply] the same traits/specializations to be valid (e.g. beca...
7,928,935
7,929,025
The Meaning of C++ Quotes in g++ vs. MSVC
There's probably a Google search that'll answer this question but for the life of me, I can't think of one that doesn't get millions of unrelated answers. So, In MSVC text inside quotes "like this" is taken, I think, as a std::string or, maybe, std::string&. In g++/gcc it always seems to be taken as const char*. True...
A string literal always has the type of an array of char, with a size just large enough to contain the characters in the literal with a null terminator. So "Empty key" has the type char[10]. This can be implicitly converted to either char const * or std::string if required. The error is because exception is intended as...
7,929,123
7,929,181
ClockTimer shows the value in second or ms?
I have read this implementation in C++; int ClockTimer::ClockMS() { return clock() * 1000 / CLOCKS_PER_SEC; } double ClockTimer::CLOCK() { return ClockMS() * 0.001; } void ClockTimer::StartTimer() { _time_start = ClockMS(); } void ClockTimer::StopTimer(int verb) { _time_stop = ClockMS(); } float ...
If ClockMS is returning milliseconds, then GetElapsedTime will return the time in seconds. For example, if the elapsed time (the difference between stop and start) was 1000 ms, then the return value would be 1000 ms * .001 second/ms = 1 second.
7,929,177
7,929,269
Why don't I need to include STL headers in gcc 4.6?
I'm using gcc 4.6 in c++0x mode. I've noticed I don't seem to get any compiler errors if I use vectors and other STL containers but don't include their associated header files. Was this by design? What's the preferred practice? I do always use explicitly specify the std namespace... but I always thought that the header...
You should always include all the standard headers that your code needs. Unfortunately, standard headers are allowed to include other standard headers, in which case you may find yourself able to use something without including the correct header. You can't rely on that, and you may find that you have to fix your inclu...
7,929,291
7,929,342
get code line with __LINE__
I tried to print the line number of the current code by using: #include <stdio.h> void err (char *msg) { printf ("%s : %d" , msg , __LINE__); } int main ( int argc , char **argv ) { ERR ("fail.."); return 0; } But i always get the wrong line number , it should be 10 instead of 5 , how can i fix this ? Al...
#define ERR(msg) printf("%s : %d", (msg), __LINE__) Should do the trick. You do not need the function!
7,929,477
7,929,543
Explain the error: ISO C++ forbids declaration of `Personlist' with no type
I have a class which is going to handle an array of objects of another class I've created earlier (which works fine). The problem appears when I try to create an object of my List-class. This is the header of the list-class: #ifndef personlistH #define personlistH #include "Person.h" #include <iomanip> #include <iostre...
You have the wrong capitalisation on your constructor declaration. You have Personlist(); but need PersonList();. Because what you have isn't equal to the class name it is considered a function rather than a constructor, and a function needs a return type.
7,929,740
7,930,004
visual studio windows calling function from other class
I am developing a small visual stdio 2010 c++ project. I have created a small windows based project. The GUI interface have some buttons. Then I have created a xxx.h and xxx.cpp file with some small function. Now I want to call a function fom xxx, when some one press the button. I am getting following error please help...
You need to include the class name in the definition: static void EagleTool::extractCorrectPathofEagle() { // ... } Otherwise you're defining an entirely unrelated function that just happens to have the same name.
7,930,105
7,930,386
Does moving leave the object in a usable state?
Say I have two vectors and I move one unto the other, v1 = std::move(v2); will v2 still be in a usable state after this?
From n3290, 17.6.5.15 Moved-from state of library types [lib.types.movedfrom] Objects of types defined in the C++ standard library may be moved from (12.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecifi...
7,930,157
7,930,183
Bitwise operations between an integer and an array of bits
Suppose I have a c++ array of bits, ones and zeros, and I want to have it bitwise XORed with an integer number, and get the result as an integer. What is the fastest way to do so?
Assuming that you mean a std::bitset and assuming that it would fit into an unsigned long, then unsigned long result = your_bits.to_ulong() ^ your_int;
7,930,168
7,930,204
missing default constructor while using templates
We have a problem using a class template which itself uses function objects in some of its member functions. The error message form the VS2010 compiler is: error C2512: 'SimpleFunctor::SimpleFunctor' : no appropriate default constructor available The downsized code to reproduce this is as follows: // myfunctor.h cl...
Once you define any constructor yourself, including a copy constructor, the compiler doesn't generate a default constructor anymore. (On the other hand, a copy/move constructor is generated by default if you don't provide one, subject to certain rules.)
7,930,369
7,930,438
"dynamical storage" with memcpy
I'm working with a library that uses "memcpy" to simulate dynamical storage data structure with direct access. It's important to note that I'm working on numerical operations that result with small data sets. How can I determine if a linked list would be more appropriate than memcpy in terms of efficiency? From what I'...
If you really care that much about performance, you should measure it, i.e. benchmark your code (this is not evil, it is common practice; what is evil is premature optimization). But be aware that, at least with recent GCC (e.g. GCC 4.6) on GNU/Linux and when optimized by at least -O2, memcpy & memset are semi-magicall...
7,930,403
7,930,664
Use class method comparator on std::sort
Possible Duplicate: problem sorting using member function as comparator Is it possible to use a class method as comparator function in std::sort? for example: std::sort(list.begin(),list.end(),object->comparator) //Doesn't compile If yes, how I do this?
Yes, you can use boost::bind: #include <iostream> #include <algorithm> #include <iterator> #include <boost/bind.hpp> struct S { bool ascending; bool Compare(int lhs, int rhs) { return ascending ? (lhs < rhs) : (rhs < lhs); } }; int main () { int i[] = { 1, 3, 5, 7, 8, 6, 4, 2 }; S s; s.ascending = tr...
7,930,429
7,930,646
Is there any way to call c++ functions from objective-c code without .mm extension?
Is there any way to call c++ functions from objective-c code without .mm extension? For example maybe it is possible to create a C wrapper or anything else that can help in this situation? I know that it is possible assign type "objective-c++ source" for .m files but it is not what I want.
Yes, I do this often. You will need a small amount of .mm glue code, but your intuition of using wrappers is correct. You may be interested in Wrapping C++ - Take 2. There are good reasons to avoid excessive use of .mm files. They compile slower, run slower (particularly under ARC where they incur significant overhead)...
7,930,445
8,943,829
Visual C++ 2008 Linking (specifically embedding manifest) taking too long
Normally I would refrain from asking vague questions but in this case I cannot find enough information to even start looking into fixing the issue. My project is small (to give you an idea: Vector/Matrix math, and some core data structures such as Arrays, Lists and Strings). Some other much bigger projects I tried link...
As Hans Passant mentioned, the problem was caused by the virus scanner. Adding an exception to the folder and file extensions related to the compiler fixes the issue.
7,930,482
7,930,711
boost::lexical_cast from string to char exception
I am new to using boost::lexical_cast and have minimal understanding of its internals. I am trying to do the following cast: string someString = boost::lexical_cast<char>(sourceString); However, boost is complaining that the above code is: [Exception]: bad lexical cast: source type value could not be interpreted as ta...
When I test it (after fixing the invalid conversion from char to string), the lexical cast succeeds as long as sourceString contains a single character. Here are the test results. If your real code doesn't work, then please post more of it; preferably a runnable program that demonstrates the error.
7,930,527
7,930,871
C++ Boost Asio Simple Chat Tutorial
I've been reading Boost Asio's Tutorials (Official website). But I found them a pain in the neck! Is There a simple tutorial on asio?! I mean, A simple client-server chat. NO THREADS!! Thank you!
http://www.boost.org/doc/html/boost_asio/tutorial/tutdaytime1.html Is there anything wrong with the above? That's where I learnt to use Boost::Asio when I used it.
7,930,773
7,930,819
Why is this considered an extended initializer list?
#include <vector> struct foo { int i; int j; int k; }; int main() { std::vector<foo> v(1); v[0] = {0, 0, 0}; return 0; } When compiling this using g++, I get the following warning: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default] As far...
Pre C++11 (and possibly C99) you can only initialize a POD at creation, not at arbitrary runtime points, which is what you're attempting here (assignment from an initializer list). You can make a null_foo though: int main() { const foo null_foo = {0, 0, 0}; std::vector<foo> v(1); v[0] = null_foo; return...
7,930,796
8,687,240
boost::tokenizer vs boost::split
I am trying to parse a c++ string on every '^' character into a vector tokens. I have always used the boost::split method, but I am now writing performance critical code and would like to know which one gives better performance. For example: string message = "A^B^C^D"; vector<string> tokens; boost::split(tokens, messag...
The best choice depends on a few factors. If you're only needing to scan the tokens once, then the boost::tokenizer is a good choice in both runtime and space performance (those vectors of tokens can take up a lot of space, depending on input data.) If you're going to be scanning the tokens often, or need a vector wi...
7,930,887
7,930,945
Find index of iterator in STL container - need template function
I want to have a function with interface like this: template<typename T, typename R> int find_index (const T& list, const R& value); As I know, there is find() in STL that returns iterator. I need to return index of iterator (even for non-indexed containers such as std::list). I tried this code: template<typename T, t...
for (typename T::const_iterator it = list.begin(); it != list.end(); ++it, ++index) should solve your problem. When using dependent types (types depending on template parameters), the compiler does not know that const_iterator is a type until it instantiates the template with a concrete type, it could also just be a s...
7,930,977
8,338,728
How to swap two elements of an mpl::vector?
I'm writing a template function which should swap two elements of a boost::mpl::vector (similarly to std::swap). The difficult part is there is no concept of a variable during compile time. I have written a draft but I wonder if there are better ways to approach this. My current code sketch extracts an integral index f...
Here is a solution using only MPL metafunctions, without explicit recursion. The idea is to start by copying all the values between the beginning of the sequence and the first value to swap, insert the second value, copy the middle, insert the first value, and finally copy the end. A disadvantage of this method is that...
7,931,006
7,931,026
What language coined the term lvalue?
Was C the first programming language to use the term lvalue, or does it go further back? Note that I'm not talking about the general concept of "something on the left-hand side of an assignment statement" (which it has ceased to mean in C++ a long time ago). You can find that in pretty much any imperative programming l...
The notion of lvalues and rvalues was introduced by CPL. http://en.wikipedia.org/wiki/L-value This link doesn't go directly for some reason... https://en.wikipedia.org/wiki/Value_(computer_science)#lrvalue
7,931,022
7,931,230
Object constructor "settings" idiom
I remember reading quite a while back about a constructor idiom for C++ in cases of complex object configurations. It's particularly useful as it helps enable RAII for some nasty concepts which have way too many (often conflicting) options. Here is a simple example. Suppose you were to write a wrapper class for Win32...
Looks like a mix of things. The Settings object is created with the Named Parameter Idiom. Though usually you see it returning a reference to itself so you can chain them. struct Builder { Builder &one(int val) { one_ = val_; return *this; } Builder &two(int val) { two_ = val_; return *this; } int one; int t...
7,931,098
7,931,334
Convert local object to pointer, without copying the data?
I have a class cnList which stores a flexible number of items. This list must later be converted to a cnArray object. The list class already implements a method cnArray cnList::toArray() const. But as you can see, it returns an object, not a reference nor a pointer. But what I have to do after converting the list to...
You can allocate a new cnArray from the heap, constructed from the return value of toArray. If you do it right, Return Value Optimization will allow the compiler to optimize out the redundant copy: cnArray *p = new cnArray(list.toArray()); To see that g++'s RVO will eliminate the copy, see http://ideone.com/loXAT
7,931,164
7,931,308
Graph visualization (boost graph)
I have C++ program using boost graph library. I wonder if there is any way to visualize the graph (nodes and optionally edges) following a certain position values contained in nodes. Please look the examples of the image bellow to understand what I want to visualise: http://img11.hostingpics.net/pics/647608graphViz.png...
You're in luck. Boost graph can serialize to and deserialize from the dot language (which is the language used by GraphViz). There are several examples in the (free) Boost Graph Library book and on the site. See e.g.: http://www.boost.org/doc/libs/release/libs/graph/doc/write-graphviz.html If you take the output of the...
7,931,358
7,931,452
Printing sizeof(T) at compile time
Possible Duplicate: Is it possible to print out the size of a C++ class at compile-time? Can I output the size of an object at compile time? Since the compiler already has this information when it is compiling a source file, can I see it (at compile time) rather than going through the lengthy process of outputting t...
Yes. The possible duplicate prints the size as error message, which means the compilation will not succeed. However, my solution prints the size as warning message, which means, it will print the size, and the compilation will continue. template<int N> struct print_size_as_warning { char operator()() { return N + ...
7,931,378
7,931,546
How do I get the fundamental type of an enum?
With a declaration such as: enum DrawBoldMode : unsigned { DBM_NONE = 0, DBM_ITEM = 1<<0, // bold just the nearest line DBM_SECTION = 1<<1, // bold all lines in the same section DBM_LINETYPE = 1<<2, // bold all lines of the same line type DBM_POINTA...
It should be available as std::underlying_type<DrawBoldMode>::type. However, my compiler (GCC 4.6.1) doesn't seem to implement that. I think it's impossible to implement it with templates, but I could be wrong about that.
7,931,391
7,931,567
#define Glib::string std:wstring
I have Linux code and I want to port it to Windows. The code uses Glib::ustring, but I want to replace all the strings to std::wstring for testing purposes. Is there a way to define all Glib::string to std::wstring without changing it in code? Something similar to typedef or #define?
What makes you think that Glib::ustring is interchangeable/interoperable with std::wstring? Most likely if you made that substitution you'd just get a bunch of compiler errors, or if you're unlucky it would compile and run with different semantics. I think you're going to have to bite the bullet and convert your Linux ...
7,931,392
7,931,685
Assigning and Deleting Pointers
Okay, so here's the context. I've been up for almost a day straight now working on the legendary 8-puzzle problem. I have my heuristics down and my A_star algorithm down. We are required by the project spec to solve it using three different heuristic values. I can solve it for any one of the three individually, but whe...
Upgrading your code-style may force the errors to evaporate. In other words new and delete are error prone and should be avoided when better alternative exists. For management of the cells consider: std::shared_ptr: can be used to void the delete calls std::vector can be used to avoid the new and delete calls Note yo...
7,931,471
7,931,706
Newbie chrome-plugin developer needs help getting started with NPAPI
Although only having done a very little in C++ before I'm trying to compile the following chrome plugin so that I can see how it works and use that as a starting point to develop something similar: http://code.google.com/p/minimizetotray/source/browse/trunk/?r=17#trunk%2FDLL So far I have taken the following steps: dow...
Unless I'm mistaken on the latest SDK the _NPString struct is defined as... typedef char NPUTF8; typedef struct _NPString { const NPUTF8 *UTF8Characters; uint32_t UTF8Length; } NPString; And in your code you are calling UTF8length instead of UTF8Length (uppercase L).
7,931,517
7,931,690
Unix - Protect yourself from runaway memory consumption bringing down the PC?
A very similar question was asked for the .net Windows environment: How do you protect yourself from runaway memory consumption bringing down the PC? This question is posed for the Unix environment using C or C++. As an example, consider the dangerous little block below: #include <vector> int main() { int n; std::v...
As suggested in a comment, either ulimit -v <size> before you start your program, or setrlimit programmatically within it.
7,931,576
7,931,597
Where does g++ (with -fno-implicit-templates) get template definitons from, if I dont explicitly instantiatie them?
The following code works. /* hello.cc */ #include <iostream> #include <vector> void vec_print() { std::vector<int> is(10, 1); for (size_t i = 0; i < is.size(); ++i) std::cout << is[i] << " "; std::cout << std::endl; } /* main.cc */ void vec_print(); int main() { vec_print(); } When i comp...
That option doesn't prevent all template instantiations, just non-inline ones: -fno-implicit-templates Never emit code for non-inline templates which are instantiated implicitly (i.e. by use); only emit code for explicit instantiations. See Template Instantiation, for more information. The compiler inlines all the...
7,931,595
7,931,647
Polymorphic (pure abstract) map key sacrifices type safety?
Some context: (Feel free to skip ahead) I have a module that processes complex data, but only has to know some semantics of it. The data can be considered a packet: The module should only reason about the opaque payload-string, but it will eventually pass the whole thing to a guy who needs more information. However, it...
The answer in full generality should involve double dispatch. The idea is that if you have n different subclasses of PacketInfo, you need n * (n - 1) / 2 implementations of the comparison operator. Indeed, what happens if you compare a CustomInfo with a AwesomePersonalInfo ? This involves knowing the entire hierarchy a...
7,931,687
7,932,212
getopt_long() function with custom argc and argv
I am having trouble using getopt_long() function with custom argc and argv. I receive my arguments in a string instead of the real command line args. Then a new_argc and new_argv was built from this string to be used with getopt_long(). But getopt_long() fails on the first call itself. returns EOF and optarg = NULL. st...
EDIT: "The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector." So, yes. You can use getopt_long to scan the arguments or another argument list agai...
7,931,694
7,931,743
portable c++ alignment?
I want to apply the Pimpl idiom with local storage idiom: mytype.h class mytype { struct Impl; enum{ storage = 20; } char m_storage[ storage ]; Impl* PImpl() { return (Impl*)m_storage; } public: mytype(); ~mytype(); void myMethod(); }; mytype.cpp #include "mytype.h" struct mytype::Impl { int foo; void doMet...
boost::aligned_storage http://www.boost.org/doc/libs/1_43_0/libs/type_traits/doc/html/boost_typetraits/reference/aligned_storage.html should do the trick. Is there a reason you aren't just using the normal pimpl approach though?
7,931,771
7,931,877
what is the command for finding integer in a integer?
for example I have a c++ which takes 2 integers from a file. For example int a = 2052342 and int b = 2. I need to do a search that will search if b is inside a. So in this example, b is inside a, but if b would be for example 7 it wouldn't be. What kind of function, should I use, and could you give me a quick demo of i...
You use a pretty flakey example without much explanation of what "if b is inside a' means. Are you just checking to see if the substring of 'int b' is inside 'int a'? if B were 205, or 234, would that count? Perhaps not the best way, but simple enough, is to convert each integer to a string, and then do a substring che...
7,931,828
7,932,312
cvResize on a video frame
When trying to load an Image and copy a part of it or smooth, everything ok, but when I'm capturing video and try to copy a part of the frame, it becomes reverse and rotated on 180 degrees, does anybody knows why? IplImage *scaled=cvCreateImage(sz,IPL_DEPTH_8U,3); capture = cvCaptureFromFile( "C:\\New York.avi" ); Ip...
You need to match the depth and number of channels of the destination image to make the resize operation work. Right now, you are assuming these values. capture = cvCaptureFromFile("C:\\New York.avi"); IplImage* frame = cvQueryFrame(capture); IplImage* scaled = cvCreateImage(sz, frame->depth, frame->nChannels); cvR...
7,931,860
7,931,946
Windows GDI Context - LoadImage
Using LoadImage() causes segmentation fault. Backtracing the stack I found the following function as called last: AlpcMaxAllowedMessageLength() This is the function I call: status = (HBITMAP) LoadImage(NULL, MAKEINTRESOURCE(STATUS_BMP), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION)); with STATUS_BMP load...
I believe your issue is the fact that you are specifying that you want the image to be loaded from file by the LR_LOADFROMFILE flag, which means that the second parameter needs to be the string name of the standalone image file (this usually means on disk). You might try removing the LR_LOADFROMFILE flag and see if tha...
7,932,074
7,932,122
Unicode across the network to xml
I'm trying to figure out the safest way to retrieve unicode data in a unified method from remote computers and make sure that data stays consistent and readable. Computer A: Chinese user, mixed English Windows 7, some registry values contain Chinese letters like L"您好" Computer B: US English, no unicode values returned ...
UTF8 is more standard (for networking) because it does not have endian issues. For UTF16 you'll need to specify an endian-ness for the transmission. If you're using a unicode format, you do not need a code page. You can do the translation with standard windows calls like WideCharToMultiByte if they're on windows ma...
7,932,153
7,932,614
Windows GDI Context - CreateDIBSection
I am using CreateDIBSection() to create a HBITMAP from a buffer, but sometimes - with no regular occurrence - I get a NULL pointer from it. I can't understand what may cause the function to return a NULL pointer because - as I said before - it is not regular. Sometimes it happens after displaying 10 frames, sometimes a...
If this function is failing at random, I would be inclined to think that the buffer is not correctly formatted or is messed up. Go back in the code that creates the buffer and see if any of the functions fail there. I would suspect that a functions return status is not being correctly checked before the code continues....