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 |
|---|---|---|---|---|
5,486,113 | 5,486,583 | How to turn URL into IP address using boost::asio? | So I need some way of turning given Protocol://URLorIP:Port string into string ip int port How to do such thing with boost ASIO and Boost Regex? Or is it possible - to get IP using C++ Net Lib (boost candidate) - notice - we do not need long connection - only IP.
So I currently use such code for parsing
#include <boost... | Remember that there may be multiple IP addresses for any one hostname, boost gives you an iterator that will go through them.
The use is fairly straightforward, add this before return 0; of your program:
std::cout << "IP addresses: \n";
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_serv... |
5,486,341 | 5,486,407 | problem in reading binary file (mix of ascii and binary) | My code for reading binary file is:
dataFile.open(fileName.c_str());
ifstream binData("Trafficlog_Data.txt", ios::in | ios::binary); //binary data file
if(!binData) {
cout << "Cannot open file.\n";
return -1;
}
char *memblock;int nBytes =12;
memblock = new char [nBytes+1];
binData.read(memblock,nBytes);
membl... | Change:
memblock[nBytes+1]='\0';
to:
memblock[nBytes]='\0';
Let's say you read in six bytes to memblock, that goes into positions 0 through 5 inclusive:
0 1 2 3 4 5 6 7
+---+---+---+---+---+----+---+---+
| H | E | L | L | O | \n | ? | ? |
+---+---+---+---+---+----+---+---+
(the ? areas still contai... |
5,486,508 | 5,488,886 | Point cloud alignment using principal component analysis with CGAL | I have sets of randomly sampled points on the surface of 3D objects. I want to be able to compute the similarity between two different objects. To make that work, I first have to make sure that the sample points of both objects I want to compare do have the same rotation and scale. I thought I could do this by orientin... | Fitting a plane to a set of points leaves one degree of freedom unconstrained. The plane is free to spin around its normal and the fit is equal. I don't know anything about CGAL, but I wouldn't be surprised to discover that they just find a convenient plane when finding the fit (probably a nearest projection from the... |
5,486,586 | 5,487,410 | Embedded C++: Initialization of an array member of a struct within a class, size omitted | Hello there and thanks in advance for any help on the following matter.
Edit: I forgot to add that this is on an embedded system with no access to STL features. My apologies for leaving this very important piece of information out. This is my first time coding in C++ extensively so I forgot to mention the obvious. ... | In general, it's hard to create something that has a variable size in C or C++, without resorting to dynamic allocation, which you should try to avoid when using embedded systems.
I would suggest that you would create a plain array of things, and place a pointer to this inside your class. You can place the array in glo... |
5,486,753 | 5,493,406 | boost::program_options vector of values with zero_token | I'm trying to get the following syntax parsed with boost::program_options:
a)
$ a.out
verbosity: 0
b)
$ a.out -v
verbosity: 1
c)
$ a.out -v -v
verbosity: 2
d)
$ a.out -vv
verbosity: 2
e) (optional)
$ a.out -v3
verbosity: 3
My program so far:
#include <iostream>
#include <boost/program_options.hpp>
namespace po = b... | While it's not beautiful this solves my original question:
#include <iostream>
#include <vector>
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
std::pair<std::string, std::string> verbosity(const std::string& ... |
5,486,870 | 5,487,355 | pugixml "extend" element to add value | I trying to set the value of an element, regulary when the element looks like this <element></element> I just do this :
pugi::xml_node node = xmlBase.child("element");
pugi::xml_node nodechild = node.first_child();
nodechild.set_value(this->elementValue);
But, when I have an element looking like this:
<element />
thi... | Seems like the Solution is to do this:
nodechild = node.append_child(pugi::node_pcdata);
this will create a child thats only plain text within the element
|
5,487,122 | 5,487,346 | Overwrite only a specific part of a file | I know this was asked once, but I didn't understand the answer.
Let's say I have a file like this:
Guest list:
jon
mary
paul
luke
Table list:
And then, for example, I want to change the names of the guests. I understood that I need to search for the string "Guest list" and then overwrite everything between "Guest list... | If the new guest names do not match exactly the length of the old guest names, you can't perform the replacement in-place, it's best to use a temporary file.
Read the original file line-by-line until you locate the "Guest list:" delimiter copying each line to the temporary file.
Write the new guest list to the tempor... |
5,487,197 | 5,487,330 | Check for duplicates in large vector of strings | I'm attempting to find duplicate instances of strings where I have a vector of ~2.5 million strings.~
At the moment I use something like:
std::vector<string> concatVec; // Holds all of the concatenated strings containing columns C,D,E,J and U.
std::vector<string> dupecheckVec; // Holds all of the unique instances of co... | If you don't mind reordering the vector, then this should do it in O(n*log(n)) time:
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
To preserve the order, you could instead use a vector of (line-number, string*) pairs: sort by string, uniquify using a co... |
5,487,204 | 5,487,688 | Hashing Data greater than or equal to 56 bytes | I'm trying to understand the internal mechanism used in the SHA-1 hash function. I'm also referring to the FIPS-180 standard.
Managed to write an implementation is able to return accurate results hashing a string "abc". However I'm still blunt how to interpret strings >= 56 bytes. The FIPS-180 standard specifies to use... | Sha1 operates on messages with block size of 512bits (64 bytes).
What happens if you have a message of length 104 bytes? First you need to pad the message in order to be able to operate on blocks of size 512bits.
You take the incomplete last block of 104 - 64 = 40 bytes, and go through the message padding phase that is... |
5,487,249 | 5,487,814 | How write posix waitpid() analog for windows? | I want to port my linux code to windows. I don't want use cygwin or mingw. I would like to do this via WinApi. So who can help me to write waitpid() analog under windows?
| CreateProcess the way to create a new process. Its output is PROCESS_INFORMATION structure. WaitForSingleObject could wait for the end of the process.
Here is the example from MSDN library (GetExitCodeProcess was added.):
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )... |
5,487,302 | 5,488,022 | stopping parser when error found in semantic action | I wish to stop a token parser when the semantic action code finds a problem.
IF x > 10
is syntactically correct, but if x does not exist the the parser should stop
The grammar rule and semantic action look like this
condition
= ( tok.identifier >> tok.oper_ >> tok.value )
[
b... | Spirit has a special value you can use in a semantic action to make the parse fail. It's called _pass and you should set it to false.
From some of my code:
variable_reference_impl_[_pass = lookup_symbol_(_1, false)][_val = _1]
in this case, lookup_symbol is a Phoenix functor that returns true if the symbol is found, f... |
5,487,616 | 5,487,651 | Overloading of operator[] | What are the scenarios which may need to overload the subscript operator?
And what has the assert function got to do with this? I see in most cases of subscript overloading use of assert, would need an explanation on that.
| You might overload the [] operator on a custom container, to provide a syntactically/semantically clearer way of accessing elements.
For example my_container[3] = 9; is somewhat clearer than my_container.set(3, 9);
Of course, you could overload the [] to do essentially anything, but you probably shouldn't. You could, f... |
5,487,849 | 5,488,100 | Shall a C++ class function end with a }; or only a }? | A basic questions about C++ syntax.
Shall a c++ function end with a ; or does it not matter?
Or what is the difference between those two examples?
With a ending ;
void Test :: print()
{
...
};
Without ;
void Test :: print()
{
...
}
I have seen C++ code both with and without,
but I don't get the difference.
/Than... | Outside of a class body (where a function definition may optionally be followed by a single ;), a function definition is terminated by the end of a compound-statement - that is the closing }. At namespace scope, the next token after the closing brace of a function-definition must form part of the next declaration.
In C... |
5,488,057 | 20,266,156 | c++ mark enum value as deprecated? | Is it possible to mark an enum value as deprecated?
e.g.
enum MyEnum {
firstvalue = 0
secondvalue,
thirdvalue, // deprecated
fourthvalue
};
A second prize solution would be to ifdef a MSVC and a GCC solution.
| You can use the [[deprecated]] attribute from C++14 on.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3760.html
So, you would write this:
enum MyEnum {
firstvalue = 0
secondvalue,
thirdvalue [[deprecated]],
fourthvalue
};
When you deprecate an enum value with value explicitly assigned, then ... |
5,488,510 | 5,489,024 | Check if music has ended, OnStopped? | Is it possible to make SFML 1.6 handle end of music by itself? Currently I have this:
//in music.cpp
music.Play()
//in main.cpp
//on every frame check for end of music
if(music.getStatus() == Sound::Stopped)
loadNextMusicFile();
Isn't there a way in SFML to just say, "Play until music stopped, then load the next,... | If you look at the code from Music.cpp
bool Music::OnGetData(SoundStream::Chunk& data)
{
Lock lock(myMutex);
// Fill the chunk parameters
data.Samples = &mySamples[0];
data.NbSamples = myFile->Read(&mySamples[0], mySamples.size());
// Check if we have reached the end of the audio file
return... |
5,488,608 | 5,488,718 | How define an array of function pointers in C | I've a little question.
I'm trying to define an array of function pointers dynamically with calloc.
But I don't know how to write the syntax.
Thanks a lot.
| The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to:
int foo( int )
would be:
int (*)( int )
In order to name an instance of this type, put the name inside (*), after the star, so:
int (*foo_ptr)( int )
declares a variable called foo_pt... |
5,489,184 | 5,489,221 | How a can I extract these three numbers fast? | I have an std::string which contains 3 numbers which are separated by spaces
for instance: 123334 33335 54544. How a can I extract these three numbers fast?
int r = ... /* 123334 */
int g = ... /* 33335 */
int b = ... /* 54544*/
| The easiest way is to use a stringstream:
std::string numbers = "123334 33335 54544";
std::istringstream parse(numbers);
int r, g, b;
parse >> r;
parse >> g;
parse >> b;
if (!parse)
throw std::runtime_error("invalid string");
|
5,489,242 | 5,489,290 | Expanding array capacity | I was thinking of ways to make an array larger quickly in C++ and I came up with this:
// set up arr1
int *arr1 = new int[5];
// add data to arr1
arr1[0] = 1;
arr1[1] = 2;
arr1[2] = 3;
arr1[3] = 4;
arr1[4] = 5;
// set up arr2
int *arr2 = new int[10];
arr2 = arr1; // assign arr1 to arr2
// add more values
arr2[5] = 6... | The line arr2 = arr1; leaks memory, and all the following arr2[...]= lines invoke undefined behavior as they access the array of 5 ints outside of its bounds.
To do what you wanted to do, replace arr2 = arr1; with std::copy(arr1, arr1+5, arr2); (example program: https://ideone.com/3Rohu)
To do this properly, use std::... |
5,489,326 | 5,489,774 | /Za compiler directive does not compile system headers in VS2010 | I wanted to disable language extensions to be able to do some tests in my project. I found that I must set /Za compiler directive from http://msdn.microsoft.com/en-us/library/0k0w269d.aspx, but after this I have errors if I include windows headers. Is there a way to write standard compliant code(enforced by the compile... | The windows headers have never compiled with /Za.
There are other problems as well with /Za, that has caused Microsoft to stop testing their C++ standard library with that option. As told here:
http://permalink.gmane.org/gmane.comp.lib.boost.devel/212180
The recommendation is not to use it in "real" code.
|
5,489,331 | 5,489,439 | A function to populate an array with maps | I'm pretty new to C++ so I'm not sure I'm going about this problem in the right way. I'm dealing with a 3D array of voxel data and I would like to create a parallel data structure to store isosurface normal vectors. Memory efficiency is an issue so I thought to use a 2D array of maps, which are indexed by an integer an... | If i understood you correctly, you want to use the coordinate as a std::map key?
You could just create 1 dimensional std::map, and convert the XYZ coordinates into 1 dimensional coordinate system:
int pos1d = z*max_x*max_y+y*max_x+x;
and then just put that to the map key.
Edit: or you could just use a struct with x,y,... |
5,489,364 | 5,489,377 | Empty dynamic array in c++ | Let's say I have an object called Square with the constructor Square(int rx, int ry), i want to create a dynamic array of Squares, with different arguments in the constructor:
Square *squares = new Square[10];
for (int i = 0; i < 10; i++)
{
squares[i] = new Square(i, i);
}
However this fails, saying no appropri... | You could make an array of pointers to Square:
Square **squares = new Square*[10];
for (int i = 0; i < 10; i++)
{
squares[i] = new Square(i, i);
}
As others have pointed out, it is a good idea to consider using std::vector instead.
|
5,489,436 | 5,490,059 | Qt and C++ to show large DECIMAL number from MySQL without scientific notation | I have a large value in MySQL. It is stored in MySQL properly as a DECIMAL(22,2). I have confirmed that the value is stored properly. If I run a query via command console I get the proper value back in the desired non-scientific form (the value and the form is: 99996543210987654321.99).
The problem is that when I ru... | QSqlQuery::value() returns a QVariant, and there is no QVariant::toLongDouble or anything like that (aside from toString(), which doesn't work). So you have to do the conversion in MySQL--ALTER TABLE with the CHANGE option to change DECIMAL to VARCHAR or something like that, query the result, and then change it back. ... |
5,489,442 | 5,490,054 | Exception Handling for Files | If a program tries to use my file-reading class to access part of a file that does not exist (i.e., is after ios_base::end), what exception should be thrown?
I was going to use std::out_of_range, but now I'm beginning to think std::runtime_error would be more appropriate.
Edit:
The interface works a bit differently tha... | If you're providing an array-like interface (using operator[], rather
than get), then throwing std::out_of_range is a good idea; a better
idea in this case might be to figure out how many bytes you can actually
access, furnish a size() function, and make being in range
a pre-condition. (Of course, to provide random ac... |
5,489,503 | 5,490,637 | Do I need to overload delete if I have operator T *()? | If I have a template class A which holds a pointer, and A has an implicit conversion operator which will return that pointer, do I need to, or should I, define a delete operator for A, if I intent to apply delete to objects of this class?
| I believe that you've got something like the following:
template <typename T>
struct A {
T * t;
operator T* () { return t; }
};
An you intend to "apply delete to objects of this class", so by that I'm assuming you mean:
void foo ()
{
A<int> * p = new A<int>;
delete p; // Applying 'delete'
}
If this is th... |
5,489,695 | 5,489,757 | What are good (preferrably free) resources for a C#/Java developer to learn native C/C++? | I have quite a bit of experience in writing managed code (namely C#.net and Java), but I've been looking to become fluent in unmanaged C/C++ (as I would like to work on video games when I graduate in a few years). However, as I've been trying to make the transition, I've found that things I would otherwise consider to ... | http://www.horstmann.com/ccj2/ccjapp3.html looked pretty descent. I
|
5,489,744 | 5,489,813 | Is it normal practice or very bad to nest maps? | Is it normal practice or very bad to nest maps several levels?
// name property // name singal // interval of Ranges // values
typedef std::map<std::string, std::map<std::string, std::map<RangeSignalValue, std::string > > > sgHashSignals;
| I've certainly done this. However, I'd break down the definition into digestible chunks:
typedef std::map<RangeSignalValue, std::string> RangeIntervalMap;
typedef std::map<std::string, RangeIntervalMap> NameSignalMap;
typedef std::map<std::string, NameSignalMap> NamePropertyMap;
|
5,489,828 | 5,851,972 | Extending how Win 7 (Aero) draws it's default Windows and Controls | I'm looking to extend/override how Windows 7 draw's its standard Windows and controls. Right now I'm doing preliminary research on how to modify the standard UI to make it just a little bit more touch friendly for a project I'm working on.
Specifically what I would like to do is modify how W7 draws borders around its W... | There is no supported Windows API to replace the window visuals system-wide. Doing so requires use of undocumented APIs and hacky solutions. In turn, these kinds of hacks are likely to make your users' systems more unstable. I strongly recommend against it.
If you wish to adjust the visuals for you own app, you can use... |
5,489,872 | 5,489,907 | Attempting COM, Does C# use stdcall by default, or do you have to specify | The book I'm using describes C++ usage of COM and recommends __stdcall as a specifier, arguing that more languages use this method of stack cleanup.
However, I'm considering future interoperability with C#. Does C# use stdcall by default, or does it have to be specified?
| With COM interop, it doesn't matter as much.
If you're using Platform Invocation Services (P/Invoke), with C#, then stdcall is the default. (Technically, it's Winapi, which defaults to Stdcall on the desktop), but it can be overriden in a DllImport specification.
|
5,490,041 | 5,527,633 | Qt ,C++ - Adding QDIR::Filters to directories and files | I am trying to retrieve the files and directories in Qt using the QDir Filter. Based on the user input from the command line I plan to set the appropriate filters and retrieve the corresponding files.
User Input Eg: ./Retrieve -d C:/Sample -h
would retrieve me all the files including hidden files in the directory C:... | It's a three step process:
Define the flags that are the same regardless of user input, call it filters or something.
Iterate over the command line arguments and, when certain arguments are found, do a logical-OR of the appropriate QDir::Filter flag with filters
Keep going until all the cmdline arguments are dealt wit... |
5,490,083 | 5,490,231 | Block until boost::signal is called | Is there an easy way to wait for a boost::signal to be called? I have a signal that is called on every draw cycle in a GUI and I want a different thread to call a function and then wait for the next draw cycle (when the signal is called again so that I know the result of the function has been applied).
I think one solu... | Do you need to use signals for this?
Thread A: Drawing thread
Thread B: Other thread doing some work in response
Thread B could block on a condition. Thread A sets this condition true, which allows thread B to do some work. Thread B sets the condition to false and blocks on this condition.
If you really need to use the... |
5,490,101 | 5,490,124 | malloc exception in VS | i am trying to allocate memory for a 2 dimensional array using c and i am getting an exception in visual studio 2008.
int Count=16383,N=14;
char **result=(char**)malloc(sizeof(char)*Count);
for(int i=1;i<=Count;i++)
result[i] = (char*)malloc(sizeof(char)*N);
Unhandled exception at 0x012e1692 in combinatio... | char **result=(char**)malloc(sizeof(char)*Count);
should be
char **result=(char**)malloc(sizeof(char*)*Count);
|
5,490,113 | 5,491,227 | QListview, QTreeview which is right to show files in a list | I like to show files like in the Windows Explorer or any other file manager with Qt in a list. This was no problem using QFilesystemModel and QListView but there were no columns like size or the last modified date. Next I tried to use QTreeView and now there have been columns but unfortunately for moving into the files... | If I understand you correctly, you want multiple columns (which QListView does not support), but a flat list without the content of subfolders? This here works for me, tested on OS X:
It uses setRootIndex to hide the root folder ("/" in this case) and proxy model to filter all children of the root node's children.
#inc... |
5,490,159 | 5,494,547 | Visual Studio fatal error C1084: Cannot read include file: 'c:\program files (x86)\microsoft visual studio 10.0\vc\include\map': Permission denied | Having some problems with Visual C++ express 2010 and getting the same thing with Visual Studio 2010.
I get this error on compilation:
fatal error C1084: Cannot read include file: 'c:\program files (x86)\microsoft visual studio 10.0\vc\include\map': Permission denied
What's odd is this was compiling yesterday, I closed... | I copied the "map" file from another machine into my c:\program files (x86)\microsoft visual studio 10.0\vc\include\ and now it all works. It must have been corrupted somehow.
|
5,490,221 | 5,490,590 | Thread Pool Implementation | I'd like to make a simple thread pool (on a *nix system) to handle input on my asynchronous communication server. And I have some questions. At first I just want to have a static number of threads, arbitrarily say 6.
How should I send the command to the worker thread?
I was thinking of using simple socket communicatio... | First of all, you should realize that Windows has not just one, but two thread pool APIs built in. In case that wasn't enough, I/O completion ports are also basically thread pools in disguise. As such, there's probably not a lot of reason to write your own thread pool at all.
Unless you're planning on allowing your th... |
5,490,253 | 5,490,282 | important things to note for transition from wxWidgets to QT | I'd like to pick up QT for some future projects and I would like to know, what are some important concepts to keep in mind when developing in QT? I can see the concept of signals and slots vs. wxwidget's events as something pretty important to get a good understanding of, so what other concept for QT are important that... | The only real magic is signals/slots
There are a few other differences, Qt generally uses more modern C++ constructs than wx which is a bit more MFC era. But like most guis it's just a matter of learning the control->widget->window hierarchy.
It is worth getting the Qt4 book or at least reading the free Introduction to... |
5,490,333 | 5,491,262 | One AutoreleasePool per object? | I can't have a "big" NSAutoreleasePool in main() – I'm not allowed to touch it. So what's about having one pool per object?
struct MacGuiEngine
{
// members …
ScopedAutoreleasePool pool;
};
struct MacFontEngine
{
// members …
ScopedAutoreleasePool pool;
};
Is this a valid "pattern"?
| When you say you can't touch main(), when do you call UIApplicationMain()? I'm assuming this is iOS, since you don't need to create an autorelease pool in main() on Mac. Wherever you call UIApplicationMain() is where you want the top-level autorelease pool.
Remember, an autorelease pool is automatically created for you... |
5,490,414 | 5,490,711 | Concatenate 2 audio sources with OpenAL | I'm using OpenAL as the sound engine for my iPhone game, but still learning how to use it. I managed to play sounds with it, however I'm in one point when I need to concatenate (not merge) 2 sound sources (same file in fact, so this needs no conversion I guess) and I'm stuck. Any help would totally be appreciated:D
| I wonder if you landed on this: OpenAL Programmers Guide
Try looking into ExtAudioFile.
|
5,490,428 | 5,490,439 | What's the equivalent of WORD in C#? | I'm trying to access an unmanaged library and am lucky to have access to a comprehensive guide to the API.
Unfortunately, I've no idea what the C# equivalent of C++'s WORD type is. Similarly, I've no idea what DWORD would be.
| You're probably looking for ushort for WORD and uint for DWORD.
|
5,490,447 | 5,492,087 | make_heap not making heaps | I have a program that heapsorts a subset of another vector in a vector, as references to indices.
std::vector<foo> knowledgeBase;
std::vector<int> workingSet;
Does this comparison class work?
class Compare
{
bool operator()(int lft, int rgt)
{
return knowledgeBase[lft].bar() > knowledgeBase[rgt].bar();... | ... I feel dumb now.
class foo()
{
public:
foo();
void addLiteral(std::string var, bool truth);
bool bar(){return siz;} <==== returns a bool
private:
int siz;
std::set<Literal, LiteralComp> literals;
}
Sorry for wasting anyone's time.
|
5,490,756 | 5,490,842 | std::fill_n on array of non-PODs possible for first initializing? | is it possible to use std::fill to initialize an array of non-POD types?
The documentation says that std::fill uses operator= to initialize the array not placement copy construction. The assignment operator, however, does not really have a chance to free any current memory when it is called on an uninitialized space, a... | You're looking for std::uninitialized_fill_n from the memory header, not std::fill_n from the algorithm header.
Beware, however! Your code does not take alignment or padding into consideration -- consider using std::alignment_of, or the suitable boost replacement on platforms where it isn't available.
|
5,490,864 | 5,491,069 | Visual Studio C Performance | I have a C project (compiled as lib) in Visual Studio 2010. Functions from this library are then called from C++ (native, no CLR). My question is: Does Visual Studio compiler produce for plain C as fast binary code as it would for C++? Is there any performance penalty for plain C? I hope there is not, but I would like ... | Visual C++ uses the same code generation back-end for both C and C++, so it will generally produce identical output for equivalent input.
There are some things you can do in C++ (e.g., using templates) for which C provides no (reasonable/practical) equivalent. In some of these cases, C++ can (and typically will) allow ... |
5,490,962 | 5,491,653 | Pass function reference with boost python | I have such function in C++:
typedef boost::function<boost::shared_ptr<Object> (CL_DomElement*, std::string& desc)> Parser;
void registerParser(std::string type, Parser p);
// Later: exporting into python-module:
BOOST_PYTHON_MODULE(TypesManager)
{
bp::def("RegisterParser", registerParser);
}
# Python code:
class... | I don't believe Boost Python understands how to convert a python function to a boost::function object. What I would suggest is to use a proxy to take the python callable object and mimic the C++ interface. Quick example mock-up (untested, of course):
typedef boost::function<boost::shared_ptr<Object> (CL_DomElement*, s... |
5,491,007 | 5,562,132 | How would I build Box2D to work in Code::Blocks/Mingw32(Windows) | hey the title pretty much says it all. i have been trying different methods from internet sources, but whenever i try something goes wrong..this is where i got Box2D
in cMake, i get a bunch of errors when building it(i was going through the steps in the readme.txt, but onfortunately, theyre for Visual C++...)
so im won... | Assumptions:
You have installed cmake.
You have installed Code::Blocks/MinGW to C:\codeblocks.
You have downloaded Box2D and extracted it to C:\Box2D_v2.1.2.
If any of those are wrong, modify the paths to match what you have.
Start->Run->cmd.
Navigate to the Box2D "Build" folder:
cd C:\Box2D_v2.1.2\Box2D\Build
Create t... |
5,491,231 | 5,491,997 | console out in multi-threaded applications | Usually developing applications I am used to print to console in order to get useful debugging/tracing information. The application I am working now since it is multi-threaded sometimes I see my printf overlapping each other.
I tried to synchronize the screen using a mutex but I end up in slowing and blocking the app.... | You have 3 options. In increasing order of complexity:
Just use a simple mutex within each thread. The mutex is shared by all threads.
Send all the output to a single thread that does nothing but the logging.
Send all the output to a separate logging application.
Under most circumstances, I would go with #2. #1 is... |
5,491,263 | 5,491,385 | Forest of tree nodes C++? | Hey, I am trying to create a "forest" of tree nodes. A user will input two forests..
For example,
Forest1 :
a
_ _b
c
where b is a child tree/node of a.
Forest2:
d
e
_ _f
_ _ _ _g
_ _h
where d is a parent, e is the parent of f and h, f is the parent of g. f and h are siblings.
Anyway, I have two questions that I've... | It doesn't really matter too much on what kind of system you're on, but yes, process it line by line using an ifstream. There really isn't a "best way" to traverse this I don't think, as it is a text file and someone can pass you a txt file formatted in any weird way; so you should consider that and try to handle all ... |
5,491,508 | 5,491,802 | How to copy a char* to a char in c++ | I have been working on a question in c++ but im stuck in a part.
It is a long code but I will only post a small part of it where i am stuck now. Here it is;
char* x = (char*)malloc(sizeof(char));
char y = (char)malloc(sizeof(char));
y = *x;
The problem is when I do it, if X points to a char named "HELLO", when i print... | To paraphrase Inigo Montoya, I don't think this code means what you think it means.
malloc(sizeof(char))
This allocates a certain amount of memory. How much memory is allocated is dictated by malloc's parameter. In this case you're passing sizeof(char) which is, by definition, one byte exactly. Therefore, you are al... |
5,491,691 | 5,501,754 | Non-GPL library that can connect to a MySQL database? | I'm looking for a C, C++, or Objective-C library that can connect to a MySQL database. I'm aware of libmysqlclient (GPL) and SQLAPI++ (non-GPL).
Are there any alternatives besides SQLAPI++ that can be included in a non-GPL project?
| iODBC is BSD-licensed, and provides an ODBC client implementation.
The user could then install the MySQL Connector/ODBC to interface with the MySQL server.
|
5,491,893 | 5,492,044 | Using a Template to Expose a Private Typedef | I have a class that contains a private typedef and several member
functions:
class Foo
{
private:
typedef std::blahblah FooPart;
FooPart m_fooPart;
...
public:
int someFn1();
int someFn2();
};
Several member functions need to use m_fooPart in a similar way, so I
want to put that in a function. I put helper f... | Yes, that approach produces well-defined, standards-compliant behavior.
That said, adding member functions to a class does not increase the size of a class (assuming you mean the result of the sizeof operator), so I'm not sure what drawback you perceive in just making the helper function a private member of Foo.
|
5,491,920 | 5,492,140 | I want to write a function that iterates through a list? | I want to write a function that iterates through a list, but takes two elements if they equal a target.
The logic could be to have two loops; first iterate through list and see if any element + the first = target, then second, then third
etc..
int i;
int max = list.size;
for(i=0; i<=max; i++)
{
if()
}
in c++
... | It might help if you thought about it slightly differently. You said "first iterate through list and see if any element + the first = target". What if you phrased it as "Iterate through the list and see if the current element + any other element in the list = target". All I've done is consolidated your placement of ... |
5,492,380 | 5,492,605 | What is the C++ iostream endl fiasco? | I was listening to a google talk by Andrei Alexandrescu on the D programming language when he threw out a one liner about the "endl" fiasco. I just thought endl was the preferred way to signify the end of a line and flush the buffer for a stream. Why is it considered a fiasco? Should I not be using it in my code?
| (I assume) He just means that many, especially new, C++ programmers use std::endl blindly instead of '\n' for newline, flushing unnecessarily frequently and potentially making the performance of their program abysmal.
I.e., most people are taught that std::endl is the canonical way to insert a newline into a stream eve... |
5,492,485 | 5,492,535 | strcmp or string::compare? | I want to compare two strings. Is it possible with strcmp? (I tried and it does not seem to work). Is string::compare a solution?
Other than this, is there a way to compare a string to a char?
Thanks for the early comments. I was coding in C++ and yes it was std::string like some of you mentioned.
I didn't post the co... | For C++, use std::string and compare using string::compare.
For C use strcmp. If your (i meant your programs) strings (for some weird reason) aren't nul terminated, use strncmp instead.
But why would someone not use something as simple as == for std::string
?
|
5,492,747 | 5,492,765 | What is the operator `|=`? How can I implement this in C#? | What is the C++ code below doing? More specifically, what is the operator |=?
long liFaultFlags = 0;
for (int i = 0; i < FAULTCOUNT; i++)
{
if (faults[i] == true)
{
liFaultFlags |= (1 << i);
}
}
return liFaultFlags;
How would this be implemented in C#?
| It is the bitwise OR operator and is equivalent to
liFaultFlags = liFaultFlags | (1<<i);
You would write that line in exactly the same way in C#.
|
5,492,816 | 5,493,438 | std::string with no free store memory allocation | I have a question very similar to
How do I allocate a std::string on the stack using glibc's string implementation?
but I think it's worth asking again.
I want an std::string with local storage that overflows into the free store. std::basic_string provides an allocator as a template parameter, so it seems like the thi... | Andrei Alexandrescu, C++ programmer extraordinaire who wrote "Modern C++ Design" once wrote a great article about building different string implementations with customizable storage systems. His article (linked here) describes how you can do what you've described above as a special case of a much more general system t... |
5,492,879 | 5,492,944 | How to define copy constructor and = operator override in class with pointers on class object? | I heard that when there is a pointer in a class, there should always be copy constructor and = operator override in C++. I have searched about it and didn't found the explanation about when the pointer points to the class object.
To illustrate my problem:
class Figure
{
Figure();
Figure(const Figure& figure)
... | The typical solution for this is to make the needed operation abstract, and support it in subclasses.
class Figure {
virtual Figure * clone() const = 0;
};
class Sphere : public Figure {
Figure * clone() const {
return new Sphere(*this);
}
};
Then of course implement the Sphere copy constructor properly.... |
5,492,922 | 5,492,953 | char[N] versus char * | Could anyone tell me why there is a compile error with the following code?
struct Foo {
char m_p[8];
inline operator char *() const { return m_p; }
};
With GCC 4.5 I am given the message:
error: invalid conversion from 'const
char*' to 'char*'
while the Digital Mars compiler has no problem with it.
Edit: The ... | Since that operator is a const function, this and all its members (m_p) is supposed to be const. So the type of m_p is const char[8]. It cannot be implicitly converted to char* as the const-ness will be lost. Conversion to const char* is OK.
You could either make it return a const char*
inline operator const char *()... |
5,492,932 | 5,493,006 | Linking Error with Lua? | I've got a simple test application I'm trying to build in C++ with Lua (on Linux). The build line looks like this:
g++ -o"LuaTest" ./src/LuaTest.o -l/home/diego/lua-5.1.4/src/liblua.a
And it spits out this error:
/usr/bin/ld: cannot find -l/home/diego/lua-5.1.4/src/liblua.a
Which would be all well and good except tha... | Leave out the -l. It should be just:
g++ -o"LuaTest" ./src/LuaTest.o /home/diego/lua-5.1.4/src/liblua.a
The -l switch tells g++ to automatically add the lib and .a parts of the filename, and to look for it in the standard library directories - which you don't need here.
|
5,493,017 | 5,493,378 | Problem: How to convert CString into const char * in C++ MFC | How do I convert CString into const char *? I have tried everything found on the internet but I still cant convert them.
Please help.
Thank you.
| CString casts to const char * directly
CString temp;
temp = "Wow";
const char * foo = (LPCSTR) temp;
printf("%s", foo);
will print 'foo'
Newer version of MFC also support the GetString() method:
CString temp;
temp = "Wow";
const char * foo = temp.GetString();
printf("%s", foo);
|
5,493,143 | 5,493,166 | Why does C++'s complex class use getters and setters? | Why does the C++ complex class use functions to modify the real and imaginary parts? Wouldn't public member variables work just as well without having to deal with getters and setters? All that's been hidden is the private name of the real and imaginary parts.
| The simple reason for this is that it allows the implementation to change over time, even if it may not actually change often (if ever). If you have a class and you're modifying its instance variables, you're now dependent on those instance variables existing instead of having a public interface that could remain the ... |
5,493,171 | 5,498,772 | C++ read/write txt file in one task -> exchanging chars | I try to open a txt File for reading / writing in one task.
My prior target is to exchange some characters by the saved ones in an array:
void Inputfile::decryptFile(string filename)
{
for(int i=0;i<15;i++)
{
fstream filedest(filename.c_str(), ios::in | ios::out);
if(!filedest)
ce... | When replacing a file, usually two separate streams are used for input and
output individually.
If you need to use one stream for both input and output,
the while loop will be like the following:
while(filedest)
{
streampos p = filedest.tellg();
if(!filedest.get(ch)) break;
filedest.seekp(p);
char ch2 =... |
5,493,323 | 5,493,381 | Design decision for XML data transfer | I am implementing a profiler which collects data and sends the data via socket serialized in XML to a given host. The profiler is implemented in C++, the host (GUI) is implemented in Java.
It arises for me, putting data which belongs together into C++ classes, for instance a class ThreadInfo, containing string ThreadNa... | If your classes are simple, just use a plain XML structure to serialize the data and it will be easy to write your code and efficient. However, keep in mind that if you have things like special characters, binary data etc. in your data it would be easier to use something like CORBA as they will handle all special chara... |
5,493,395 | 5,493,762 | OpenProcess handle invalid for ReadProcessMemory | I've made this simple class to open a process and read memory from it:
The problem is when I call ReadDWORD with any memory address ReadProcessMemory fails with error code 6: ERROR_INVALID_HANDLE, The handle is invalid. And I can't figure out what I'm doing wrong.
If I put the OpenProcess part in the ReadDWORD function... | Memory::Memory()
{
Memory(0);
}
This isn't doing what you think its doing: it's not actually calling the other constructor, instead it's creating a temporary that gets discarded. So you are opening the process, but in a separate temporary object, while this object remains uninitialized.
Safer approach is to have a... |
5,493,474 | 5,493,656 | Graph implementation C++ | I was wondering about a quick to write implementation of a graph in c++. I need the data structure to be easy to manipulate and use graph algorithms(such as BFS,DFS, Kruskal, Dijkstra...).
I need this implementation for an algorithms Olympiad, so the easier to write the data structure the better.
Can you suggest such D... | It really depends on what algorithms you need to implement, there is no silver bullet (and that's shouldn't be a surprise... the general rule about programming is that there's no general rule ;-) ).
I often end up representing directed multigraphs using node/edge structures with pointers... more specifically:
struct No... |
5,493,492 | 5,494,330 | Silence between played buffers in OpenAL? | I use alSourceQueueBuffers to stream buffers into a AL sound source. I have buffers of different size that need to be played one after another. So far so good, however, between some buffer I need a variable amount of silence, how can I add it programmatic?
| Perhaps the easiest way would be to generate buffers that hold silence of the length needed and queue them appropriately. You just need to make an array full of zeros based on the sample rate and the desired length of silence and pass it into the buffer.
If you want things to be more complicated, then you can't queue ... |
5,493,676 | 5,493,680 | C++ Constructor Question | If I create a default parameter in my ctor then how will the compiler know which ctor to call the default ctor or the ctor with a default parameter.
| It won't. If you have the following class:
struct S {
S();
S(int = 0);
};
Then the compiler will report that the following is ambiguous:
S x;
|
5,493,688 | 5,493,734 | Stack overflow error or exception? | Why does the following ends up with no error?
void func()
{
func();
}
int main()
{
func();
}
| In theory, it would overflow the stack (because, even if no local variables are used, each call would add the previous return address on the stack); in practice, with optimizations enabled, it doesn't overflow because of tail call optimization, which actually avoids any resource consumption transforming the call in a j... |
5,493,745 | 5,493,793 | C++ linking 2 classes together how | this maybe a little trivial but I'm puzzled with such problem.
I want to create two classes Class1, Class2. Both classes should contain a field that contains pointer to instance of the other class. So they should be cross linked.
If I do it like this then I get an error from the compiller saying:
- ISO C++ forbids dec... | Add class declaration (as opposed to definition) before you use it. For example, you could have:
#ifndef CLASS1_H
#define CLASS1_H
class Class2;
class Class1
{
public:
Class1();
private:
Class2* link;
}
#endif
and do the same for Class2.h.
|
5,493,752 | 5,494,063 | QList of templated structures | Consider the following two structures:
template <typename T> struct duplet{
QString str;
T value;
}
struct MyObject{
QList<struct duplet> myList;
}
The compiler throws the following error:
error C3203: 'Duplet' : unspecialized class template can't be used as a template argument for template parameter 'T', expecte... | I think its simply that duplet, as a template, must be fully specified in order to serve as a template argument? The compiler can't create the mylist instance because it doesn't know what type it is. 'duplet' is not a (complete) type; 'duplet< T > for some type T' is.
struct MyObject {
QList<struct duplet<int> > my... |
5,493,758 | 5,494,390 | Visual Studio static library compiler hardcodes relative paths | I think my problem is that the Visual Studio static library linker hardcodes relative paths, and this causes problems later when linking against that static library from a different directory.
Here's what I'm trying to do:
I have a library dll, call it base.dll.
I have an application that links against this dll: appli... | The trick is to not link against base.dll when I build the static library, and only link against it when I build testing.dll.
|
5,493,819 | 5,493,921 | Could this alternative way to loop be more effcient? | I was bored one rainy afternoon and came up with this:
int ia_array[5][5][5]; //interger array called array
{
int i = 0, j = 0, k = 0;//counters
while( i < 5 )//loop conditions
{
ia_array[i][j][k] = 0;//do something
__asm inc k;//++k;
if( k > 4)
... | First off, your compiler will likely store the values of i, j and k in registers.
It's more efficient to do for (i = 4; i <=0; i--) than for(i = 0; i < 5; i++) as the cpu can determine if the result of the last operation it executed was zero for free - it doesn't have to explicitly compare to 4 (see the cmovz instructi... |
5,493,851 | 5,494,041 | Returning a global jobject in Java | I have two JNI functions. The first one allows the programmer to pass an arbitrary Java object to C++:
void Java_org_love_Lua_pushLightUserdata( JNIEnv* env, jobject javaThis, jlong state, jobject value )
{
jobject* objectRef = lua_newuserdata( (lua_State*)state, sizeof( jobject ) );
*objectRef = (*env)->NewGlo... | Because you aren't returning the global ref that you carefully created, but rather perhaps a long-stale local ref?
|
5,494,003 | 5,494,027 | Strange syntax in some Design Pattern code: explanation? | OK, I ran into this today, when the TI TMS470 C++ compiler refused to take it.
This comes from the Silver version of the C++ translation of the "Head First Design Patterns" example code.
class foo {
...
protected:
virtual ~foo() = 0 {}; // compiler barfs on this line
};
The compiler refused to accept the combin... | It is not legal C++. Pure virtual function can have a body, but the definition has to be made out-of-class.
In this particular case (the function is a destructor), the function must have a body if the class is used anywhere in the program (i.e. if it is used as a base class somewhere, since this is the only way one can... |
5,494,084 | 5,494,509 | how to execute TThread with parameter like in windows api? | When i creating TThread i can't pass parameters to thread, so i need use global variables or what?
I am using Embarcaderos Rad Studio C++ Builder 2010
| You have a class derived from TThread, right? Can you just make your class constructor take additional arguments (beyond the bool suspended one that seems to be common)?
|
5,494,340 | 5,495,895 | How to perform advanced search of all process memory from Visual Studio debugger? | I am a developer on a large commercial program, and I am trying to track down a particular C++ memory leak. I would like to use Visual Studio to search the entire valid address space of my process, but I can not see how to perform this search effectively.
I am aware of the .s command documentation here, but it is not ... | When doing anything beyond simple debugging, I find that often times WinDbg (part of Debugging Tools for Windows) has far better capability.
And you don't even have to do all your debugging from WinDbg. If you are in VS doing your thing and then want to search memory (or do other things which are not easy in VS), go t... |
5,494,368 | 5,495,082 | Windows system message constants in C++ | I was looking at some various sample code for processing mouse click events in C++ using a Windows system message hook, and thought that this would be a great way to process key presses that are usually only sent to the system, such as CTRL, ALT, SHIFT, etc. I was wondering if someone has a complete list of input const... | In addition to the link included in Donatalo's answer, this link goes to the list of keyboard constants - Virtual key codes, that I think you are looking for.
|
5,494,415 | 5,494,603 | C++ Vector removing specific items, but segfaults | all. I'm working on software to block ads using the system's hosts file, but on to the code.
I have a custom class HostEntry that contains necessary information such as the destination host, the host to block, the destination host's ip... etc.
In the HostsManager class, it keeps a vector to keep track of all the hosts ... | It is generally better to use std::remove_if to delete multiple items from a vector; it runs in linear time instead of quadratic and avoids having to worry about iterator invalidation.
Might look something like this:
hosts.erase(std::remove_if(hosts.begin(),
hosts.end(),
... |
5,494,613 | 5,494,638 | gcc fails to compile static function in namespace | I have the following declaration.
namespace test{
static cl_option* find_opt(const int &val, const cl_option *options);
}
test::cl_option* test::find_opt(const int &val, cl_option *options){}
The problem is when compiling I get the following error.
error: ‘test::cl_option* test::find_opt(const int&, test::cl_option*)... | The function you declared is different from the one you tried to define: the second parameter is "const" in the declaration, and not in the definition. Those are two different functions.
|
5,494,728 | 5,494,744 | When to use * and & signs (call by reference, or value, …) |
Possible Duplicate:
How to pass objects to functions in C++?
My main program gives me coefficient of plane equation as a vector.
I have many planes and I am trying to find out their intersections. So, I have series of plane parameters, belongs to each plane and I have created a map to accommodate plane parameters a... | If you want to learn when to use pointers or references I strongly recommend you read "Effective C++" and "More Effective C++" by Scott Meyers. They are both excellent books that will give you a deep understanding of how to write good C++ code.
I'm sure they're available on Amazon.
|
5,494,878 | 5,495,104 | How to make an inversely proportional loop? | Hey, I'm trying to write a loop which updates within a method at 1/60 fps.
Basically, im trying to find out how to write a loop that says:
If x is increasing. decrease y.
I tried defining two variables for x; x1 and x2, x1 being the original value and x2 being the altered value.
int x1,x2,y;
x1 = x2;
if (x2 > x1... | This takes care of X increasing and decreasing.
I am assuming: integers, a 1-1 linear relationship.
(pseudo code)
Note, lastXValue is global or static to the context.
int y; // comes from somewhere
int lastXValue = y;
function callBack(int currentXValue) {
int delta = currentXValue - lastXValue; // Note: can be negat... |
5,494,995 | 5,495,012 | Sphere with gravitational pull at the center | I'm wondering whats the easiest way to apply gravity at the center of a sphere (much like a planet) I'm thinking that ODE would be the best library to use? But not sure on how to implement it to apply the gravity at the center of the sphere.
| All you need is :
a = F/m = -GM r/r^3
where r is the radial vector for the mass m from the Sphere of mass M and G is the Gravitational constant.
You don't necessarily need much of a library to integrate this. You can just compute acceleration for each time step. The only point is that you get a much better result (E.g.... |
5,495,019 | 5,495,034 | Why does Microsoft use the "g_" naming convention with its DirectX10 pipeline variables? | Most of the sample code from Microsoft's DirectX SDK includes variables which use the g_ prefix for Windows API variables, as well as DirectX pipeline variables, such as the swapchain.
Here are some samples:
D3D10_DRIVER_TYPE g_driverType;
ID3D10Device* g_pd3dDevice;
IDXGISwapChain* ... | The g_ typically stands for global variable. The (non-.NET) code presented in Microsoft documentation and samples may use some variant of Hungarian notation for historical reasons.
Systems Hungarian notation isn't used very much, if at all, in C++ since the compiler already knows the types of your variables. There is s... |
5,495,032 | 5,495,186 | Using a Classifier with a split_iterator | There is something about the boost string algorithms that I seem to be missing. I am trying to use a split_iterator with a using Clasifier as the split point. So, for example I would like to be able to do something like this:
make_split_iterator(str, is_space);
however make_split_iterator expects a Range and a Finde... | You can use token_finder, as in make_split_iterator(str, token_finder(is_space())) or make_split_iterator(str, token_finder(is_any_of(" "))) etc.
Full example, assuming your goal is tokenize (hence token_compress_on)
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
int main()
{
std::s... |
5,495,390 | 5,495,405 | How to compare range of date in C/C++? | Is there any system defined function to compare two dates in C/C++?
Thanks
|
convert the date (you pick the format) to seconds since the start of the era. use strptime and mktime.
compare the two time_t (seconds) values.
example using MON-DD-YYYY format:
CODE:
#include <time.h>
time_t to_seconds(const char *date)
{
struct tm storage={0,0,0,0,0,0,0,0,0};
char *p=NULL;
time_t retval... |
5,495,559 | 5,495,776 | How to autologin to oracle using OCI with C++ using windows credentials? | Basically I have a C++ app which login to oracle db using OCI.
DB is configured to authenticate users from windows domain user accounts.
At the moment when my client log in, I pass user name and password to OCI in order to login by setting OCI_ATTR_PASSWORD and OCI_ATTR_USERNAME attributes in user session handle.
What ... | See Oracle Call Interface Programmer's Guide - OCISessionBegin()
The second type of credentials
supported are external credentials. No
attributes need to be set on the user
session handle before calling
OCISessionBegin(). The credential type
is OCI_CRED_EXT. This is equivalent to
the Oracle7 'connect /' sy... |
5,495,615 | 5,496,311 | C++ Should this be easier? | long-time listener, first-time caller. I am relatively new to programming and was looking back at some of the code I wrote for an old lab. Is there an easier way to tell if a double is evenly divisible by an integer?
double num (//whatever);
int divisor (//an integer);
bool bananas;
if(floor(num)!= num || static_ca... | The question is strange, and the checks are as well. The problem is that it makes little sense to speak about divisibility of a floating point number because floating point number are represented imprecisely in binary, and divisibility is about exactitude.
I encourage you to read this article, by David Goldberg: What E... |
5,495,936 | 5,496,215 | Statement from ISO standard $3.1 : 1st point from n3242 doc | Statement from ISO standard $3.1 : 1st point
n3242 Says:
A declaration (Clause 7) may
introduce one or more names into a
translation unit or redeclare names
introduced by previous declarations.
If so, the declaration specifies the
interpretation and attributes of these
names. A declaration may also ha... | I believe it just that some new features have changed the way a declaration works - in the small details.
For example, this does't just introduce some names, but also affects compilation of the code.
struct A
{
int x;
};
struct B
{
A a;
static_assert(sizeof(a) > 10, "Wrong member size");
};
We also have th... |
5,496,254 | 5,496,309 | C++ graph implemation |
Possible Duplicate:
Graph implementation C++
Hi
I was wondering about a quick to write implementation of a graph in c++. I need the data structure to be easy to manipulate and use graph algorithms(such as BFS,DFS, Kruskal, Dijkstra...).
I need this implementation for an algorithms Olympiad, so the easier to write th... | Instead of maintaining nextEdge list inside an edge, you should implement them separately.
struct Edge
{
int start;
int end;
};
Since you are using C++ and it's for a Olympiad, better use everything STL has to offer.
Therefore, store the Edges inside a vector. This would be helpful for algorithms that iterate over Ed... |
5,496,692 | 5,496,726 | How to remove element(s) from std::vector without resizing it |
iterator erase ( iterator position );
iterator erase ( iterator first,
iterator last );
Erase elements Removes from the vector
container either a single element
(position) or a range of elements
([first,last)).
This effectively reduces the vector
size by the number of elements
removed, calling each element... | resize will never reduce the capacity of the vector - you can safely use erase for this.
Use reserve to make a vector preallocate space for a certain number of items. Unless you actually exceed this limit, no insert or erase or resize will lead to a realloc. If you exceed it, the vector will internally reserve more spa... |
5,496,706 | 5,496,740 | Issues with setfill in a member function | I am trying to create a program over multiple files that reads out the time, but I am having trouble displaying the time in the desired format. More specifically, setfill appears to be causing me problems.
Here is the beginning of a very long error messages I recieve when compiling:
error: no match for ‘operator<<’ in... | setfill takes a char, it should be '0' instead of "0"
|
5,496,811 | 5,523,410 | Broken indentation for Qt-specific constructions in Visual Studio | Automatic indentation in VS editor obviously does not know about Qt. And declarations of signals and slots are auto-formatted like this:
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass();
signals: // <-- Broken indentation
void someSignal();
public slots: // <-- Also broken
... | In short answer seems to be NO. Maybe not what you are looking for but maybe you can live with this:
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass();
private:
Q_SIGNAL void someSignal();
public:
Q_SLOT void someSlot();
};
(It's ugly but it seems you can't have your cak... |
5,496,827 | 5,496,893 | In QListWidget how do i check if QListWidgetItem already exists based on its Data member | im setting item's in QListWidget and in each QListWidgetItem im setting id like this:
newItem->setData(Qt::DisplayRole,ID);
now each time before im adding the itemi wish to check if already there is item with the same data in the list .
how can i do that ... i don't think the findItems will help me here
| Let me assume that type of ID is int (cause you didn't specify it).
bool found = false;
for (int i = 0; i < list->count(); ++i) {
if (list->item(i)->data(Qt::DisplayRole).toInt() == ID_to_match) {
found = true;
break;
}
}
if (!found) {
do_something_here();
}
|
5,496,911 | 5,496,954 | Is dictionary in Python can be seen as Map in C++ | Is dictionary in Python can be seen as Map in C++
And the insert complexity is constant time?
and what about sort complexity of dictionary?
What about iteration?
Need some good points or link to good resource.
Thanks!
| If I recall correctly, the C++ map implementation uses a tree, so insertion and retrieval is O(log(n)) as opposed to O(1).
Python uses hashtables, so retrieval is O(1).
|
5,496,912 | 24,269,514 | Unit testing non-exported classes in a DLL | We develop a C++ application using Visual Studio 2008 and unit test using Boost.Test. At the moment, we have a separate solution which contains our unit tests.
Many of our projects in the core solution produce DLL's. We're limited in test coverage because we cannot test non-exported classes.
I have two ideas on how the... | Expanding on Tom Quarendon's answer to this question, I have used a slight variant of Simon Steele's response:
Create a test project (using whatever test framework you like, I use CppUnit).
In your test_case.cpp, #include <header/in/source/project.h>.
In the test project properties:
In Linker->General, add the sourc... |
5,496,921 | 5,523,062 | How can I track cases when a pointer from a "new" expression is passed to dynamic_cast? | Recently I found the following while reviewing some old code:
auto_ptr<DerivedClass> pointer = dynamic_cast<CBase*>( new CDerived() );
aside from the fact that this code is meaningless in valid cases (in valid cases class Derived is derived from class Base and no dynamic_cast is necessary) there's a problem with objec... | Get rid of all your dynamic_casts.
All of them.
Then no tracking will be necessary.
|
5,497,014 | 5,497,091 | A recommendation for a good programming book in Threads and Concurrency in c\c++ | HI all!
I'm currently taking the course Operating Systems in my university. We mainly study theory and have simple exercises in c++ to exercise some theoretical principles.
I want to study more about the practical programming in concurrency and threads in c\c++ and i was wondering if any of you have a good book to rec... | I have also been looking for such a book, they are very hard to come by. This one will be released in May, if that's any help:
http://www.manning.com/williams/
I purchased this book:
http://www.amazon.co.uk/gp/product/0123705916/ref=oss_product
It's very good, it's in java, but most of the principles apply to c/c++ any... |
5,497,100 | 5,497,372 | Alterative array representation | I'm facing a problem in C++ for which I currently don't have an elegant solution. I'm receiving data in the following format:
typedef struct {
int x;
int y;
int z;
}Data3D;
vector<Data3D> v; // the way data is received (can be modified)
But the functions that do the computations receive parameters like this:
Co... | You could of course change your computer function.
I assume that all operation done on your int* in compute are dereference and increment operation.
I did not test it but you could pass in a structure like this
struct IntIterator
{
int* m_currentPos;
IntIterator(int* startPos):m_currentPos(startPos){};
Int... |
5,497,277 | 5,497,312 | How to read space separated numbers from console? | I'm trying to do a simple task of reading space separated numbers from console into a vector<int>, but I'm not getting how to do this properly.
This is what I have done till now:
int n = 0;
vector<int> steps;
while(cin>>n)
{
steps.push_back(n);
}
However, this requires the user to press an invalid character (such... | Use a getline combined with an istringstream to extract the numbers.
std::string input;
getline(cin, input);
std::istringstream iss(input);
int temp;
while(iss >> temp)
{
yourvector.push_back(temp);
}
|
5,497,284 | 5,498,570 | Is it OK to use iostreams with int as character-type? | When trying to come up with an answer to this question, I wrote this little test-program:
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
void writeFile() {
int data[] = {0,1,2,3,4,5,6,7,8,9,1000};
std::basic_ofstream<int> file("test.data", std::ios::binary);
... | Instantiating any of the iostream classes, or basic_string, on anything
but char or wchar_t, without providing a specific custom traits class,
is undefined behavior; most of the libraries I've seen do define it to
do something, but that definition often isn't specified, and is
different between VC++ and g++ (the two ca... |
5,497,317 | 5,497,376 | Can I translate ADDRESS in a code line? | I receive from an application a message like this:
"The instruction at 0xA.... referenced memory at 0xB..... The memory could not be "written". Click on OK to terminate the program"
the address 0xA looks valid: 0x10001053. Exe is mapped in memory by default at 0x40000000 and dlls at 0x10000000 so it's in the first load... | You should be able to locate it with the help of a map file. You may need to tweak some of your compiler/linker options to get the map file generated with sufficient detail.
If you are using the MS compiler then you need /MAP linker option.
|
5,497,348 | 28,629,282 | Debug and Release Library Linking with CMAKE (VISUAL STUDIO) | There was already a Thread which did not help really. I want to be able to link for example Foo.lib for Release Config and Foo_d.lib for Debug Config , how can I achieve this?
If I do this:
target_link_libraries(MyEXE debug Foo_d)
target_link_libraries(MyEXE optimized Foo)
then I have both libraries in my project for... | There is no problems when your library is a part of the project or you're
importing it using config mode of find_package command (see documentation and example).
In case you can't modify 3rd party so it will produce <package>Config.cmake
(it may not use cmake tool or you don't want to do it) the answer is to emulate
su... |
5,497,512 | 5,497,654 | How to write a C or C++ program to detect modules in another C program, using a syntax tree | I'm working on a project where I have to divide a C program into modules and find the time taken for the execution of each module. I have to use C or C++ to do this.
For example: the first module will be main() then inside you may have other modules like for, or while or if etc.
It's actually like generating a syntax t... | What you're describing is a profiler. Which one is suitable very much depends on the platform which you're using.
For Window and Visual C++ I've found LTProf to be lightweight, inexpensive and usable http://www.lw-tech.com/index.php?option=com_content&task=view&id=25&Itemid=65. Alternatively the higher end Visual Studi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.