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
4,718,213
4,718,257
Dividing a 9x9 2d array into 9 sub-grids (like in sudoku)? (C++)
I'm trying to code a sudoku solver, and the way I attempted to do so was to have a 9x9 grid of pointers that hold the address of "set" objects that posses either the solution or valid possible values. I was able to go through the array with 2 for loops, through each column first and then going to the next row and repe...
You could calculate a block number from row and column like this: int block = (row/3)*3 + (col/3); This numbers the blocks like this: +---+---+---+ | 0 | 1 | 2 | +---+---+---+ | 3 | 4 | 5 | +---+---+---+ | 6 | 7 | 8 | +---+---+---+
4,718,403
4,718,422
Can an exe be smaller than its largest declared buffer?
The reason I'm asking: #include <string.h> using namespace std; int main() { unsigned char file[512000]; unsigned char key[512000]; for(int i = 0; i < 512000; i++) file[i] = key[i]; return 0; } When I compile this with cl.exe on windows I get an executable that is about 31kb in size. The ...
In this case, the buffers will be allocated on the program's stack space at runtime. There's no need for them to be statically built into the exe file.
4,718,468
4,718,484
Understanding C++ Virtual Methods of Instances Allocated on the Stack
For the following code: #include<iostream> using namespace std; class A{ public: virtual int f(){return 1;} }; class B : public A{ public: virtual int f(){return 2;} }; int main(int argc,char*argv[]){ A b=B(); cout<<b.f()<<endl; } I expect the number 2 to be printed. Instead the program prints the number 1. ...
What you've done is called slicing. See What is object slicing? Instead, pointers should be used: A* b = new B();
4,718,568
4,718,675
libstdc++ - compiling failing because of tr1/regex
I have these packages installed on my OpenSUSE 11.3: i | libstdc++45 | Standard shared library for C++ | package i | libstdc++45-devel | Contains files and libraries for development | package But when i'm trying to compile this C++ code: #include <cstdio> #include <tr1/regex> using namespace ...
You need to look at the c++0x library support for gcc as I think Regex is not yet completed http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.200x
4,718,737
4,718,918
Typedef equivalence in function arguments
The question is kind of hard to ask without an example so here it is: #include <vector> struct O { }; struct C { template <typename T> void function1(void (C::*callback)(const O*)); template <typename T> void function2(void (C::*callback)(const typename T::value_type)); void print(const O*); }; int main...
Your problem is that const typename T::value_type is basically typename T::value_type const which resolves to O* const which is obviously not the same as const O* (which would be O const *, when writing the ptr declaration behind the type (more useful to figure out this behaviour)). As for archiving what you want, tha...
4,718,762
4,718,816
C++: Casting my object to a different superclass results in a different pointer address
I'm learning C++, trying to write good, polymorphic code, and running in to some confusion. I have a class Er_1Sine which has two superclasses: "Generator" and "Triggerable". Er_1Sine looks like this: class Er_1Sine : public Generator, public Triggerable{ } If I create a "Generator" pointer (gen), setting it to "er1...
while not entirely correct, you can think of your compound class as 2 seperate objects stacked on top of eachother. The one you declared first being the top (same address) and the one declared second underneath (hence a different address).
4,719,153
6,130,006
RTL layout issue for Property Sheets (MFC)
I am running my English application in Arabic Windows. It contains a property sheet UI (MFC). Everything seems to be fine (Left-To-Right or LTR), except the buttons (OK, Cancel, Apply, and Help) which are Right-To-Left or RTL. But how to make the buttons LTR? I played around with the flag PSH_RTLREADING mentioned on M...
The answer is given by Raymond Chen [1] and another Microsoft employee [2]; you have to remove the WS_EX_LAYOUTRTL style from the buttons in the window created by your CDialog (aka CPropertySheet). You can either do this globally when you create your CMainFrame and inherit it to all child windows, or locally by changin...
4,719,172
4,719,882
BufferedImage + jPanel equivalent way to view an image in C++ using Qt
I have a Java program that used a BufferedImage attached to a jPanel to display some image data that I am reading in from a byte array. I was getting a row of the Image at a time into the byte array, getting the WriteableRaster of the image, and calling the setDataElements() method of the raster, and then setData of th...
I think that QImage is the closest in concept to a BufferedImage. It has a method loadFromData() which can load image data from an array. You can then convert that into a QPixmap by calling QPixmap::fromImage() and display it in a QLabel or whatever.
4,719,382
4,719,624
Is there a way to make pos_type and off_type to be an int64_t using traits?
I am trying to understand what traits are, for example expressions like typedef typename traits_type::off_type off_type in the GNU implementation of fstream. This question came up when I was working with files larger than 2/4 GB. I found that recompiling the STL library, with the appropriate flags usually solves the la...
Traits are a way of "adding" properties to existing types. Let's say we are creating a container type, which contains a typedef to tell its contained data type. The classic way would be: template <class T> struct Cont { typedef T contained_type; } This has the disadvantage that we have to create our class just to cont...
4,719,411
11,308,473
Bitwise and unsigned int operations in PHP
I'm trying to convert my C++ code to PHP and I'm stuck, my source codes uses unsigned integers (32bit) and many bitwise operations like rotations, xor, shifting, I'm trying my best to make it work, I'm cutting integers to 32bit $i = $i & 0xFFFFFFFF; but still I'm having a lot of troubles (my guess it has something to d...
Please take a look of how Java programmers handler unsigned int's http://www.javamex.com/java_equivalents/unsigned.shtml I guess that's the only way of doing it...
4,719,484
4,719,519
Empty vector of type <stuff*>
I have a vector populated with objects: std::vector<Stuff*> stuffVector; and am trying to delete all elements of it using a cleanup function void CleanUp() { for (std::vector<Stuff*>::size_type i = 0 ; i < stuffVector.size() ; i++) { stuffVector.erase(stuffVector.begin()+i); } cout << stuffVect...
This is wrong: for (std::vector<Stuff*>::size_type i = 0 ; i < stuffVector.size() ; i++) { stuffVector.erase(stuffVector.begin()+i); } Imagine the vector has elements 0, 1, 2, 3, 4 in it. After the first erase (i==0), it would be 1, 2, 3, 4. The second erase with i==1 would render it 1, 3, 4, and in the end, it wi...
4,719,599
4,719,644
What's going wrong with this SOCKS proxy request?
I'm currently trying to implement SOCKS 4/5 functionality in my C++ program (i.e. requests to arbitrary protocols and hosts can be redirected through a given SOCKS proxy if desired). I'm developing purely for Windows so using Winsock 2. My problem is slightly less abstract than simply "how does this work" though. I've ...
First of all message_ptr is uint8_t* and *message_ptr = msg_struct.ip; is wrong. You should cast message_ptr to uint_32t* and then assign data, like * ((uint32_t*)message_ptr) = msg_struct.ip; otherwise msg_struct.ip will be converted to uint8_t and then assigned. Same problems with other fields. Check this and let me ...
4,719,796
4,719,820
vector<vector<largeObject>> vs. vector<vector<largeObject>*> in c++
Obviously it will vary depending on the compiler you use, but I'm curious as to the performance issues when doing vector<vector<largeObject>> vs. vector<vector<largeObject>*>, especially in c++. In specific: let's say that you have the outer vector full, and you want to start inserting elements into first inner vector...
Vector is internally a pointer so pointer of vector is sort of overkill. Vector of pointers or smart pointers is usually used when polymorphic contents are needed. In C++03 it may be expensive to insert more vectors or (erase existing ones) of your master vector but C++0x resolves even that issue with its move semantic...
4,719,915
4,719,941
Which language sits between C++ and Java?
I feel the two languages are not enough to rapid build complex but high performance native applications. I want a language which includes: Compile time type check. Memory pointer, but no code pointer. A VM kind design inside, but not need to be run on VM (like Java). Auto memory management. OOP, but not to be pure OO...
D, perhaps. I would also suggest looking at Scala or C# (there is Mono, fwiw), but they miss out on the "native target" bit. For most applications they will likely have the required "high performance" -- but it depends upon specific application and functional requirements. (In any case, I would use either of those lang...
4,719,926
4,719,946
How to call shared_ptr<boost::signal> from a vector in a loop?
I've got a working callback system that uses boost::signal. I'm extending it into a more flexible and efficient callback manager which uses a vector of shared_ptr's to my signals. I've been able to successfully create and add callbacks to the list, but I'm unclear as to how to actually execute the signals. ... // Sig...
That's because dereferencing results in a shared_ptr, not the callback object: // (* i)(data, size); // <-- Dereferencing doesn't work Try dereferencing twice: (**i)(data, size); optionally you can call: (*i)->operator()(data, size);
4,720,120
4,726,475
Using SSL sockets and non-SSL sockets simultaneously in Boost.Asio?
I'm in the process of converting a library to Boost.Asio (which has worked very well so far), but I've hit something of a stumbling block with regards to a design decision. Boost.Asio provides support for SSL, but a boost::asio::ssl::stream<boost::asio::ip::tcp::socket> type must be used for the socket. My library has ...
There's a couple of ways you can do this. In the past, I've done something like if ( sslEnabled ) boost::asio::async_write( secureSocket_ ); } else { boost::asio::async_write( secureSocket_.lowest_layer() ); } Which can get messy pretty quickly with a lot of if/else statements. You could also create an abstrac...
4,720,304
4,720,394
array size and const
Possible Duplicate: initialize array size from another array value in C++ const int a[]={1,2,3,4,5}; int b[a[2]]; int main() { return 0; } The code is giving error in line 2; However, if it is something like below it gives no error after compilation: const int a=3; int b[a]; int main() { return 0; ...
Because in C++ array sizes must be constant expressions, not just constant data. Array data, even though const, is not a constant expression. Second version IS a constant expression.
4,720,344
4,720,465
VS2010 C++ Concurrency Runtime - How to force single threaded mode?
In VS2010, is there a way to force a Concurrency::parallel_for() loop (or parallel_for_each) to run in serial? It would be easier for debugging. If so, how? Thanks
You can achieve a debug friendly build by using a define based on the _DEBUG preprocessor symbol to map the required functions to either serial (mostly found in std) or parallel versions. Of course this means a lot of effort, your way better off learn the useful skill of MT debugging as GMan suggested
4,720,564
4,720,606
Define C++ class in Java way
This maybe not a real question, please close this if it's not appropriate. In C++, you can't mix the header and implementation in a single source file, for example, the class will be defined twice if it's included by a.cc and b.cc: // foo.h #pragma once class Foo { void bar() { ... } }; // a.cc #include "foo.h" c...
Where to give the default values for the optional parameters? The header file. Default arguments are just syntactic sugar which is injected in at the call site. To give them at the definition point should not compile. Move between inline & not inline...? Depends on two things: A. if performance matters, and B. if y...
4,720,591
15,532,716
How do I make Qt Creator's debugger show the contents of C++ vectors in OS X?
I'm writing a program that makes extensive use of vectors and am developing with Qt Creator 2.0.1 on Mac OS X 10.6.6 for the first time. As I am debugging, I can see literals and arrays just fine in the Locals and Watchers window, but as soon as I go to expand a vector, in this case of type Student, I get this tree: T...
QtCreator 2.6 has support for Mac FSF GDB (7.5) support. FSF GDB supports python which allows qtcreator to properly display QVector, QSet, QList, QString, etc. It can be download from macports. Download and Install macports (download it from here http://www.macports.org/install.php) To install FSF GDB 7.5: sudo ...
4,720,652
4,720,782
Tools for Dealing with Stack Corruption in c++
EDIT: Due to a comment that was right about my example I removed it and turn this into a generic question: Some times in my projects I come across stack corruption. No matter how much I fight to write code to avoid it, sometimes it is just unavoidable. But when it happens what are the ways to fight it? I found one macr...
It's far from unclear that you are having stack corruption. But I accept there is some data corruption. A reasonably effective technique is to add guard fields around the suspect field(s): ... long namecheck1; Artist artist; long namecheck2; ... Have the constructor initialize these to most anything, but without ...
4,720,753
4,904,486
How do you extend the JavaScript API with custom methods that have access to native code in Chromium
I am making a custom build of Chromium to get access to speech to text functionality in a custom way and am not sure how to expose access to a new native method through JavaScript. In other versions of WebKit there are methods like addToJavaScriptWindowObject (that is in Qt) but I am not sure how to do the same thing i...
The interprocess API is a narrow interface, so has essentially the minimal number of calls. First off, I would like to point you to the documented way to add new features to the cross-browser API (you can search for "carnitas" on the list to learn more about this): https://sites.google.com/a/chromium.org/dev/developers...
4,720,876
4,720,976
can't get copyfile to work
i am just trying to use copyfile to copy a file, it is as simple as that but it wont work. i have googled it and looked at 20 links and they all say "object.CopyFile ( source, destination[, overwrite] ) " The problem is i can't get it to copy the txt file for me, i have tryed running it as an admin but still does not ...
Replace the line: CopyFile("C:\\Somefolder\\file.txt","C:\\folder\\file.txt",0); with: BOOL b = CopyFile("C:\\Somefolder\\file.txt","C:\\folder\\file.txt",0); if (!b) { cout << "Error: " << GetLastError() << endl; } else { cout << "Okay " << endl; } That should tell you if and why it's failing. The error code...
4,720,936
4,721,069
Program cannot open file, but the file is already there
I am writing a program that will open an image file, but strange thing happened. This is the output from cmd: C:\Users\Karl\Pictures>testcvconsole mypic.jpg argv[0]==testcvconsole argv[1]==mypic.jpg fopen is null strerror(errno)==No such file or directory Are there something I should consider when fopen simply failed ...
Make absolutely sure they are in the same directory. I'm saying this because you're using Visual Studio, for which the "same" directory isn't always so clear, because it depends on how you execute the executable through the IDE. C:\Users\Karl\Pictures>testcvconsole mypic.jpg Are you sure mypic.jpg is located in C:\Use...
4,720,947
4,720,955
What does an extra 0 in front of an int value mean?
Inspiring from a obfuscated piece of code, I have a small question regarding to assign value to an integer: #include <iostream> #include <cstdio> int main() { int i = 0101; std::cout << i << "\n"; } And the output was 65, and I have no idea where 65 came from? Any idea?
It specifies an octal (base-8) number: 0101 == 1 * (8 * 8) + 1 == 65.
4,721,047
4,721,074
This is CRTP usage for static polymorphism but without implementation of a derived function. Compiles both in gcc and visual studio. Why?
#include <iostream> template <class Derived> class Base { public: void method1() { static_cast<Derived*>(this)->method1(); } void method2() { static_cast<Derived*>(this)->method2(); } }; class Derived1: public Base<Derived1> { public: void method1() { std::cout << "Method 1 of Derived1 ex...
I think the reason that this is valid is that if you instantiate this code: void method2() { static_cast<Derived*>(this)->method2(); } where Derived does not have an implementation of method2() will essentially be a glorified self-recursive call. The reason here is that in Derived1, there is indeed a member functio...
4,721,136
4,722,488
Binding temporary to const reference in c'tor initializer list
Section 12.2.5 in C++03 says "A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits" So I tried following program #include<iostream> using namespace std; struct foo { foo() { cout<<"foo c'tor"<<endl; } ~foo() { cout<<"foo d'tor"<<e...
I have tried this with MS VS 2010, and it gives me the output also gives warning during compile: warning C4413: 'bar::ref' : reference member is initialized to a temporary that doesn't persist after the constructor exits foo c'tor bar c'tor foo d'tor Press any key to continue . . . It seems that MS VS 2010 implements ...
4,721,188
4,721,224
C++ Function pointer map with Class Member Variables
I am trying to make a stl map with key as "KEYWORD" and value as "Class member function" But it is not getting compiled. Following is the code. Can anybody please let me know what is wrong. The class member functions are not static. typedef void (RemoteHostManager::*CmdHandlerPtr)(char *); typedef std::map<char *,CmdH...
typedef std::map<char *,CmdHandlerPtr> CommandHandlerSet; typedef std::map<char *,CmdHandlerPtr>::iterator CommandHandlerSetItr; First make it const char*, or even better std::string: typedef std::map<std::string,CmdHandlerPtr> CommandHandlerSet; typedef std::map<std::string,CmdHandlerPtr>::iterator CommandHandlerSetI...
4,721,429
4,721,461
Correct usage of GetComputerName - Do I need to reserve extra space for null character
I was wondering, what is the correct usage of GetComputerName. Should it be TCHAR computerName[1024 + 1]; DWORD size = 1024; GetComputerName(computerName, &size); or TCHAR computerName[1024]; DWORD size = 1024; GetComputerName(computerName, &size);
The size passed in the lpnSize parameter reflects the amount of space available in the buffer, including space for the null terminator. Either of your statements will work, because in the first one you're just allocating one more byte than what you're saying is available. You may want to use MAX_COMPUTERNAME_LENGTH ins...
4,721,648
4,743,448
Unknown source of warning: "can't find linker symbol for virtual table for..."
Since a few days I'm getting a warning msg while debugging. I can't find where it comes from. I was googleing already and found things like it's because I have a static variable. But taking it out doesn't change anything. This is the main method: int main(int argc, char* argv[]) { if (argc != 2) { cout << "...
The message comes from this code in gdb/gnu-v3-abi.c: static struct type * gnuv3_rtti_type (struct value *value, int *full_p, int *top_p, int *using_enc_p) { ... /* The symbol's demangled name should be something like "vtable for CLASS", where CLASS is the name of the run-time type of VALUE. ...
4,721,841
4,721,954
What's the point of temporary bound to a member lifetime statement in C++ Standard?
In this question user Happy Mittal quotes section 12.2.5 of C++03 Standard: A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. How can that be useful anyway? I mean once the constructor exits the temporary gets destroyed, but the reference remains ...
It is not useful to have a reference member bound to a dead object, but it is useful to be clear that "normal" temporary lifetime extension when bound to a reference doesn't apply in this case. It also specifies temporary lifetime extension that applies specially in the ctor initializer: it's extended to the end of the...
4,721,978
4,722,048
Should preprocessor instructions be on the beginning of a line?
A while ago I have discovered an (rather ancient) C Compiler, which scanned macros this way (Pseudo code): if line.startswith("#include") or line.startswith("#define"): ... .. Which kind of raised the question for me where macros should really be placed, at the beginning of a line, like so: void stuff() { #if de...
Some old C compilers required that the #define (for example) be flush with the left margin: #define FOO bar Other C compilers required only that the # be at the left margin, so you could: # define FOO bar Newer C compilers tend to accept the # after any leading whitespace: #define FOO bar If you want compatib...
4,722,236
4,722,291
Converting CfbsBitmap format to JPG
I am doing a mobile application using symbian and Qt 4.7 I have a CFBSBitmap data when i save the CFBSBitmap data, the format is a .mbm file and I wish to convert it to be saved as jpg format. Can anyone help me in this area as I am quite a newbie in Qt and Symbian
QImage provides a save function that takes a parameter format. Just specify the JPG format.
4,722,369
4,722,457
How to build C interpreter using C++ or some other PL
I am looking at creating an interpreter for the C language. I have got hold of this link but I would like to know if there is any better way to do it. Right now, I am looking at implementing it using C++. But if there is any other language which is better at this task then I am willing to change to that for this purpos...
A tool to statically analyze some code is not an interpreter. Anyway, writing such tool is not a trivial thing, it requires a good understanding of how compilers work. Usually such job is split in many tasks: tokenizing the code, parsing it and building an abstract syntax tree first of all These operations are simple t...
4,722,400
14,253,371
Qt compiler warning: overriding commands for target / ignoring old commands for target
When I'm compiling my Qt project for Windows I receive these 2 warnings: Makefile.Debug:109: warning: overriding commands for target `debug/moc_mainwindow.cpp' Makefile.Debug:106: warning: ignoring old commands for target `debug/moc_mainwindow.cpp' I assume they indicate some problem with my project config, what is th...
I got the same error once , maybe source of your problem is different but I will write anyways. In my *.pro file, it was like : SOURCES += main.cpp\ mainwindow.cpp\ serialHelper.cpp \ serialHelper.cpp HEADERS += mainwindow.h\ += serialHelper.h \ serialHelper.h \ typeDefinitions.h cpp and header file was...
4,722,922
4,723,030
Cygwin GCC C++ compiler - Why ./?
If you look at point (6) here: http://www2.warwick.ac.uk/fac/sci/moac/students/peter_cock/cygwin/part3/ Why should we type ./ before the .exe file in order for it to run? Why cannot we type hello.exe immediately? Thanks.
On Windows, the current directory is always in the search path for an executable. The search order is "look in the current dir, if not found, look in the directories listed in the PATH environment variable". From MS site: The operating system always searches in the current directory first, before it searches the d...
4,723,143
4,723,347
Static member functions
After reading sbi and Eli Bendersky's answers in this question I started to wondering what static member functions are for. A class' friend free function shouldn't be able to do anything a static member function can do? If so, why/when should I prefer a static member function to a friend free one?
In general: Require access to private members static member functions have access to private members of the class. If you need that, you can use a static member function. You have to declare it in the header anyway to give it access, so you may as well make it a member rather than a friend. It is commonly done this way...
4,723,326
4,723,362
How to split an unsigned short in two
I am trying to parse binary data that I receive in a string. I am not very familiar with bitwise operation. One of the byte (which I assume is an unsigned short) in my string contains 2 important numbers: the version and a count. Bits 1 to 4 contain the version, bits 5 to 8 contain the count. So I have an unsigned shor...
Shift and perform AND operation. int version = value & 0xF; int count = (value >> 4) & 0xF; or vice versa. Bits as numbers are right to left - 7-6-5-4-3-2-1-0
4,723,618
4,723,638
C++, templates and operator << (using Qt framework)
I'm building little class called Output ... It's meant to be something that will ease my programming in terms of writing output (like support more types for output to stdout (like QString) and so on ...) So far it was good, it worked with QString, but now I wanted to make it to accept any type as argument. But while co...
You need to implement your template in class declaration, not in class definition. C++ compiler simply not compiling your "Output::operator <<" for "T = int" in .cpp file since it don't "know" that you will use it with "int" in different .cpp file. Moving "Output::operator <<" body from .cpp to .h will fix your problem...
4,723,730
4,723,888
How to import and use a unmanaged C++ class from C#?
I have an native C++ dll, some header files and the import library. Is there a way how to instantiate an object within C# that is defined in the dll? The two ways I'm aware of are: to wrap the C++ code into COM to use DLLImport and external C functions
C++/CLI is your friend for this. You'll run into one problem though: it is not possible to store standard C++ objects inside C++/CLI ref or value classes (the ones for .NET). So you'll have to resort to the following class (that you can modify) that I use in production code: #pragma once #include <boost/shared_ptr.hpp>...
4,723,768
4,723,846
How to implement is_stl_vector
I want to specialize a template for STL's vector template arguments. Something like this: // (1) template <typename T> class A { ... }; // (2) template <> class A<std::vector<> > { ... }; I don't care what is the type of the vector element. I would like to use it as follows: A<int> a1; // Will use the general...
You can simply specialize like this: // (2) template <typename T, typename Alloc> struct A<std::vector<T, Alloc> > {...};
4,723,880
4,724,351
How to define a template method for a non-template class?
My compiler is not happy with the way I implement my template methods. It gives tons of error messages like "undefined type T" for these implementations. This is my first method, it is implemented outside of the class block: class VectorConvertor { public: // ... template <class T> static ...
Your code looks OK to me. But there is one thing that got in my mind. Can you please check if the function "sign" is defined before? Simply hover your mouse on it. C runtime library implements some of its functions using the "#define" keyword and because of that you can't define a function with that same name afterward...
4,724,110
4,724,128
C++ problem with virtual functions
I need to write something in C++. I have problem with virtual functions. For example, in header file Human.h I have this: class Human { public: virtual int Age(); Human(); ~Human(); } In Human.cpp file I have this: #include<iostream> #include "Human.h" int Human::Age() { return 0; } I...
You have forgotten to end the class definition with a ; It should read class Human { public: virtual int Age(); Human(); ~Human(); }; This will likely make the error go away. Also, always read the compiler's output: Error 2 error C2628: 'Human' followed by 'int' is illegal (did you forget a ';'?) c:\...
4,724,125
4,724,326
When will adding a move constructor and a move assignment operator really start make a difference?
Considering the high quality of today's compilers regarding return value optimization (both RVO and NRVO), I was wondering at what class complexity it's actually meaningful to start adding move constructors and move assignment operators. For instance, for this really_trivial class, I just assume that move semantics can...
It is already meaningful for purely semantic reasons, even if you keep the optimization-aspects out completely. Just imagine the case where a class does not/cannot implement copying. For example boost::scoped_ptr cannot be copied, but it can be moved!
4,724,185
4,724,214
Any Default Pass By Reference DataTypes in C++?
I understand that unlike C# ( where class is passed by reference and struct is passed by default), both structure and class in C++ are passed by value into a method, unless it is explicitly modified to pass by reference. i.e., // this is a method that passes by reference void PassReferenceOp(MyClass &myclass, MyStruct ...
There are no default pass by reference types. Of course, there are references which are passed by value (most notably, smart pointers), the difference between which you could argue for a while. Not that I see the importance. Adding an & is hardly the epitome of difficulty or time wastage.
4,724,348
4,732,579
C++ regex: convert C# regex to C++ Linux
I can I convert exactly this regex in c#: Regex (@"\s*nameserver\s+(?<address>.*)") Regex (@"\s*search\s+(?<domain>.*)") to std::tr1::regex or to regex.h in C++? (Linux) thanks!
std::tr1::regex in GCC is incompelete. std::regex have bugs. Consider boost::regex.
4,724,586
4,724,682
Return value of a function in Visual studio
HI, I am very much new to using Visual studio. I am trying to debug an application. where i came across a statement like below: double tmp = myPart->bat_qty() * timeFactor / myPart->AUB() * myPart->UCost * myAIM->param->myAnalysisParams->wd_year; in VS when put the cursor at timeFactor myPart->UCost myAIM->param->my...
The quickest way is just to enter myPart->bat_qty() in the Immediate window. This way you don't need to change the code.
4,724,672
4,724,749
C++ Templates and STL vector problem
I need help in the simple matter Im trying to create class #include <iostream> #include <vector> #include <algorithm> using namespace std; template<class T> class merge_sort { protected: vector<T> merge(const vector<T> &a, const vector<T> &b) { vector<T> v; typename vector<T>::iterator A; ...
Use typename vector<T>::const_iterator A = a.begin(); typename vector<T>::const_iterator B = b.begin(); because a and b are const references, the const version of begin is called, and it returns a const_iterator, not an iterator. You cannot assign const_iterators to iterators, like you cannot assign pointers-to-const...
4,724,925
4,724,967
Compiler version, name, and OS detection in C++
I need to detect the OS name, compiler name, and version of the compiler with C++, as I need to change the setup for each case. How can I do that?
For most compilers you can find a list of predefined macros. VS http://msdn.microsoft.com/en-us/library/b0084kay%28v=vs.80%29.aspx gcc http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
4,725,093
4,734,576
Image Skeletonization using Medial Axis Transform
My requirement is something like this: Lets take there is a Bitmap with a big letter 'A'. The Bitmap is two colors (Either Black or White). I need to skeletonize the big 'A'. (see: http://en.wikipedia.org/wiki/Topological_skeleton) Using "Medial Axis Transforming" algorithm. I tried my best in googling but i ended up b...
The following two articles are the ones where the Medial Axis Transform was first proposed, so I think that you can find the algorithm to implement there. Do not expect a C++/C# implementation though. A transformation for extracting new descriptors of shape Shape description using weighted symmetric axis features For...
4,725,115
4,739,224
On Windows is there an interface for Copying Folders?
I want to copy folder A and paste to desktop. I am currently using C++ so preferably an OO interface if available.
it works #include <iostream> int main() { system("xcopy C:\\Users\\Elmi\\Desktop\\AAAAAA\ C:\\Users\\Elmi\\Desktop\\b\ /e /i /h"); return 0; }
4,725,118
4,725,581
Launching an application from a thread with C++
I need to launch a 3rd party program inside a thread, wait to get the results both from stdout/stderr with C++. What methods are available? Are they cross-platform? I mean, can I use them both for cl/gcc?
On Unix: http://linux.die.net/man/3/execl #include <sys/types.h> #include <unistd.h> void run_process (const char* path){ pid_t child_pid; /* Duplicate this process. */ child_pid = fork (); if (child_pid != 0){ /* This is the parent process. */ int ret = waitpid(child_pid, NULL, 0)...
4,725,204
4,725,234
Use of static variables and functions in global scope
Is there a use for flagging a variable as static, when it lies in the global scope of a .cpp file, not in a function? Can you use the static keyword for functions as well? If yes, what is their use?
In this case, keyword static means the function or variable can only be used by code in the same cpp file. The associated symbol will not be exported and won't be usable by other modules. This is good practice to avoid name clashing in big software when you know your global functions or variables are not needed in othe...
4,725,239
4,725,298
Display image in Qt that is coming from an unsigned char**
I am trying to display an image in Qt that is coming in as data from another function. That function stores the rows of an image as an unsigned char** I read somewhere I could somehow store it as a QByteArray and then create a QPixMap then set the QPixMap of a label to display it, but I am not having much luck. This i...
Use QImage. This constructor should help you: http://doc.qt.io/qt-5/qimage.html#QImage-4
4,725,506
4,725,528
Can a C# AnyCPU project include a platform specific dll
Our product is based on a bunch of C++ projects but we are now using C# projects for the front end. We are also now doing a 64 bit version. Our plan is to build all of the C# dlls as AnyCPU. The C# projects will have references to the C++ dlls in a common bin folder. When building x64 the bin folder will contain x64...
As far as I remember, this works. I had only 32bit DLLs, c# compiled and it crashed on startup. So if you put there 64bit DLLs, I think you don't need to recompile C#.
4,725,515
4,725,787
c++ Genetic Algorithm Mutation error
I Have a problem with the mutation function within my genetic Algorithm. I can't quite see what I am doing wrong either. I've looked at this code for a while and I think the logic is correct, it's just not producing the results i want. The problem When i output the Binary array located in the Child Struct, If mutation...
You can't throttle the multation rate this way. You need to separate the mutated bit from the probability of the mutation occuring. for (int z = 0; z < Binscale; z++) { if (rand() % 100 < MutationRate) { // flip bit Child1.binary_code[z] += 1; Child1.b...
4,725,615
4,725,762
Disabling/Removing caret from chat window
I have setup richedit control as a chat window and I've no idea how to remove the blinking caret from the control, does anyone know how to do that in edit/richedit control?
Based on this page, you need to handle the EN_SETFOCUS Windows message and call HideCaret(). The docs there say that calls to HideCaret() are cumulative, so you probably should only call it once (use a static variable to remember whether it has been set), or alternatively call ShowCaret() in response to EN_KILLFOCUS.
4,725,664
4,725,838
How not to compile casting into enum type in C++?
I have this "better" enum class that cannot contain invalid values, and cannot be used until enum value is not set explicitly, as follows: class Symmetry { public: enum Type { GENERAL, SYMMETRIC, HERMITIAN, SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED }; Symmetry(...
Potentially a crummy solution, but it would solve your immediate problem. Rather than having an inner enum type, define a little helper class with a private constructor, and make the outer class a friend. Then the "enum" values can be static const members in your outer class. Something like this: (DISCLAIMER: untest...
4,726,005
4,726,836
CUDA function call-able by either the device or host
I have a re-useable function in some CUDA code that needs to be called from both the device and the host. Is there an appropriate qualifier for this? e.g. what's the correct definition for func1 in this case: int func1 (int a, int b) { return a+b; } __global__ devicecode (float *A) { int i = blockDim.x * block...
From the CUDA Programming Guide: The __device__ and __host__ qualifiers can be used together however, in which case the function is compiled for both the host and the device.
4,726,085
4,726,158
Zipping multiple Files in C++
I need a zip library (or a function) that can zip\unzip a few files, i tried zlib or gzip I can't find a solution to archive more than one file in a single .zip (or .tar, or .gzip). Does anyone have ideas?
Minizip could do that.
4,726,115
4,726,171
Do I need to delete an static std::map?
In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted. Thanks.
If the map contains pointers that were allocated with new (or new[], or malloc), then each pointer needs a corresponding delete (or delete[], or free). The map's destructor wont know what to do with a bald pointer. Consider using a smart pointer that has appropriate move semantics like a boost smart pointer or if you'...
4,726,272
4,727,650
Keyboard hook only working in the calling process
I am doing a VoIP program where I use keyboard hook to check push-to-talk button is pressed down. It works locally from the process which installs the hook, but my aim is to have it check all global input too. Here's what I use: SetWindowsHookEx(WH_KEYBOARD,hook_hookproc,hookInst,0); According to MSDN and other sour...
A global hook like WH_KEYBOARD indeed requires a DLL that can be injected. You typically have to add some IPC code to tell somebody else about it. Beware that you are crossing a process boundary doing this so you need something like a pipe to talk. Have you considered using a low-level keyboard hook (WH_KEYBOARD_LL)....
4,726,384
4,726,682
Passing a derived type from Fortran to C++
I have an old Fortran77 program that calls a C++ function and passes several arrays of values to it (~ 100 individual values total). I'd like to convert the arrays to derived types, to make the code more readable and give names to the individual members of the arrays. Is it possible to pass a derived type from Fortran ...
Look into ISO_C_BINDING, the C-Fortran binding that is part of F2003. You can create a derived type with a BIND(C) attribute, which will be compatible with a C struct of the "companion C processor" (in the case of gfortran, gcc). See chapter 7 in the gfortran manual: http://gcc.gnu.org/onlinedocs/gfortran/Mixed-Languag...
4,726,387
4,726,426
Boost array Initialization in C++
I need to declare a boost::array. I did it as boost::array<char, 116> buf; is there a possibility that I can declare with the size stored as a constant that is initialized from property file. something like boost::array<char, BUFFER_SIZE> buf; Any Help?
No. If you want a dynamically sizable array, use a std::vector Reason for No is that the template parameter cannot be provided at run time (caveat: current standard)
4,726,416
4,726,463
while (i<=sqrt(static_cast<double>(n))
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program: while (i<=sqrt(static_cast<double>(n)) Provided that "i" was initialized to "2", and "n" is the user's input. Why are we comparing to the...
Because if a number has factors other than itself and 1, then at least one of those factors will be less than the number's sqrt.
4,726,428
4,726,498
C++ vector debug implementation
While learning c++ I went through the pains of learning what iterators were, and exactly how to use them. Then, I went through the pain of learning what function calls invalidate iterators, and spotting them quickly. I've been following questions lately and have noticed that a very common theme is people not realizin...
Microsoft's implementation does some debug checking (ref, and ref). It checks specifically for range, so I'm not sure if the erase() scenario fits or not. Edit for jalf's contribution: It appears that GCC (and g++) has similar functionality: stackoverflow.com/questions/2567997/ and gcc.gnu.org/onlinedocs/libstdc++/man...
4,726,570
4,726,710
Deprecation of the static keyword... no more?
In C++ it is possible to use the static keyword within a translation unit to affect the visibility of a symbol (either variable or function declaration). In n3092, this was deprecated: Annex D.2 [depr.static] The use of the static keyword is deprecated when declaring objects in namespace scope (see 3.3.6). In n3225...
In C++ Standard Core Language Defect Reports and Accepted Issues, Revision 94 under 1012. Undeprecating static they note: Although 7.3.1.1 [namespace.unnamed] states that the use of the static keyword for declaring variables in namespace scope is deprecated because the unnamed namespace provides a superior alternative...
4,726,633
4,771,046
Connecting to imap.google with SSL
I`m trying to make an email client but it doesn't work :/ Im trying to connect to google imap with SSL (without SSL i can make it) Code: #include "StdAfx.h" #include "openssl/ssl.h" #include "iostream" #include <cstdio> #include <iostream> #include <string.h> #include <errno.h> #include <sys/types.h> #include <windows....
You need to terminate all commands sent to an imap server with both a carriage return and a line feed. Send a2 SELECT INBOX\r\n and it should work.
4,726,768
4,727,021
Function returning a lambda expression
I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work: auto retFun() -> decltype ([](int x) -> int) { return [](int x) { return x; } ...
You don't need a handcrafted function object, just use std::function, to which lambda functions are convertible: This example returns the integer identity function: std::function<int (int)> retFun() { return [](int x) { return x; }; }
4,726,974
4,727,013
A class containing 3 objects, which have pointers to each other, and an initialisation list to pass references to those objects. ERROR
Agent.h: //#include "Genetics.h" "Sensors.h" "Effectors.h" class C_Agent { public: C_Agent(); C_Genome Genome; C_Sensors Sensors; C_Effectors Effectors; s_agentParameters parameters; }; Agent.cpp: //#include "Agent.h" C_Agent::C_Agent() : parameters(), Sensors(& parameters), Effectors(& para...
If you have a circular dependency, you will need a forward declaration of at least one of the class names somewhere.
4,727,064
4,728,541
Class template for cache aligned memory usage in C++
(to provide the information you need to understand my question is a lot, however it is already compressed) i try to implement a class template to allocate and access data cache aligned. This works very good, however trying to implement support for arrays is a problem. Semantically the code shall provide this mapping in...
When c_line_size is compile time integral constant then of course better pad the cache_aligned with char array depending on sizeof T. You can also check if 2 T-s fit onto one cache line and lower the alignment requirement accordingly. Do not expect miracles from such an optimization. I think 2 times better performanc...
4,727,098
4,727,959
How to find if 3 numbers in a set of size N exactly sum up to M
I want to know how I can implement a better solution than O(N^3). Its similar to the knapsack and subset problems. In my question N<=8000, so i started computing sums of pairs of numbers and stored them in an array. Then I would binary search in the sorted set for each (M-sum[i]) value but the problem arises how will I...
You could benefit from some generic tricks to improve the performance of your algorithm. 1) Don't store what you use only once It is a common error to store more than you really need. Whenever your memory requirement seem to blow up the first question to ask yourself is Do I really need to store that stuff ? Here it tu...
4,727,163
4,727,211
What is wrong with this function call
Behold the code: QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8); ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor)); Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems...
It's because QPixmap::fromImage expects a reference to an image, not a pointer to one. However, change your qi[0] to *qi, that makes the intention cleaner. (or just refrain from using a pointer and start with QImage qi(fullCharArray ...).
4,727,449
4,727,501
Dereferencing pointer C++
I just managed to write a global CBT hook in c++, usable with c#. It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#. I'm not able to dereference a pointer inside a struct pointed to by the lParam. It looks like this: the lParam is a long Pointer to a CBT_CREA...
Your syntax seems to check out, even though it is perhaps a bit unreadable, and the LPCREATESTRUCT cast is obviously unnecessary. You mentioned that you get invalid values for x, perhaps lParam is not really a pointer to a CBT_CREATEWND structure? Are you checking that nCode of the callback function is equal to HCBT_C...
4,727,625
4,727,757
Displaying and sizing a grayscale from a QImage in Qt
I have been able to display an image in a label in Qt using something like the following: transformPixels(0,0,1,imheight,imwidth,1);//sets unsigned char** imageData unsigned char* fullCharArray = new unsigned char[imheight * imwidth]; for (int i = 0 ; i < imheight ; i++) for (int j = 0 ; j < imwidth ; j+...
QImage has a scaled member. So you want to change your setPixmap call to something like: QImage small = qi->scaled(labelWidth, labelHeight, Qt::KeepAspectRatio); ui->viewLabel->setPixmap(QPixmap::fromImage(small, Qt::AutoColor); Note that scaled does not modify the original image qi; it returns a new QImage that is a...
4,727,638
4,769,644
simpest way to get audio/video data from directshow
I compiled the DirectShow sample player (from the Windows SDK's "Samples\multimedia\directshow\players\dshowplayer" folder). Everything works well but it renders directly to the screen and the audio goes directly to directsound. I need to be able to grab the data and write out images to BMPs and write out the audio to...
You can insert a SampleGrabber filter before the renderer, and use the ISampleGrabberCB Interface to access the data. You can still render the video to the screen, and output the audio. If you don't want that, use a NullRenderer instead. See also this example on codeproject.
4,727,709
5,125,754
How can I have a dynamically changing menu in a single QMainWindow, multiple nested QWidgets application on Symbian Qt?
My application consists of one QMainWindow, and a nested QStackWidget containing the rest of the application "forms". I would like to have a soft-key activated menu on each of those sub forms. How is this possible?
Hi sabbour here is the link,which gives you a detailed info, perhaps this could be very useful
4,728,061
4,728,154
Accessing the associated string of a stringstream object
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code : stringstream HTMLss; // string stream of HTML document // ... (load up HTMLss with HTML) const string & HTMLstr = HTMLss.str(); // grab refer...
Take a closer look at stringstream's str method. It returns a copy of the string, not a reference to a string object. So in theory, as long as you, yourself do not change the string your iterators won't be invalidated.
4,728,155
4,728,280
How do you set the cout locale to insert commas as thousands separators?
Given the following code: cout << 1000; I would like the following output: 1,000 This can be done using std::locale, and the cout.imbue() function, but I fear I may be missing a step here. Can you spot it? I'm currently copying the current locale, and adding a thousands separator facet, but the comma never appears ...
The default implementation of do_thousands_sep already returns ','. It looks like you should override do_grouping instead. do_grouping returns an empty string by default, which means no grouping. This means groups of three digits each: string do_grouping() const { return "\03"; }
4,728,160
4,728,210
Thrown off by functor syntax in Effective C++
In Item 15 of Effective C++ 3rd edition an RAII class Font contains as its resource a FontHandle. The item shows how the Font class can offer an implicit conversion function to its FontHandle thus: operator FontHandle() const {return f;} What is the difference between this code and: FontHandle operator()() const ...
The first, operator FontHandle, is a conversion operator. It allows an instance of this class type to be implicitly converted to a FontHandle object, so you could write: Font myFont; FontHandle handle = myFont; More commonly, conversion operators are used to allow you to use an object of one type as if it were anothe...
4,728,219
4,728,271
Is there a way to cap the max size on a STL::map container?
My application can only process up to a certain number of entry in the map structure, how do I specify that limit in my code so that my code does not get overwhelmed (for lack of better term). Is there a way to specify the max limit when defining the variable of type map? Thanks
There's no way to set a limit when instantiating the map, though I supposed you could have your own safe guard when accessing it. For example: if (mymap.find(a) == mymap.end() and mymap.size() >= MAX_MAP_ALLOWED) { throw (runtime_error("map limit exceeded")); } else { mymap[a] = b; } You could possibly create ...
4,728,265
4,728,294
std::string part into integer
I have a std::string: 01001, I want to get each number: std::string foo = "01001"; for (int i=0; i < foo.size(); ++i) { int res = atoi( foo[i] ); // fail int res = atoi( &foo[i] ); // ok, but res = 0 in any case } How to do that?
This is the easiest way I see: std::string foo = "01001"; for (int i=0; i < foo.size(); ++i) { int res = foo[i] - '0'; }
4,728,555
4,729,336
Problem with Parallax Normal Mapping in Opengl , GLSL
I've got a terrible issue with parallax normal mapping and I don't know what can be the problem. (OpenGL 2.0, C++, WinXP) My results: (green are normals, blue are tangents and red are binormals (bitangents) ) Normal mapping is working fine so I assume the tangent vectors are good. The weird thing is, on some walls o...
Wild guess following I'd bet either on a tangent basis (vectors) problem, or on view vector being transformed/considered in the wrong coordinate space. Without more information, it's difficult for me to say more... Some source code, or animation of the problem would be helpful.
4,728,581
4,728,701
HSL Image Adjustements on GPU
I have an application where the user should be able to modify an image with sliders for hue, saturation and lightness. All image processing is done on the GPU using GLSL fragment shaders. My problem is that RGB -> HSL -> RGB conversions are rather expensive on the gpu due to the extensive branching. My question is whet...
For lightness and saturation you can use YUV (actually YCbCr). It's easy to convert from RGB and back. No branching needed. Saturation is controlled by increasing or decreasing both Cr and Cb. Lightness is Y. You get something similar to HSL hue modification by rotating Cb and Cr components (it's practically a 3D vect...
4,728,627
4,728,693
fopen fails invisibly when creating files in system drive (C:\)
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file. My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any error...
This might have to do with the virtual store. Take a look here for some info.
4,728,699
4,728,725
Preferred conversion from char (not char*) to std::string
I have a char, a plain old character, that I would like to turn into an std::string. std::string(char) doesn't exist of course. I could create a char array and copy it in, I could go through string streams, or many other little roundabout routes. Currently, I prefer boost::lexical_cast, but even that seems too verbo...
std::string has a constructor that takes a number and a character. The character will repeat for the given number of times. Thus, you should use: std::string str(1, ch);
4,728,704
4,729,085
For high scalability & performance needs, is it preferable to have C++ or Java implementation at the backend of a PHP application?
For high scalability & performance needs for a social portal, is it advisable to have C++ or Java implementation at the backend of an PHP application ? What are the benefits & trade-offs of the same ?
In raw performance terms, C++ will get you a fair bit further than Java or PHP, and slightly further than C#. By this I mean that if you implement the same algorithm in these different languages you are most likely to see the best performance from C++ (although it will depend exactly on what you're doing and how you do...
4,728,888
4,729,398
how to start c++ mfc application
i work last 3 years on c#. now for some reason i have to make some MFC cpp application. so what u people suggest for me. is it harder then c#? how can i begin? in c# i started just making some puzzle game do i follow the same for it? what is the best way to learn MFC c++? where i can find the resource?
MFC does not really hide the fact that it is built upen the Win32 API. So, the answer to your question really depends on whether you have been exposed to this API and if so how familiar you are with it. When I used to program MFC (those were the days...) it really helped me understand to create an application without a...
4,728,909
4,728,959
Compile current .cpp file VS2008
What is the hot-key or where can I go to compile my current file in VS2008 C++? Thx.
Ctrl-F7 - current file F7 - project
4,729,046
4,729,132
memcpy vs for loop - What's the proper way to copy an array from a pointer?
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums). Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo. I understand the following is invalid: void foo (int[] nums) { myGlobalArray = *nums } What ...
Memcpy will probably be faster, but it's more likely you will make a mistake using it. It may depend on how smart your optimizing compiler is. Your code is incorrect though. It should be: memcpy(myGlobalArray, nums, 10 * sizeof(int) );
4,729,077
4,729,128
C++ Set Iterator in Class
I have a class, which has a member named _Emails. It is of the type set<PEmail*>. When I'm in a member function, and run the following code, it works as expected: for( set<PEmail*>::iterator it=this->_Emails->begin(); it!=this->_Emails->end(); ++it ) { cout << "Email: " << (*it)->getEmail() << endl; } That is...
When you get this->_Emails->begin() right after creating the std::map, the iterator you get is the end iterator (because there are no elements in the std::map, its size is zero and begin() == end()). You cannot dereference or increment an end iterator. It doesn't point to "the beginning of the container;" it points t...
4,729,224
4,729,235
Efficiently convert an unsigned short to a char*
What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25'). I'd like to avoid things such as getting (std::string) strings involved. Performance is important in this case since this conversion will need to happen quickly and often. I was looking into things such as using ...
First off, do it right, then do it fast--only optimize if you can see for certain that a piece of code is not performant. snprintf() into a buffer will do what you want. Is it the fastest possible solution? Not at all. But it is among the simplest, and it will suffice to get your code into a working state. From there, ...
4,729,326
4,729,865
Eclipse C++ content assist, auto activation
I have noticed in Eclipse that content assist kicks in after inserting -> or . or :: I really like this feature, but I was hoping that it would be a little more flexible and auto activate after every 2-3 character typed. An example of this is in Code::Blocks. It allows you to auto activate content assist after a certai...
I havn't seen a setting to auto-activate the content assist, for other than . :: and -> However, Hit CTRL+Space to autocomplete or bring up the content assist , e.g. after you typed 2-3 chars.
4,729,433
4,729,518
Jasper Reports with C++ possible or painful?
I've briefly looked at using Jasper Reports as a reporting engine. However it's all in Java and everything else we have including our server/client architecture, in memory data model, etc is all in C++. Does anyone have any experience with wrapping JasperReports and calling it from C++ or do they have an interface wh...
From how you describe your environment, I'd not go into Jasper Reports, unless some corner somewhere in your company has already used it.
4,729,441
4,729,696
C++ permutations of specified parts in 2D array
I have a simple two 2D arrays (represented as map), filled with 1 and 0. | A | B | C | D | sum -------------------------- A | 0 | 1 | 1 | 1 | 3 B | 1 | 0 | 0 | 0 | 1 C | 1 | 0 | 0 | 1 | 2 D | 1 | 0 | 1 | 0 | 1 it is representation of a graph, so the table is symmetrical to the main diagonal (no members...
There are just 64 variants of bidirectional graphs like you describe with 4 vertices. In other words your graph contains 6 bits of information and is therefore easy to construct from numbers 0 to 63.
4,729,759
4,729,790
Array filling mistake
I can't understand what's wrong is in my program. I have such input data: 01000 11110 01000 I want to save it into: vector< vector<int> > matrix; vector< vector<int> > fillMatrix(vector< vector<int> > matrix, int height, int width, ifstream &read) { // Make 2d-array [matrix] matrix.resize(width); for (int ...
When you initialise the vector, you have width and height the wrong way around. When you later read from the last two columns, the results will be undefined. matrix.resize(width); for (int i=0; i < width; ++i) matrix[i].resize(height); should be matrix.resize(height); for (int i=0; i < height; ++i) matrix[i].r...
4,729,792
4,729,817
Detect null reference in an array
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this: public static <T> boolean containsNull (T[] array, int fromInclusive, int toExclusive) { for (int i = fromInclusive; i < toExclusive; ++i) { if (array[i] == null) return true; } return false; }...
Check whether Arrays.asList(myArray).contains(null). To check part of an array, check whether Arrays.asList(myArray).subList(from, to).contains(null) This will not create unnecessary copies of the array; both asList and subList create ArrayList and RandomAccessSubList objects that wrap the original array without copy...
4,729,820
4,732,798
Propagate constness to data pointed by member variables
It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or reference). For example, the following is perfectly correct: class SomeClass { class SomeClassImpl; SomeClassImpl * impl_; // PImpl idiom pub...
As @Alf P. Steinbach noted, you oversaw the fact that copying your pointer would yield a non-const object pointing to the same underlying object. Pimpl (below) nicely circumvent the issue by performing a deep-copy, unique_ptr circumvents it by being non-copyable. It is much easier, of course, if the pointee is owned b...
4,729,900
4,729,920
C++ loop stack allocation
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about. Lets say you have a for loop: for(int i =...
In the code you have posted, obj does not maintain any state between iterations. for(int i = 0; i < 10; i++) { MyObject obj(file); //obj enters scope, constructor is called with 'file' obj.doSomething(); } //obj loses scope, destructor is called In that example, obj is a different object every time. It may...
4,730,053
4,730,128
How to disable VirtualStore for C++ programs?
I'd like my program to throw an error when it tries to create files in protected locations like the root of the C:\ drive (eg: FILE* FileHandle = fopen("\\file.txt", a)). Instead the file gets created in the Virtual Store under %APPDATA%. How can I disable that Virtual Store? Thanks EDIT: Just to be clear, I'm not ask...
You add an application manifest. Choose asInvoker, highestAvailable, or requireAdministrator. It sounds like you want asInvoker. From http://msdn.microsoft.com/en-us/library/bb756929.aspx: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> ...