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 |
|---|---|---|---|---|
1,320,444 | 1,321,000 | Ropes: what's "large enough to benefit from cache effects"? | From Wikipedia:
The main disadvantages are greater
overall space usage and slower
indexing, both of which become more
severe as the tree structure becomes
larger and deeper. However, many
practical applications of indexing
involve only iteration over the
string, which remains fast as long as
the leaf n... | The limit case for a rope-like string would be built on top of a std::list<char>. That obviously isn't very effective. When iterating, you are likely to have have one cache miss per "leaf"/char. As the number of characters per leaf goes up, the average number of misses goes down, with a discontinuity as soon as your le... |
1,320,460 | 1,321,651 | How do you insert into a sorted linked list? |
Possible Duplicate:
LinkedList “node jump”
I just need to have a linked list in order by name. I can only get it as far as 1st, 3rd, 5th, .. nodes. I just can't think this far. I want to be a C++ programmer but if I can't understand this is their any hope? STL containers std::lists are not an option for me at this p... | Of course there's hope, we all have to start somewhere! :)
First of all, I must point out a dangerous practice in your implementation that my own students used, and it usually resulted in lots of head scratching to find the problem:
while ( headByName->nextByName != NULL )
{
headByName->nextByName = tail_node;
... |
1,320,899 | 1,321,128 | How to find the menu item (if any) which opens a given HMENU when activated? | I'd like to implement a function with the prototype
/* Locates the menu item of the application which caused the given menu 'mnu' to
* show up.
* @return true if the given menu 'mnu' was opened by another menu item, false
* if not.
*/
bool getParentMenuItem( HMENU mnu, HMENU *parentMenu, int *parentMenuIdx );
Give... | You could try setting MENUINFO.dwMenuData to the parent menu handle for all menus you create in your application:
MENUINFO mi;
mi.cbSize = sizeof(MENUINFO);
mi.dwMenuData = (ULONG_PTR)<parent HMENU if this is a sub menu>
mi.fMask = MIM_MENUDATA;
SetMenuInfo(hCreatedMenu, &mi);
Then you only need to query this dwMenuD... |
1,320,912 | 1,320,946 | How to terminate a QThread? | QThread::terminate() documentation states that it is discouraged to terminate a thread by calling this function.
In my program, I need to terminate a thread before it finishes execution. The thread is performing some heavy computation and I want the user to have control to stop calculation.
How can I do that instead of... | Set a flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.
|
1,320,915 | 1,323,895 | Why does Visual Studio 2008 highlight internal as a keyword in C++ code? | I'm porting VC++7 codebase to VC++9. Surprisingly Visual Studio 2008 highlights internal as a keyword in C++ code but looks like it is not really treated as such.
What is this - a bug in VS, an environment setting I haven't found yet, or a sign that I will no longer be allowed to use internal as a regular identifier in... | Just ignore it. The "problem" is just that not all parts of Visual Studio properly distinguish between C++ and C++/CLI. So certain C++/CLI keywords get highlighted even in plain native C++. (array is another one).
This only affects syntax highlighting, not the actual compiler.
So the only reason to avoid these words i... |
1,321,062 | 1,321,169 | Object layout in case of virtual functions and multiple inheritance | I was recently asked in an interview about object layout with virtual functions and multiple inheritance involved.
I explained it in context of how it is implemented without multiple inheritance involved (i.e. how the compiler generated the virtual table, insert a secret pointer to the virtual table in each object and ... | The memory layout and the vtable layout depend on your compiler. Using my gcc for instance, they look like this:
sizeof(int) == 4
sizeof(A) == 8
sizeof(B) == 8
sizeof(C) == 20
Note that sizeof(int) and the space needed for the vtable pointer can also vary from compiler to compiler and platform to platform. The reason ... |
1,321,137 | 1,321,154 | Convert String containing several numbers into integers | I realize that this question may have been asked several times in the past, but I am going to continue regardless.
I have a program that is going to get a string of numbers from keyboard input. The numbers will always be in the form "66 33 9" Essentially, every number is separated with a space, and the user input will ... | I assume you want to read an entire line, and parse that as input. So, first grab the line:
std::string input;
std::getline(std::cin, input);
Now put that in a stringstream:
std::stringstream stream(input);
and parse
while(1) {
int n;
stream >> n;
if(!stream)
break;
std::cout << "Found integer: " <<... |
1,321,407 | 1,321,818 | Programming resources for C++ in Linux | I am new (in a way) to C++ programming. I would like to start doing development in Linux using C and/or C++ as programming languages. I have done some development for a while in Java.
Unfortunately I am not sure where to start. Can you point me to some good resources, and also give me an outline as to what would be th... | It is good that you are using a Linux platform as it will help you to program as per the C and C++ standards.
I would recommend
vi/vim --> text editor
gcc --> C compiler
g++ --> C++ compiler
gdb --> Command line debugger
ddd --> GUI debugger
I use the above mentioned tools. If you ar... |
1,321,467 | 1,321,479 | Which programming technique helps you most to avoid or resolve bugs before they come into production | I don't mean external tools. I think of architectural patterns, language constructs, habits. I am mostly interested in C++
| I find the following rather handy.
1) ASSERTs.
2) A debug logger that can output to the debug spew, console or file.
3) Memory tracking tools.
4) Unit testing.
5) Smart pointers.
Im sure there are tonnes of others but I can't think of them off the top of my head :)
|
1,321,530 | 1,322,128 | How do I create synchronization mechanisms in managed shared memory segments? | I'm trying to have 2 processes communicate via an stl container - so I've decided to use the managed shared memory. I'm trying to implement some synchronisation between them - an interprocess_mutex for a start with a scoped_lock - but I'm not having much luck. How is it supposed to be done?
| I think the best solution is a container handler, and all access (getter/setter) to the container through the handler. So in this handler you could implement the synchronisation easily.
Salu2.
|
1,321,731 | 1,321,776 | How to use Winsock 2? | How do I use Windows Sockets 2 in Visual Studio 2008. I'm using precompiled headers, so far what I have tried is:
Included winsock2.h in my StdAfx.h file
and entered WS2_32.LIB as an additional dependency in Project Settings
I get these errors
------ Build started: Project: TestIVR, Configuration: Debug Win32 ------
... | You need to include winsock2.h before windows.h
|
1,321,735 | 1,321,770 | Learning C++ Example Problems | I am currently going though the process of learning C++ though reading programming books. I understand the concept but find a few days after reading, the concepts start to drift from my memory.
The only thing that keeps them there is working through examples/questions.
Are there any good sites or books that can be reco... | If your books don't give you tasks to chew on, get better books.
Look at those mentioned here.
|
1,322,125 | 1,362,409 | The Boost Statechart Library - how to implement time-consuming transitions | In our project we have UI and logic (which may be represented as a state machine). Transitions between some steps in this step machine are long (IO-bound). We don't want to steal our UI thread for all the time the transition is in progress. Therefore we are looking for a way to perform this transitions in a separate th... | Transitions between states should be triggered by an event, not a long operation.
If you have logic which has any long operations whatsoever, it would be better to put the UI into its own thread, otherwise you'll be unresponsive.
You can always have two independent state machines in their own threads, and then use inte... |
1,322,243 | 1,980,436 | Is switch from MFC to QT or WTL (or other GUI toolkit) recommended for Windows CE development? | There are pretty many questions regarding C++ GUI toolkits for Windows, but they mostly apply to desktop OS versions.
I'm now starting a C++ project for Windows CE 5.0 VGA hand-held device, and thinking about what GUI library to choose. I have some experience using MFC in Windows CE projects, but there are some known w... | We have Qt 4.5 on Windows CE 5.0 project at finishing stage, so I try to tell about advantages / disadvantages of Qt developing comparing to MFC.
Qt Pluses:
Nice OOP design
Natively supported signals/slots abstraction allows develop more rapidly and easily
Qt supports many various features (GUI, filesystem, networking... |
1,322,307 | 1,322,363 | How do I check if a process is running from c++ code? | I'm writing a C++ app that will communicate with another process via boost::interprocess, however I need to check if the other process is actually running first - as the other process is responsible for creating the inter-process shared memory. How do I check if the other process is running ?
folks, I'm specifically re... | The managed_shared_memory ctor will throw an interprocess_exception in case it fails to open the given shared memory (assuming you passed open_only to the ctor). You could use the error code in the exception to test whether the shared memory is available or not.
All means to check whether a process is running (by looki... |
1,322,360 | 1,322,381 | is there such list control in c++ | I am using MFC.
I need a control just like listControl, it has such functions:
MyListControl mylistControl = new MyListControl();
mylistControl.setDataSource(...);
mylistControl.setSQLStatement("select a, b, c, d from table where a > 3");
and system will have a listControl which is populated with the data from databas... | Depending on your platform you will need different code. You will need to use a GUI framework, there is no GUI standard library in the C++ language.
If you want Windows and C++ you can use MFC's CListCtrl, but this is not as powerful as you mentioned and you need to do your own data loading.
The more portable way wou... |
1,322,426 | 1,322,452 | Using stl containers without boost pointers | My company are currently not won over by the Boost libraries and while I've used them and have been getting them pushed through for some work, some projects due to their nature will not be allowed to use Boost. Basically libraries, like Boost, cannot be brought in for work so I am limited to the libraries available by ... | If they're not going to accept boost, I presume other "not developed here" libraries are out of the question.
It seems to me you're left with two options:
Roll your own shared_ptr.
Use raw pointers, and manage the memory yourself.
Neither is ideal, and each comes with it's own pain. Your saving grace might be that y... |
1,322,442 | 1,322,474 | Getting user temporary folder path in Windows | How I can get the user's temp folder path in C++? My program has to run on Windows Vista and XP and they have different temp paths. How I can get it without losing compatibility?
| Is there a reason you can't use the Win32 GetTempPath API?
http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx
This API is available starting with W2K and hence will be available on all of your listed targets.
|
1,322,517 | 1,322,547 | Passing a modifiable parameter to c++ function | Provided, I want to pass a modifiable parameter to a function, what should I choose: to pass it by pointer or to pass it by reference?
bool GetFoo ( Foo& whereToPlaceResult );
bool GetFoo ( Foo* whereToPlaceResult );
I am asking this because I always considered it the best practice to pass parameter by reference (1),... | I prefer a reference instead of a pointer when:
It can't be null
It can't be changed (to point to something else)
It mustn't be deleted (by whoever receives the pointer)
Some people say though that the difference between a reference and a const reference is too subtle for many people, and is invisible in the code whi... |
1,322,578 | 1,322,663 | Win32 API for getting the language(localization info) of the OS? | Can anybody please help me with how to get the language(english,chinese etc) of Windows OS through win32 API(C/C++)??
Thanks,
Sourabh
| You can get the default user locale (which I think is what you're asking) using GetUserDefaultLCID. This will give you an ID which can be used to determine the culture. See here for a table containing IDs and the cultures they represent.
For Vista or Windows 7, Microsoft recommend GetUserDefaultLocaleName.
|
1,323,042 | 1,323,112 | problems with global variables in shared library project (C++) | i have a problem with global variables in a c++ shared library project. my library has to be working as a standard g++ shared library (.so) as well as a dll. i did this by creating files libiup_dll.cpp and libiup_dll.h, where i have something like
#ifdef BUILD_DLL
// code for the dll: wrapper functions around the clas... | The trick is to know that each .cpp file is a compilation unit - ie the things that get compiled. Each one is a total individual and know nothing about each other. Its only at the link stage that these are brought together.
Now, extern says "this variable can be found elsewhere" to the compiled cpp file, the compiler j... |
1,323,824 | 1,323,863 | How to read numbers from an ASCII file (C++) | I need to read in data files which look like this:
* SZA: 10.00
2.648 2.648 2.648 2.648 2.648 2.648 2.648 2.649 2.650 2.650
2.652 2.653 2.652 2.653 2.654 2.654 2.654 2.654 2.654 2.654
2.654 2.654 2.654 2.655 2.656 2.656 2.657 2.657 2.657 2.656
2.656 2.655 2.655 2.653 2.653 2.653 2.6... | Since this is tagged as C++, the most obvious way would be using streams. Off the top of my head, something like this might do:
std::vector<float> readFile(std::istream& is)
{
char chdummy;
is >> std::ws >> chdummy >> std::ws;
if(!is || chdummy != '*') error();
std::string strdummy;
std::getline(is,strdummy... |
1,324,411 | 1,324,555 | Question about precompiled headers in Visual C++ | If I put a header (a.h) into stdafx.h and that header includes another header (b.h) that is not mentioned in stdafx.h, will b.h be visited every time someone includes a.h or is it compiled in as part of a.h? If it is compiled into a.h, what happens when someone includes b.h directly? Will this be precompiled or not?
... | a.h and b.h will be part of precompiled header, and there is no need to include them later. All you need is to include stdafx.h where a.h or b.h are required. If you'll include a.h or b.h explicitly after stdafx.h (all code before stdafx.h include are ignored), then it'll not be compiled second time (just because they ... |
1,324,589 | 1,324,598 | what does this code mean? | this is some code that SDL requires in visual studios 2005 in order for my simple program to work. what is the code doing? the only reason i have it is because my instructor told me to put it in and never explained it.
// what is this code doing?
//---------------------------------------------------------
#ifdef WIN32
... | #pragma is a directive to the compiler. In this case, it asks the compiler to put a "comment" into the final object file, and this comment is then used by the linker to link against the library.
Then it initializes the SDL library.
Then it registers SDL_Quit function to be executed at program exit.
Then pause, otherw... |
1,324,719 | 1,324,765 | using pointers to get values back from a function (c++) | i have a function to calculate several different values:
int ASPfile::get_dimensions(int* Lat, int* Lon,
vector<double>* Latgrid, vector<double>* Longrid) {
_latsize = get_latsize();
_lonsize = get_lonsize();
Lat = &_latsize;
Lon = &_lonsize;
latgrid = read_latgrid();
longrid = read_... | You're writing to memory in get_dimensions, but you're never actually allocating that memory. Instead, you are just passing NULL pointers.
One potential fix is to change your calling code to:
int Latsize, Lonsize;
vector<double> Latgrid;
vector<double> Longrid;
int res = asp->get_dimensions(&Latsize,&Lonsize,&Latgrid,... |
1,324,790 | 1,324,798 | Can an STL map iterator go out of bounds through incrementing? | For associative containers, can the ++ operator send an iterator past the end of a collection?
Example:
map<UINT32, UINT32> new_map;
new_map[0] = 0;
new_map[1] = 1;
map<UINT32, UINT32> new_iter = new_map.begin();
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
At the end of this, ... | If you increment the end iterator, the result is undefined behavior. So, it could remain end, or go off the end, or email your grandmother a link to goatse.
See also: What if I increment an iterator by 2 when it points onto the last element of a vector?
|
1,324,800 | 1,458,470 | Boost Multi-Index Custom Composite Key Comparer | I'm looking to write a custom comparer for a boost ordered_non_unique index with a composite key. I'm not exactly sure how to do this. Boost has a composite_key_comparer, but that won't work for me, because one of the comparers for a member of the key depends on a previous member. This is a simplified example, but I... | I think you have hit the wall.
You may want to refer here: Ordered Indices
As with the STL, you will actually have to provide the comparison criteria yourself, and thus you will have the ability to tailor it to your needs.
As explained on the page I linked (in 'Comparison Predicates' section):
The last part of the spe... |
1,324,919 | 1,324,955 | What language is .NET Framework written in? | The question I always wanted to ask and was afraid to, actually - what language is .NET Framework written in? I mean library itself.
It seems to me that it was C and C++ mostly. (I hope Jon Skeet is reading this one, it`ll be very interesting to hear what he thinks about it)
| The CLI/CLR is written in C/C++ and assembly. Almost all of the .NET framework classes are written in C# > compiled to IL, which runs in the CLR. If you crack open a framework library in Reflector, class, you may see an attribute such as [MethodImpl(MethodImplOptions.InternalCall)] which delegates the call to the CLI... |
1,325,270 | 1,325,332 | How to send a string via PostMessage? | Inside my app, I want to send a message to a dialog from a different thread.
I want to pass an std::exception derived class reference to the dialog.
Something like this:
try {
//do stuff
}
catch (MyException& the_exception) {
PostMessage(MyhWnd, CWM_SOME_ERROR, 0, 0); //send the_exception or the_exception.e... | You can't pass the address of the string in PostMessage, since the string is probably thread-local on the stack. By the time the other thread picks it up, it could have been destroyed.
Instead, you should create a new string or exception object via new and pass its address to the other thread (via the WPARAM or LPARAM... |
1,325,390 | 1,325,399 | C++ and pulseaudio "not declared in this scope" | I'm trying to use pulseaudio to play the contest of a vorbis-stream but are hitting problems. Basicly I'm told that:
‘pa_simple’ was not declared in this scope
‘pa_simple_new’ was not declared in this scope
‘pa_simple_write’ was not declared in this scope
Some code are shown below:
#include <pulse/pulseaudio.h>
pa_s... | Those things are all defined in simple.h, so add a new #include to the top of your file:
#include <pulse/simple.h>
|
1,325,485 | 1,331,777 | How to create a new port and assign it to a printer | We have a virtual printer (provided by a 3rd party) that is getting assigned to an invalid local printer port. The printer is always local (we aren't dealing with a remote print server or anything like that). I'd like to create a new local port (specific for our application), then configure the printer to be assigned... | Wow, looks like that one stumped everyone... After much digging, here's how to do it:
DWORD CreatePort(LPWSTR portName)
{
HANDLE hPrinter;
PRINTER_DEFAULTS PrinterDefaults;
memset(&PrinterDefaults, 0, sizeof(PrinterDefaults));
PrinterDefaults.pDatatype = NULL;
PrinterDefaults.pDevMode = ... |
1,325,494 | 1,325,515 | can't step into c++ program pixel city in netbeans on ubuntu | I'm using NetBeans 6.7 on Ubuntu, and I downloaded a linux port of shamus young's pixel city,
http://github.com/BryanKadzban/pixelcity/tree/master
but I can't step into it (it compiles and builds and runs fine (a little slow but fine)). I can step into a c++ sample project in netbeans which seems to mean that gdb is ... | Did you build it with debugger info enabled? For example, if CCFLAGS is used to specify compiler flags, does it include the -g option? You'll need this before you can use gdb.
|
1,325,553 | 1,325,580 | link with DB2 ODBC drivers on Linux | I need to link our C/C++ code that is using the DB2 ODBC driver on linux, and although ive pulled in sqlcli.h I dont know where to find the objects so i can link.
Ive installed DB2 v9.1 ESE so i wouldve thought i could get everything.
Anybody got any ideas?
| Your application (on the client) would link to a Unix ODBC library -- either iODBC or unixodbc. Both are commonly available on Debian and Ubuntu and other distros.
Next, you install the ODBC driver from the server database. This means you need to get a DB2 ODBC driver onto your system.
With that, your application is c... |
1,325,607 | 1,325,613 | accessing static member variables | Can I access static member variables of a class using dot notation or should I stick in access operator which is double colon?
| If you have an instance variable you may use dot operator to access static members if accessible.
#include <iostream>
using namespace std;
class Test{
public:
static int no;
};
int Test::no;
int main(){
cout << "\n" << Test::no;
Test::no=100;
Test a;
cout << "\n" << a.no;
return 0;
}
|
1,326,118 | 1,326,134 | sum of square of each elements in the vector using for_each | As the function accepted by for_each take only one parameter (the element of the vector), I have to define a static int sum = 0 somewhere so that It can be accessed
after calling the for_each . I think this is awkward. Any better way to do this (still use for_each) ?
#include <algorithm>
#include <vector>
#include <i... | Use std::accumulate
#include <vector>
#include <numeric>
// functor for getting sum of previous result and square of current element
template<typename T>
struct square
{
T operator()(const T& Left, const T& Right) const
{
return (Left + Right*Right);
}
};
void main()
{
std::vector <int> v1;... |
1,326,163 | 1,332,306 | How to tell a column is text or ntext when connecting to database using CDynamicAccessor? | I'm having a C++ application connecting to the MS SQL Server 2005 using CDynamicAccessor.
When my column is text or ntext, the CDynamicAccessor::GetColumnType always return DBTYPE_IUNKNOWN. I can bind the data as ISequentialStream and read the byte stream out. However, how can I tell if the column that I'm reading is t... | The CDynamicAccessor class overwrites the original DBTYPE value of the column with DBTYPE_UNKNOWN. In order to get the original DBTYPE, we need to call the GetColumnInfo function. An example of how to do this is the DynamicConsumer sample application included in the Visual Studio 2008 samples:
// the following case wil... |
1,326,446 | 1,326,456 | Best Tools for helping debug an Interop issues | One of our customers is getting an interop issue, there is nothing in the stack trace that is worth noting, just ComException with an InterOp issue.
I've tried Process Monitor and Dependency Walker, but nothing seems to pop up.
It is C++ Managed running on .net 1.1.
Any helps with any tools would be a life saver!?
| The managed debugging assistants in Visual Studio are designed for precisely this sort of thing and will catch things like GC releasing an COM pointer that's already gone (ie. native side reference counting problems).
Other than that the best tool I've found is a lot of patience and using WinDBG with SOS
|
1,326,468 | 1,326,513 | multiple definition for static member? | Failed to link up following two files, when I remove the "static" keyword, then it is okay. Tested with g++.
Check with readelf for the object file, the static member seems is exported as a global object symbol... I think it should be a local object ...?
static1.cpp
class StaticClass
{
public:
void setMemberA(i... | It seems like you're trying to have local classes in each source file, with the same name. In C++ you can encapsulate local classes in an anonymous namespace:
namespace {
class StaticClass
{
public:
void setMemberA(int m) { a = m; }
int getMemberA() const { return a; }
private:
static int... |
1,326,510 | 1,326,524 | c++ rounding of numbers away from zero | Hi i want to round double numbers like this (away from zero) in C++:
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
What is the efficient way to do this?
| inline double myround(double x)
{
return x < 0 ? floor(x) : ceil(x);
}
As mentioned in the article Huppie cites, this is best expressed as a template that works across all float types
See http://en.cppreference.com/w/cpp/numeric/math/floor and http://en.cppreference.com/w/cpp/numeric/math/floor
or, thanks to Pax, a ... |
1,326,588 | 1,329,640 | WSAEventSelect model | Hey I'm using the WSAEventSelect for event notifications of sockets. So far everything is cool and working like a charm, but there is one problem.
The client is a .NET application and the server is written in Winsock C++. In the .NET application I'm using System.Net.Sockets.Socket class for TCP/IP. When I call the Sock... | I'm guessing you're calling Shutdown() and then Close() immediately afterward. That will give the symptom you're seeing, because this is "slamming the connection shut". Shutdown() does initiate a graceful disconnect (TCP FIN), but immediately following it with Close() aborts that, sending a TCP RST packet to the remo... |
1,326,795 | 1,331,731 | Need to parse a string, having a mask (something like this "%yr-%mh-%dy"), so i get the int values | For example i have to find time in format mentioned in the title(but %-tags order can be different) in a string "The date is 2009-August-25." How can i make the program interprete the tags and what construction is better to use for storing them among with information about how to act with certain pieces of date string?... | First look into boost::date_time library. It has IO system witch may be what you want but I see lack of searching.
To do custom date searching you need boost::xpressive. It contain anything you will need. Lets look into my hastily writed example. First you should parse your custom pattern, witch is easy with Xpressive... |
1,326,811 | 1,326,905 | How does a blur gauss algorithm look like? Are there examples of implementation? | I have a bitmap image context and want to let this appear blurry. So best thing I can think of is a gauss algorithm, but I have no big idea about how this kind of gauss blur algorithms look like? Do you know good tutorials or examples on this? The language does not matter so much, if it's done all by hand without using... | This is actually quite simple. You have a filter pattern (also known as filter kernel) - a (small) rectangular array with coefficients - and just calculate the convolution of the image and the pattern.
for y = 1 to ImageHeight
for x = 1 to ImageWidth
newValue = 0
for j = 1 to PatternHeight
for i = 1 to ... |
1,326,824 | 1,327,147 | How can I find all permutations of a string without using recursion? | Can someone help me with this: This is a program to find all the permutations of a string of any length. Need a non-recursive form of the same. ( a C language implementation is preferred)
using namespace std;
string swtch(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
... | A stack based non-recursive equivalent of your code:
#include <iostream>
#include <string>
struct State
{
State (std::string topermute_, int place_, int nextchar_, State* next_ = 0)
: topermute (topermute_)
, place (place_)
, nextchar (nextchar_)
, next (next_)
{
}
std:... |
1,326,845 | 1,356,258 | Dropdown height bug in CComboBox (common controls 6.0)? |
I've made a simple MFC application (Visual Studio 2008, dialog based) and added a CComboBox using the resource editor. I used the resource editor to specify the dropdown height. Then I added some code to add 100 texts to the combobox. If I run this simple application the dropdown height is ignored. If I disable the Mi... | The only solution I've found (thx to someone on the Microsoft MFC newsgroup) is to use the CBS_NOINTEGRALHEIGHT flag that states that the combobox must look to the exact size specified by the user rather then adjusting it automatically (the reason this is a patch is that the flag is normally intended to disable the fea... |
1,327,157 | 1,327,169 | What's the C++ version of Guid.NewGuid()? | I need to create a GUID in an unmanaged windows C++ project. I'm used to C#, where I'd use Guid.NewGuid(). What's the (unmanaged windows) C++ version?
| I think CoCreateGuid is what you're after. Example:
GUID gidReference;
HRESULT hCreateGuid = CoCreateGuid( &gidReference );
|
1,327,231 | 1,581,189 | Is it possible to run C++ binded with SDL+OpenGL code on a web browser? | My client wants her website to have an application that renders 3D (light 3D stuff, we are drawing only flat squares in 3D world) but web programming is not my thing. So I am looking for something that can run a C++ program from a web browser. But I think, if this is the case, then the client side must download the pro... | No, NativeClient is not what you want. It won't let you run SDL+OpenGL -- it may be C++ code, but it's run inside a sandbox.
Running SDL in a browser is difficult in general. OpenGL somewhat less so, but it's no cakewalk either. Any such native code solution is difficult if you want it to work across browsers and pl... |
1,327,485 | 1,328,028 | Proxy Authentication in POCO Net C++ library | I have been playing with the Poco Net library for some time, it is quite nice. Very convenient and easy to understand.
I was able to set a proxy address, and it is saying 407 Proxy authorization required, properly. I figured that
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
req.setCredentials(s... | You probably need to add the Proxy Authorization field to the HTTP headers. Poco's HTTPRequest class doesn't have a dedicated method for this. However, since it inherits the NameValueCollection class publicly you can set it like this:
req.set("Proxy-Authorization" , "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Where QWxhZGR... |
1,327,806 | 1,328,583 | Do all C++ compilers allow using a static const int class member variable as an array bound? | In VC++ when I need to specify an array bound for a class member variable I do it this way:
class Class {
private:
static const int numberOfColors = 16;
COLORREF colors[numberOfColors];
};
(please don't tell me about using std::vector here)
This way I have a constant that can be used as an array bound an... | Yes, it's 100% legal and should be portable. The C++ standard says this in 5.19 - Constant expressions" (emphasis mine):
In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case-expressions (6.4.2), as bit-field lengths (9.6), as enumera... |
1,327,943 | 1,328,006 | When to use pointers, and when not to use them | I'm currently doing my first real project in C++ and so, fairly new to pointers. I know what they are and have read some basic usage rules. Probably not enough since I still do not really understand when to use them, and when not.
The problem is that most places just mention that most people either overuse them or unde... | For the do's and dont's of C++:
Effective C++ and More Effective C++ by Scott Meyers.
For pointers (and references):
use pass by value if the type fits into 4 Bytes and don't want to have it changed after the return of the call.
use pass by reference to const if the type is larger and you don't want to have it changed... |
1,328,062 | 1,328,101 | listening socket dies unexpectedly | I'm having a problem where a TCP socket is listening on a port, and has been working perfectly for a very long time - it's handled multiple connections, and seems to work flawlessly. However, occasionally when calling accept() to create a new connection the accept() call fails, and I get the following error string from... | Some possibilities:
Some other part of your code overwrote the handle value. Check to see if it has changed (keep a copy somewhere else and compare, print it out, breakpoint on write in the debugger, whatever).
Something closed the handle.
Interactions with a buggy Winsock LSP.
|
1,328,156 | 1,328,273 | Small example on getting Cairo graphics to work with MFC? | I have some legacy MFC apps, and I'd like to use the Cairo drawing engine to add some charts and graphs.
I'm searching for a small example of how to get that to work. Basically, once I've created a PNG or GIF file, how do I get that show up in an MFC CView window?
My google-fu is not finding any good clues.
| From my demo samples,
// cairo_surface_t *surface;
// cairo_t *cr;
// surface = call_win32_surface_create_with_dib_T(CAIRO_FORMAT_ARGB32, 240, 80);
// cr = call_create_T (surface);
// call_surface_write_to_png_T (surface, "hello.png");
HDC src = call_win32_surface_get_dc_T(surface); // <--------
BitBlt(dest, 0, 0, ... |
1,328,223 | 1,328,246 | When a function has a specific-size array parameter, why is it replaced with a pointer? | Given the following program,
#include <iostream>
using namespace std;
void foo( char a[100] )
{
cout << "foo() " << sizeof( a ) << endl;
}
int main()
{
char bar[100] = { 0 };
cout << "main() " << sizeof( bar ) << endl;
foo( bar );
return 0;
}
outputs
main() 100
foo() 4
Why is the array passed ... | Yes it's inherited from C. The function:
void foo ( char a[100] );
Will have the parameter adjusted to be a pointer, and so becomes:
void foo ( char * a );
If you want that the array type is preserved, you should pass in a reference to the array:
void foo ( char (&a)[100] );
C++ '03 8.3.5/3:
...The type of a funct... |
1,328,238 | 1,328,635 | How to hash and compare a pointer-to-member-function? | How can i hash (std::tr1::hash or boost::hash) a c++ pointer-to-member-function?
Example:
I have several bool (Class::*functionPointer)() (not static) that point to several diferent methods of the class Class and i need to hash those pointer-to-member-function.
How can i do that?
Also how can i compare (std::less) tho... | All C++ objects, including pointers to member functions, are represented in memory as an array of chars. So you could try:
bool (Class::*fn_ptr)() = &Class::whatever;
const char *ptrptr = static_cast<const char*>(static_cast<const void*>(&fn_ptr));
Now treat ptrptr as pointing to an array of (sizeof(bool (Class::*)())... |
1,328,410 | 1,329,545 | Include problems when using CMake with Gnu on Qt project | I am starting a multiplatform (Win Xp, Linux) qt project. I want to use an out of source build so my directory structure is as followed:
project/
CMakeLists.txt (global CMake file, includes other CMakeLists)
build/ (my build directory)
libA/
CMakeLists.txt
mystuff/
subprojectA/
CMakeLi... | I have a similar problem, with includes for out of source builds on unix (although I am not using QT), and in each effected projected I added:
include_directories( . )
Not the most elegant but I worked for me.
|
1,328,434 | 1,328,570 | Vectored exception handler and Microsoft C runtime error handling | I've recently implemented some vectored exception handling to catch errors in our software. This is especially useful as we've just converted from vc6 to vs2005. We're encountering a few problems with the use of the STL library (generally people doing things they shouldn't). I'm trying to catch these errors with my vec... | http://msdn.microsoft.com/en-us/library/aa985973%28VS.80%29.aspx
#define _SECURE_SCL 1
#define _SECURE_SCL_THROWS 1
The above allows me to throw exceptions.
|
1,328,492 | 1,328,659 | QTableView - not allow user to edit cell | I created a QTableView with a QSqlTableModel.
By standard, double-clicking on the cells will mark them and the user can edit them.
I want, that the user isn't allowed to do that. He is allowed to mark the whole row by clicking on a single cell, but not to edit the cell.
How can I do that?
| Depending on whether you are coding everything or doing things in the designer, set
editTriggers to QAbstractItemView::NoEditTriggers
selectionBehavior to QAbstractItemView::SelectRows
optionally set selectionMode to QAbstractItemView::SingleSelection if you want the user to select exactly one row
on the tableview o... |
1,328,496 | 1,328,513 | Is there a way to typedef this? | Simplified version of the code:
Foo.h:
class Foo {
private:
class Bar {
// ...
};
typedef std::map<int, Bar> mapType;
mapType _map;
public:
void method(mapType::iterator it);
};
Foo.cpp:
void Foo::method(mapType::iterator it) {
// ...
notMethod(it);
}... | Use
void notMethod(Foo::mapType::iterator it) {
// ...
}
and put the typedef in the public section of Foo's class declaration.
Edit:
If you want to avoid this, you can
make notMethod a friend (as suggested by DanDan),
use sbi's template solution, or
make notMethod a private static member function of Foo (which ge... |
1,328,568 | 1,328,742 | custom stream manipulator for class | I am trying to write a simple audit class that takes input via operator << and writes the audit after receiving a custom manipulator like this:
class CAudit
{
public:
//needs to be templated
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
//attempted manipulator... | To make it work you have to add overload of operator << for functions,
than call the function from it:
class CAudit
{
//...other details here as in original question
CAudit& operator << (CAudit & (*func)(CAudit &))
{
return func(*this);
}
};
CAudit audit;
audit << "some text" << CAudit::write;
|
1,329,147 | 1,332,745 | How to extend listControl class in C++ and add new functions? | Hi I need to extend the CListControl class in C++/MFC, which will add several new features in the list control,
Any one have good sample code ?
Or could you please tell me how can i start it ?
Thanks in advance!
Or just write the new features and listControl into a ActiveX or COM ??
Which is better ?
| TO add functionality such as you suggest in your comments above I wouldn't even make a derivation of CListCtrl. It would make more sense, IMO, to create a CListCtrlManager class that handles things such as you suggest and then handles populating an associated CListCtrl.
Thing is if you wish to derive from a CListCtrl ... |
1,329,163 | 1,329,178 | How to write an unsigned short int literal? | 42 as unsigned int is well defined as "42U".
unsigned int foo = 42U; // yeah!
How can I write "23" so that it is clear it is an unsigned short int?
unsigned short bar = 23; // booh! not clear!
EDIT so that the meaning of the question is more clear:
template <class T>
void doSomething(T) {
std::cout << "unknown t... | You can't. Numeric literals cannot have short or unsigned short type.
Of course in order to assign to bar, the value of the literal is implicitly converted to unsigned short. In your first sample code, you could make that conversion explicit with a cast, but I think it's pretty obvious already what conversion will take... |
1,329,181 | 1,329,319 | The behavior of overlapped vector::insert | Where does the C++ standard declare that the pair of iterators passed to std::vector::insert must not overlap the original sequence?
Edit: To elaborate, I'm pretty sure that the standard does not require the standard library to handle situations like this:
std::vector<int> v(10);
std::vector<int>::iterator first = v.be... | 23.1.1/4 Sequence requirements has:
expression: a.insert(p,i,j)
return type: void
precondition: i,j are not iterators into a. inserts copies of elements in[i,j) before p.
So i and j cannot be iterators into your vector.
It makes sense, as during the insert operation, the vector may need to resize itself, and so the exi... |
1,329,191 | 1,329,232 | Is it legal C++ to use a typedef in a method declaration but the canonical type in the method definition? | The GNU C++ (g++ -pedantic -Wall) accepts this:
typedef int MyInt;
class Test
{
public:
MyInt foo();
void bar(MyInt baz);
};
int Test::foo()
{
return 10;
}
void Test::bar(int baz)
{
}
int main(void)
{
Test t;
t.bar(t.foo());
return 0;
}
Is it legal C++? Are other compilers likely to accept... | Yes it is legal:
7.1.3 The typedef specifier
A name declared with the typedef
specifier becomes a typedef-name.
Within the scope of its declaration, a
typedef-name is syntactically
equivalent to a keyword and names the
type associated with the identifier in
the way described in clause 8. A
typedef-name is ... |
1,329,223 | 1,329,257 | Circular reference in C++ without pointers | Is there a way to define circular references without using pointers?
I need to have somthing like this:
struct A;
struct B {
A a;
};
struct A {
B b;
};
Thanks!
| You can use references instead
struct A;
struct B {
A& a;
};
struct A {
B b;
};
But no it's not possible to create a circular reference without some level of indirection. What your sample is doing is not even creating a circular reference, it's attempting to create a recursive definition. The result would be a ... |
1,329,415 | 1,460,123 | how to pass a stl vector to a function which takes a const [] (c++) | i have a 3d stl vector,
vector<vector<vector<double> > > mdata;
i also have a function
myfun(const double ya[]);
to be more precise, it's a function from the GNU Scientific Library,
gsl_spline_init(gsl_spline * spline, const double xa[], const double ya[], size_t size);
but this is not related to my problem.
so now ... | So, the following seems to work for me:
#include <vector>
void fun(const double data[])
{
}
int main()
{
std::vector<std::vector<std::vector<double> > > data3d;
....
fun(&(data3d[0][0].front()));
}
|
1,329,994 | 1,330,056 | MATLAB functions in C++ | Does anyone know a resource where we can obtain FREE C++ libraries for MATLAB functions? For example, linear algebra problems can be solved using LAPACK and BLAS.
Also, MATLAB in a .NET project is out of the question - I'm talking about direct C++ implementations of popular MATLAB functions (I don't know which function... | I've never heard of a comprehensive port of matlab functionality to C++. That being said, almost everything matlab does exists within a C/C++ library somewhere, some off the top of my head:
LAPACK, BLAS, you already mentioned these, and there are a few good implementations, the most notable (free) one being ATLAS.
FFT... |
1,330,074 | 1,330,096 | How does spy++ find out what is the window at a certain point on the screen? | I am curious how spy++ Finder Tool finds out the window handle for the window over which the mouse is.
Is there any WIN32 function for getting the handle of the topmost window that occupies a certain pixel on the display?
| There is a WindowFromPoint() function.
|
1,330,316 | 1,330,333 | what's the correct way of writing this code? | typedef boost::shared_ptr<config_value_c> config_value_ptr;
typedef std::vector<config_value_ptr> config_value_vec;
config_value_vec config;
typeof (config.iterator ()) it = config.iterator ();
I want to extract an iterator to an array of boost pointers to class config_value_c. I know I can specify the iterator as ... | I think you want:
config_value_vec::iterator it = config.begin();
The next edition of the C++ standard (C++0x) will allow you to do:
auto it = config.begin();
|
1,330,550 | 1,330,559 | C++ Compare char array with string | I'm trying to compare a character array against a string like so:
const char *var1 = " ";
var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strl... | Use strcmp() to compare the contents of strings:
if (strcmp(var1, "dev") == 0) {
}
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather th... |
1,331,292 | 1,331,377 | C++ rely on implicit conversion to bool in conditions? | I found the following rule in a coding standards sheet :
Do not rely on implicit conversion to bool in conditions.
if (ptr) // wrong
if (ptr != NULL) // ok
How reasonable/usefull is this rule?
How much overload on the compiled code?
| In the strictest sense, you can rely on implicit conversions to bool. Backwards compatibility with C demands it.
Thus it becomes a question of code readability. Often the purpose of code standards is to enforce a sameness to the code style, whether you agree with the style or not. If you're looking at someone else's st... |
1,331,318 | 1,331,325 | How an 'if (A && B)' statement is evaluated? | if( (A) && (B) )
{
//do something
}
else
//do something else
The question is, would the statement immediately break to else if A was FALSE. Would B even get evaluated?
I ask this in the case that B checking the validity of an array index say array[0] when the array is actually empty and has zero elements. Ther... | In C and C++, the && and || operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to && is false, or the first to || is true, the rest will not be evaluated.
The code you posted is safe, though I question why you'd include an empty else block.
|
1,331,696 | 1,331,708 | calling class name in the header file | I just stumbled a c++ code with a calling of a class name in the upper part of the header file for example
class CFoo;
class CBar
{
....
};
My question is, what is class CFoo for?
Thanks alot!
| This is called a forward declaration. It means that there IS a class named CFoo, that will be defined later in the file (or another include). This is typically used for pointer members in classes, such as:
class CFoo;
class CBar {
public:
CFoo* object;
};
It is a hint to the C++ compiler telling it not t... |
1,331,821 | 1,331,865 | Fixed-width Floating-Point Numbers in C/C++ | int is usually 32 bits, but in the standard, int is not guaranteed to have a constant width. So if we want a 32 bit int we include stdint.h and use int32_t.
Is there an equivalent for this for floats? I realize it's a bit more complicated with floats since they aren't stored in a homogeneous fashion, i.e. sign, expon... | According to the current C99 draft standard, annex F, that should be double. Of course, this is assuming your compilers meet that part of the standard.
For C++, I've checked the 0x draft and a draft for the 1998 version of the standard, but neither seem to specify anything about representation like that part of the C9... |
1,331,876 | 1,405,860 | Debugging shell extension in Windows 7 | I'm trying to debug shell extension (IContextMenu) in Windows 7 with Visual C++ 2008. I have set DesktopProcess=1 in the registry and set host app to explorer.exe. But when I start the debugger, it launches explorer.exe and then detaches from the process. DllMain of the shell extension isn't called.
The same code with ... | Try launching explorer and THEN attaching the debugger to it.
|
1,331,954 | 1,331,972 | Is it possible to kill a C++ application on Windows XP without unwinding the call stack? | My understanding is that when you kill a C++ application through Task Manager in Windows XP, the application is still "cleanly" destructed - i.e. the call stack will unwind and all the relevant object destructors will be invoked. Not sure if my understanding is wrong here.
Is it possible to kill such an application im... | I believe task manager tries a "nice" shutdown by sending a WM_CLOSE message, then if the application doesn't respond it's killed.
This call should kill the process immediately with no warning:
TerminateProcess
e.g.:
TerminateProcess(GetCurrentProcess(), 1);
Update:
You may find this article interesting:
Quitting time... |
1,332,015 | 1,332,080 | using class specific set_new_handler | For class specific new_handler implementation, i came across the following example in book "effective c++". This looks problem in multithreaded environment, My Question is how to achieve class specific new_handler in multithreaded environment?
void * X::operator new(size_t size)
{
new_handler globalHandler = ... | You're right. This is probably not thread safe. You might want to consider an alternative approach like using the nothrow version of new instead:
void* X::operator new(std::size_t sz) {
void *p;
while ((p = ::operator new(sz, std::nothrow) == NULL) {
X::new_handler();
}
return p;
}
This will cause your cla... |
1,332,031 | 1,332,490 | Linux Network Interface Usage Monitoring in C/C++ | I am in a situation where I am extremely bandwidth limited and must devote most of the bandwidth to transferring one type of measurement data. Sometimes I will be sending out lots of this measurement data and other times I will just be waiting for events to occur (all of this is over a TCP socket).
I would like to b... | One of the simplest ways is to parse the file: /proc/net/dev
Mine contains:
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 44865 1431 0 0 0 0... |
1,332,067 | 1,332,101 | Problem using OpenProcess and ReadProcessMemory | I'm having some problems implementing an algorithm to read a foreign process' memory. Here is the main code:
System.Diagnostics.Process.EnterDebugMode();
IntPtr retValue = WinApi.OpenProcess((int)WinApi.OpenProcess_Access.VMRead | (int)WinApi.OpenProcess_Access.QueryInformation, 0, (uint)_proc.I... | C:\Debuggers>kd -z C:\Windows\notepad.exe
0:000> !error 0n299
Error code: (Win32) 0x12b (299) - Only part of a ReadProcessMemory
or WriteProcessMemory request was completed.
This means you tried to read a block that was partially unmapped addresses (i.e. if the app itself did this, it'd AV)
|
1,332,071 | 1,332,125 | Is SeDebugPrivilege() api function the same as System.Diagnostics.Process.EnterDebugMode? | What the title says. Are they the same? I've noticed that the first does have arguments and such, but are they going to give the same end result?
| Yes.
At least according to the documentation which states:
"Puts a Process component in state to
interact with operating system
processes that run in a special mode
by enabling the native property
SeDebugPrivilege on the current
thread."
|
1,332,142 | 1,332,171 | Should I link sqlite3 as plain object code or as a static library in a C++ application? | I am building an application in C++ which uses sqlite3 as an embedded database. The source for sqlite3 is distributed as an amalgamated source code file sqlite3.c and two header files.
What are the relative advantages or disadvantages of linking the sqlite3 code directly into my program binary versus compiling sqlite3... | It really doesn't make much difference.
Assuming you have some sort of makefile environment the sqlite.c will only be built once if you don't change anything and the linker will combine the object file in almost the same way as plugging in a static library.
|
1,332,146 | 1,332,524 | C++ game, class design and responsibilities | I've just read some related questions that came up when I typed the subject, so I'll try not to repeat those.
I've recently started revisiting a learning project I started about two or three years ago - a C++ port of a Mega Man engine. Yes I used ripped sprites. I also am using a game engine library for drawing, music,... | As far as making a class global I would use a singleton, then just call Game::GetInstance() which would return a pointer to the global class.
As far as the particles, the way I've always handled games was to make a class that manages all the objects. In my games main loop I would call that classes UpdateObjects functi... |
1,332,602 | 1,333,057 | How to serialize derived template classes with Boost.serialize? | I'd like to serialize/unserialize following classes:
class Feature{
...
virtual string str()=0;
};
template<typename T>
class GenericFeature : public Feature{
T value;
...
virtual string str();
};
I read boost.serialize docs and the sayed that you must register classes.
I can register them in constructor. But there ... | First tell boost that Feature is abstract, is not always needed:
BOOST_SERIALIZATION_ASSUME_ABSTRACT(Feature);
The serialization method should look more or less like this:
template<class Archive>
void Feature::serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(some_member);
}
temp... |
1,332,632 | 1,332,657 | defining bunch of static methods in c++ | Which is appropriate:
class xyz {
static int xyzOp1() { }
static int xyzOp2() { }
};
OR
namespace xyz {
static int xyzOp1() {}
static int xyzOp2() {}
};
Is there something specific which we can get when we define using class tag in comparision with namespace tag?
Also is there any different in memory manageme... | Without seeing the body of these functions, I would say that namespaces are more appropriate. With namespaces, you can have using statements, so that you don't have to fully-qualify the function names when calling them.
The only case in which to use classes is when the static methods have any relationship with objects ... |
1,332,678 | 1,333,121 | Priority when choosing overloaded template functions in C++ | I have the following problem:
class Base
{
};
class Derived : public Base
{
};
class Different
{
};
class X
{
public:
template <typename T>
static const char *func(T *data)
{
// Do something generic...
return "Generic";
}
static const char *func(Base *data)
{
// Do something specific...
... | I found a VERY easy solution!
class Base
{
};
class Derived : public Base
{
};
class Different
{
};
class X
{
private:
template <typename T>
static const char *intFunc(const void *, T *data)
{
// Do something generic...
return "Generic";
}
template <typename T>
static const char *intFunc(const B... |
1,332,754 | 1,332,965 | CMFCPropertyGridProperty numeric input | I'm using MFC feature pack and I have a dockable properties window. How do I restrict the user from typing any other characters but numbers alone in the values field?
Thanks...
| One of the constructors for the CMFCPropertyGridProperty class has a parameter lpszValidChars which you can use to limit the characters that can be input. e.g.
CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("Numeric Value"),
(_variant_t) 250l, _T("A numeric value"), NULL, NULL, NULL,
... |
1,332,762 | 1,332,862 | native win32 gui programming in c++ or choose wxWidgets? | i like to write GUI software ( i have no experience in GUI programming )
i need it to be small as possible and fast GUI and native Look and Feel in one self contained exe . only on windows from windows 2000 to windows 7 ( or what ever it called ) .
what will be the best choice ? win32 api or wxWidgets?
| You should take a look at the Windows Template Library (WTL).
|
1,332,928 | 1,332,944 | completely removing a vector c++ | I'm having problems removing a vector from a "multidimensional vector"
I would like to achieve this:
1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2
3 3 3 3 4 4 4 4
4 4 4 4
for example
vector<vector<int>>vec;
for i...//give vec values...
vec[3].erase(vec.begin(),vec.end());
It se... | The following line removes the third element of vec. If it had four elements, it will have three after the line is executed.
vec.erase(vec.begin() + 2);
The following line, on the other hand, will leave the third vector empty.
vec[2].clear();
|
1,333,069 | 1,333,115 | pointer arithmetic on vectors in c++ | i have a std::vector, namely
vector<vector<vector> > > mdata;
i want pass data from my mdata vector to the GSL function
gsl_spline_init(gsl_spline * spline, const double xa[], const double ya[], size_t size);
as ya. i already figured out that i can do things like
gsl_spline_init(spline, &(mgrid.front()), &(mdata[i][j... | You really can't do that without redesigning the array consumer function gsl_spline_init() - it relies on the data passed being a contiguous block of data. This is not the case with you three-level vector - not only it is a cube but also each level has a separate buffer allocated on heap.
|
1,333,176 | 1,333,193 | C++ and QT4.5 - is passing a const int& overkill? Does pass by reference helps in signals/slots? | Two questions rolled into one here...
I have a number of functions which are called multiple times per frame for a real-time video processing application. Taking advice about const and pass by reference, the functions have a signature somewhat like this
void processSomething(const int& value);
As I keep typing the few... | Yes, this is overkill and will actually result in slower code than if you passed the int by value. An int is four bytes; a reference (essentially a memory address) is either also four bytes (on a 32-bit machine) or eight bytes (on a 64-bit machine). So you may actually need to pass more information to the function -- a... |
1,333,296 | 1,333,328 | How virtual is this? | can you explain me why:
int main (int argc, char * const argv[]) {
Parent* p = new Child();
p->Method();
return 0;
}
prints "Child::Method()", and this:
int main (int argc, char * const argv[]) {
Parent p = *(new Child());
p.Method();
return 0;
}
prints "Parent::Method()"?
Classes:
class Paren... | Your second code copies a Child object into a Parent variable. By a process called slicing it loses all information specific to Child (i.e. all private fields partial to Child) and, as a consequence, all virtual method information associated with it.
Also, both your codes leak memory (but I guess you know this).
You ca... |
1,333,339 | 1,337,834 | astyle formatting multiple line << | I'm using astyle which is great for applying standard style to existing code. However I've noticed that when it comes across this:
ostringstream myStream;
myStream << 1
<< 2;
it reformats to this:
ostringstream myStream;
myStream << 1
<< 2;
Here's my options file: (version 1.23)
--indent=spaces
--brackets=... | Final Conclusion is it's a bug see bottom
I tried to replicate your problem and was unable to get the behavior you are talking about (OP question update negates this)
Edit: (deleted content to update)
Parameter names have changed between 1.22 and 1.23.
If neither solves your problem, try uploading more code as an examp... |
1,333,348 | 1,333,423 | Freeing in the destructor is causing a memory leak | I have to write a stack class template using arrays in C++ for my assignment.
Here is my code:
#include <iostream>
template <typename Type>
class Stack {
private:
int top;
Type items[];
public:
Stack() { top = -1; };
~Stack() { delete[] items; };
void push(Type);
bool isEmpty() const;
Type pop();
Typ... | You haven't new'd items, so you can't delete it in the destructor. Assuming you require 'Stack' to be a dynamically sized class then the items array must be dynamically allocated in which case the declaration for items should be
Type *items; (as hacker mentions above)
and the constructor should call 'items = new Ty... |
1,333,451 | 1,333,899 | Locale-independent "atof"? | I'm parsing GPS status entries in fixed NMEA sentences, where fraction part of geographical minutes comes always after period. However, on systems where locale defines comma as decimal separator, atof function ignores period and whole fraction part.
What is the best method to deal with this issue? Long/latitude string ... | You could always use (modulo error-checking):
#include <sstream>
...
float longitude = 0.0f;
std::istringstream istr(pField);
istr >> longitude;
The standard iostreams use the global locale by default (which in turn should be initialized to the classic (US) locale). Thus the above should work in general unless someo... |
1,333,522 | 1,333,544 | Why does the code crash? | Looking on the internet for C++ brainteasers, I found this example:
#include <iostream>
using namespace std;
class A {
public:
A()
{
cout << "A::A()" << endl;
}
~A()
{
cout << "A::~A()" << endl;
throw "A::exception";
}
};
class B {
public:
B()
{
cout <... | If you are really coding, not just brainteasing never ever throw exception from destructor. If an exception is thrown during stack-unwinding, terminate() is called. In your case destructor of A has thrown while processing exception that was thrown in B's constructor.
EDIT:
To be more precise (as suggested in comments)... |
1,333,524 | 1,333,550 | Developing a facebook app with c++ | I'm a computer science student with experience in C/C++ and I want to have a go at developing
a simple facebook app. Can anyone recommend a good website and/or editor?
Is it doable with C++ or do I need to learn another language?
Thanks
| I assume that you are talking about an internet application.
For the front end (client side), you will need something to enhance your web pages (in Javascript, for example). For the back end (server side), you will need to make database queries so you will need to know SQL as well.
No, I don't think C/C++ is enough.
I ... |
1,333,527 | 1,333,542 | How do I print to the debug output window in a Win32 app? | I've got a win32 project that I've loaded into Visual Studio 2005. I'd like to be able to print things to the Visual Studio output window, but I can't for the life of me work out how. I've tried 'printf' and 'cout <<' but my messages stay stubbornly unprinted.
Is there some sort of special way to print to the Visual St... | You can use OutputDebugString. OutputDebugString is a macro that depending on your build options either maps to OutputDebugStringA(char const*) or OutputDebugStringW(wchar_t const*). In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L p... |
1,333,658 | 1,397,402 | Need a Math Editor to write math formulas | Need a Math Editor to integrate to my application written on C# to be able to write math formulas. Can someone help me with this please? Some open source code will be great! Tell me steps, that integrate your suggested application to my application.
| I recommend you to use a MathML based editor. The formula description is a W3C standard.
A open source MathML editor is gNumerator. It's core component and rendering engine are almost complete.
What is gNumerator?
First and foremost, gNumerator is a collection of re-usable components that make up a computer math pro... |
1,333,660 | 1,356,774 | MFC: How to Identfy if Dialog was created using CPropertySheet or CTabCtrl | In reference to this question:Which is prefered CTabCtrl vs CPropertySheet
I have a DDK that uses MFC which I am new to. The basic example from the DDK implements a simple dialog box with 3 tabs with the "Ok" and "Cancel" button on the right side of the box.
Based on the question from the link above, seems like only C... | There are 2 classes derived from CPropertyPage, which is always used with CPropertySheet. No wonder there is no CTabCtrl. I'd like to explain in detail if you email me the code.
|
1,333,801 | 1,336,179 | How to close dynamically created CDockablePane windows? | In my MFC (Feature Pack) application one can dynamically create docking panes to display charts/tables etc.
However, I don't want to let the user open the same thing twice.
I create a pane like this:
// Create CMyDockablePane pPane
pPane->Create(...);
pPane->EnableDocking(CBRS_ALIGN_ANY);
// Create CRect rcPane
pPane->... | As described in my update, the problem for the docking manager giving me closed panes, was that the panes were not actually closed. Only their containers were closed; the panes themselves were just hidden.
So to really close the panes I overrode the following methods in my CMDIFrameWndEx derived main frame class:
BOO... |
1,333,849 | 1,337,648 | How to generate a non-const method from a const method? | While striving for const-correctness, I often find myself writing code such as this
class Bar;
class Foo {
public:
const Bar* bar() const { /* code that gets a Bar somewhere */ }
Bar* bar() {
return const_cast< Bar* >(
static_cast< const Foo* >(this)->bar());
}
};
for lots of methods like bar(). Writ... | Another way could be to write a template that calls the function (using CRTP) and inherit from it.
template<typename D>
struct const_forward {
protected:
// forbid deletion through a base-class ptr
~const_forward() { }
template<typename R, R const*(D::*pf)()const>
R *use_const() {
return const_cast<R *>( ... |
1,334,055 | 1,335,389 | What Happens When Stack and Heap Collide | I am curious to know what happens when the stack and the heap collide. If anybody has encountered this, please could they explain the scenario.
| In a modern languages running on a modern OS, you'll get either a stack overflow (hurray!) or malloc() or sbrk() or mmap() will fail when you try to grow the heap. But not all software is modern, so let's look at the failure modes:
If the stack grows into the heap, the typically C compiler will silently start to over... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.