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 |
|---|---|---|---|---|
6,281,226 | 6,281,956 | Howto use a GUID as an ADO query parameter using C++ ADO | Given a SQL Server database that uses uniqueidentifiers as primary key fields for the table I want to query and a GUID struct (included via rpc.h) that has the value of one of the entries in the table, how do I create a ADODB::Parameter that stores that value?
I understand that the parameters take their values as _vari... | Pass a string, formatted with curly braces. If you have the guid value stored in a variable of type System.Guid then you can use the "B" format specifier. Like this:
var arg = guid.ToString("B");
See this web page for reference.
Oops, that's C# code, you can generate the string in C++ by using StringFromIID().
|
6,281,368 | 6,281,389 | Multi-line DEFINE directives? | I am not an expert, so go easy on me. Are there any differences between these two code segments?
#define BIT3 (0x1
<
<
3)
static int a;
and
#define BIT3 (0x1 << 3) static int a;
Also, is there a way to write the first in one line? What is the point of this multi-line style? Is the following code good?
#define BIT3... | A multi-line macro is useful if you have a very complex macro which would be difficult to read if it were all on one line (although it's inadvisable to have very complex macros).
In general, you can write a multi-line define using the line-continuation character, \. So e.g.
#define MY_MACRO printf( \
"I like %d... |
6,281,429 | 6,282,015 | OpenMP slow reduction | I write simple C++ code that compute array reduction sum, but with OpenMP reduction program works slowly. There are two variants of program: one is simplest sum, another - sum of complex math function. In code complex variant is commented.
#include <iostream>
#include <omp.h>
#include <math.h>
using namespace std;
#d... | The function clock() measures processor time consumed by whole process, so printed time shows sum of time consumed by all threads. If you want to see wall-time (real time elapsed from the begin to the end), use e.g. times() function on the POSIX system
|
6,281,437 | 6,281,486 | C++ Database API's - DTL | I'm looking for a C++ API that is able to connect to different types of databases all in one; mainly MySQL, oracle and SQL Server and I believe I have found one with "DTL" ( http://dtemplatelib.sourceforge.net/ )
However, I'm struggling to connect my database on localhost. Has anyone used this before and could shed som... | This is an ODBC library, so DSN is the ODBC data source name. On Windows, these can be configured under Administrative Tools->Data Sources.
|
6,281,472 | 6,281,715 | Why does a default argument for a lambda argument trigger a -pedantic" GCC warning? | I had this lambda somewhere in my code:
[](bool a, bool=true){ return !a;} }
and GCC 4.6 "complained" with this warning:
warning: default argument specified for lambda parameter [-pedantic]
Which is mightily unhelpful when you don't know why this is "bad". I consulted the FDIS n3290 and didn't find anything in 5.1.2 ... | Section 5.1.2 paragraph 5 specifically says that you can not have default values for the parameters.
Default arguments (8.3.6) shall not be specified in the parameter-declaration-clause of a lambda-declarator.
|
6,281,543 | 6,281,651 | C++ implementation of DHT | I am looking for opensource implementations of Kademlia DHT in C/C++. It must be lightweight and crossplatform (win/linux/mac).
It must be able to post information to DHT and retrieve it.
| What's wrong with maidsafe-dht ?
|
6,281,773 | 6,281,797 | It's possible to write data of an unopened C++ ofstream to a file? | With unopened I mean:
ofstream outFile;
outFile << "Some text";
So I put text in an ofstream without call the .open() method. g++ does not complain, so maybe I still can save the data? How?
| The stream will be in a failure state after you do this (outFile.fail() will be true). The text isn't stored anywhere, so no, you can't save it.
If you want to store data in memory, use an std::ostringstream (from the <sstream> header) instead.
|
6,281,835 | 6,283,015 | How Do C++ Compilers Merge Identical String Literals | How does compiler (MS Visual C++ 2010) combine identical string literals in different cpp source files? For example, if I have the string literal "hello world\n" in src1.cpp and src2.cpp respectively. The compiled exe file will have only 1 "hello world" string literal probably in the constant/readonly section. Is th... | (Note the following applies only to MSVC)
My first answer was misleading since I thought that the literal merging was magic done by the linker (and so that the /GF flag would only be needed by the linker).
However, that was a mistake. It turns out the linker has little special involvement in merging string literals ... |
6,281,916 | 6,282,279 | How to get better error messages in Boost program options | In the code below, I used program options to read parameters from command-line or file. In addition, options can be set programatically at runtime through ConfigProxy::setConfig
po::options_description desc("Allowed options");
desc.add_options()
...
("compression", po::value<int>(), "set compression level");
p... | Have you tried it?
("compression", po::value<int>(), "set compression level");
Notice po::value<int>(). You specify here that the associated value has type int. When the user passes something that Boost.ProgramOptions can't convert to int, the program fails with an error message:
error: in option 'compression': invali... |
6,281,944 | 6,281,990 | Adding Buttons in DOS | How can I add a button in a c++ dos evironment? One where when you click it, it creates a response from the game. (If there is a library and an A file, I can add those)
| ... in which case I would suggest Allegro 4.2 for DOS. But that only works in 80386 and higher CPUs, not 16-bit computers.
|
6,282,074 | 6,282,103 | C++ and binary compatibility: returning a POD struct by value | Consider the following C++ code:
struct X
{
int a;
int b;
};
X foobar()
{
X x = { 1, 2 };
return x;
}
Now assume this code is put in a shared library, which is used by third-party applications.
My question is: if I add another member at the end of X (e.g. int c), and initialize it in f... | It depends entirely on what your compiler chooses to do (more specifically, what the platform ABI dictates).
You can imagine that if the return value is placed on the stack, you would now be writing more onto the stack than the caller is expecting, which may result in stamping on something.
In general, you shouldn't re... |
6,282,081 | 6,282,180 | How do I set up a C++ project in Xcode 4? | This probably has a really obvious answer, but I can't seem to find it. I am trying to use Xcode 4 to program with C++, and I want to create a project, build, and run it through Xcode 4 like I do for other languages. My problem is that I can't find the right type of project to do this.
| Check this out : http://www.youtube.com/watch?v=Ey8LK7P1K94 at 2:30 he creates a C++ project.
Or try this:
Open XCode.
File/New Project...
In the "New Project" Assistant, expand the "Command Line Utility" group.
Select "C++ Tool"
Click "Next"
Give a project name and directory, then click "Finish".
Press Cmd-Shift-R t... |
6,282,097 | 6,282,297 | Enum<-> string map functions | I currently have two maps that link enum values to strings, one direction to convert file input to internal representation, the other to print (debug) information about that internal representation. I would like to change the map to a vector for generally faster access and conversion. But then this function, which work... | Leave the first definition as it is, but change the second one to cover all vectors. Use both in your program, the compiler will choose the appropriate version as necessary.
template<class T, class Y>
const T & map_value( const std::map<Y,T> &map, const Y &key )
{
return (*map.find(key)).second;
}
template<class T... |
6,282,258 | 6,282,434 | Using boost::asio to perform unicast messaging | What is the simplest way in C++ (an actual code example would be great) to establish/open a UDP unicast connection if I know the IP address and port?
The resolver/query/endpoint/iterator stuff seems a bit like overkill and at my level of understanding, so far a bit confusing.
First of all I'm new to Boost, but I have d... | There is an example here that uses resolvers etc.
http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime4.html
If you wish to use an ip address that you already have, you can do something like this:
boost::asio::ip::address ip_add = boost::asio::ip::address::from_string("192.168.1.1");
tcp::endpoi... |
6,282,333 | 6,283,472 | YAML::Emitter stream size | I have an iterative algorithm, written in C++. I am using yaml-cpp. On each iteration I send send some data to a YAML::Emitter object. When the algorithm terminates I use YAML::Emitter::c_str() to write the underlying buffer to an ofstream.
However, I would prefer to write the buffer to the file incrementally every fe... | It sounds like you'd like a pluggable "writer" for the YAML::Emitter - if so, please file a feature request at http://code.google.com/p/yaml-cpp/issues/list.
(I can't guarantee how quickly I'll get to it, but I'd be happy to accept patches as well.)
In the meantime, you can tag-team the emitter's c_str() and size() met... |
6,282,378 | 6,282,461 | Get record set from stored procedure using C++ ADODB CommandPtr::Execute() | I'm trying to get a recordset from a stored procedure using ADODB.
Stored procedures get executeed successfully (Doing everything written in the SP), but the recordset count is "-1".
Here is what I'm doing (stored procedure has no parameters):
hr = ptrCom.CreateInstance(__uuidof(Command));
ptrCom->ActiveConnection = _c... | Have you tried just calling Execute?
ptrCom->Execute(NULL, NULL, ADODB::adCmdStoredProc);
returns _RecordSetPtr.
You might also want to try:
after you set the connection.
ptrCom->ActiveConnection->PutCursorLocation(ADODB::adUseClient);
|
6,282,601 | 6,282,746 | How do I declare objects from my main window in Qt Creator? | This question should hopefully be easy to answer. I created a few buttons in my MainWindow using Qt Creator, and when I go to write the functions for the buttons, the compiler says they were not declared in this scope. What do I need to #include for these objects to be declared? The compiler error for the following wou... | The items you define in your .ui file are not added directly to your main window class, they are added to its ui membre.
Try with:
ui->baseDir->setText( path );
Look at the ui_mainwindow.h file that is generated during the build if you're curious.
|
6,282,697 | 6,282,822 | Why does Visual Studio 2010 create precompiled header files even if I don't ask for it? | I have Visual Studio 2010 with SP1 installed. I want to create a simple Win32 console application in C++.
I click New Project \ Win32 Console Application
There I click Console Application, no for "Empty project", no for "Precompiled header", no for "ATL" and "MFC".
The wizard looks like this:
Now, if I click finish, I... | They're not precompiled header files unless they are compiled with the appropriate compiler flags(Yc to create the pch, and Yu to use it). If you check the Precompiled Header checkbox, those flags are set by default on all files added to the project. If you don't check it, they are not.
If you don't want any files ge... |
6,282,712 | 6,282,898 | How to extract file paths from a text file | I am looking for a tool / code in C#, or C++ / C that can extract file paths from a file e.g.
File.txt:
Lorem Impusum
C:\Windows\System32\test.exe
C:\Users\Limited\Downloads.txt
testing 123
So it would output File.txt as follows:
C:\Windows\System32\test.exe
C:\Users\Limited\Downloads.txt
| This should return what you're after, assuming you've loaded the contents of your file into a List<string> or string[]
var result = potentialPaths.Where(Path.IsPathRooted).ToList();
Also, this is C#.
|
6,282,848 | 6,282,917 | Are methods in classes using the 'Curiously Recurring Template Pattern' inlined by a modern c++ compiler | I have a performance critical piece of code for which I am considering using the CRTP. My question is to what extent most compilers are able to optimize the code. In particular I am wondering if the compiler can inline (when appropriate) methods. For example, in the following code:
template <class Derived>
struct Base... | With optimization turned on, and if the compiler considers this to be worth inlining, yes.
What's good in CRTP compared to dynamic dispatch, is that from compiler's point of view it's a regular function call.
|
6,282,981 | 6,284,994 | Symmetric array-like data structure for c++ | I'm doing a simulation where I must calculate many averages and I thought that using boost::accumulators would be a good idea. The problem is that one of the quantities I want to average is a symmetric matrix, whose diagonal is known beforehand. SO I just need to calculate the averages for Q[i][j] if i < j.
At first I... | Try the Boost uBLAS Triangular matrix. Here is an example.
|
6,283,085 | 6,283,176 | getline seems to not working correctly | Please tell me what am I doing wrong here. What I want to do is this:
1.Having txt file with four numbers and each of this numbers has 15 digits:
std::ifstream file("numbers.txt",std::ios::binary);
I'm trying to read those numbers into my array:
char num[4][15];
And what I'm thinking I'm doing is: for as long... | Do not use the eof() function! The canonical way to read lines is:
while( getline( cin, line ) ) {
// do something with line
}
|
6,283,272 | 6,283,732 | How to avoid clone() boilerplate code for polymorphic objects in c++ | If I want to clone a polymorphic object in C++ (i.e. an instance of a class A which is derived from some other class B), the easiest way seems to give B a virtual clone member function, that has to be overridden by A and looks like this
A* clone(){
return new A(*this);
}
My problem is, that I find this unnecessary... | I handled this issue with a macro... it's ugly, but it works to avoid inconsistencies.
/** An interface that can be inherited by any class that wants to provide a Clone()
* method that will return a copy of itself.
*/
class ICloneable
{
public:
ICloneable() {}
virtual ~ICloneable() {}
virtual ICloneable *... |
6,283,632 | 6,283,787 | How to know if the next character is EOF in C++ | I'm need to know if the next char in ifstream is the end of file. I'm trying to do this with .peek():
if (file.peek() == -1)
and
if (file.peek() == file.eof())
But neither works. There's a way to do this?
Edit: What I'm trying to do is to add a letter to the end of each word in a file. In order to do so I ask if the... | istream::peek() returns the constant EOF (which is not guaranteed to be equal to -1) when it detects end-of-file or error. To check robustly for end-of-file, do this:
int c = file.peek();
if (c == EOF) {
if (file.eof())
// end of file
else
// error
} else {
// do something with 'c'
}
You should know tha... |
6,283,657 | 6,284,223 | Return a read-only double pointer | I want to a member variable, which is a double pointer. The object, the double pointer points to shall not be modified from outside the class.
My following try yields an
"invalid conversion from ‘std::string**’ to ‘const std::string**’"
class C{
public:
const std::string **getPrivate(){
return myPrivate;
... | Try this:
const std::string * const *getPrivate(){
return myPrivate;
}
The trouble with const std::string ** is that it allows the caller to modify one of the pointers, which isn't declared as const. This makes both the pointer and the string class itself const.
|
6,284,318 | 6,284,462 | Do any automated conversion tools exist for porting C++ code to 64-bit? | I'm researching methods to port a large (>10M lines) amount of C++ code to 64-bit. I have looked at static code analyzers and compiler flags, and I am now looking at macros or other tools that can make common, repetitive changes.
I've written a few regular expressions to see how well they work in practice, and as predi... | Rexexps suffer from a high false positive rate; by definition, a "regular expression" cannot parse a context free langauge such as C++. Futhermore, regexps cannot take into
account type information; is
fooT i=0;
ok, for some typedef'd fooT? Finally, a regexp cannot change code; you might consider Perl or SED (us... |
6,284,453 | 6,284,477 | C++ dynamically sized static array puzzler | While trying to explain to someone why a C++ static array could not by dynamically sized, I found gcc disagreeing with me. How does the following code even compile, given that the dimension argc of array is not known at compile time?
#include <iostream>
int main(int argc, char* argv[]) {
int array[argc];
for(i... | Variable-length arrays (VLAs) are part of C99 and have been supported by gcc for a long time:
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
Note that the use of VLAs in C90 and C++ code is non-standard, but is supported by gcc as an extension.
|
6,284,507 | 6,284,580 | Aggregate Initialization Safety in C++ | Suppose I have the following struct:
struct sampleData
{
int x;
int y;
};
And when used, I want to initialize variables of sampleData type to a known state.
sampleData sample = { 1, 2 }
Later, I decide that I need additional data stored in my sampleData struct, as follows:
struct sampleData
{
... | Initialising variables that way is only supported with Aggregate Classes.
If you add constructor(s) then then problem goes away, but you'll need to change the syntax a little and you lose the ability to store the struct in a union (among other things).
struct sampleData
{
sampleData(int x, int y) : x(x), y(y) {}
... |
6,284,524 | 6,284,978 | BSTR to std::string (std::wstring) and vice versa | While working with COM in C++ the strings are usually of BSTR data type. Someone can use BSTR wrapper like CComBSTR or MS's CString. But because I can't use ATL or MFC in MinGW compiler, is there standard code snippet to convert BSTR to std::string (or std::wstring) and vice versa?
Are there also some non-MS wrappers ... | BSTR to std::wstring:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring to BSTR:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
std::basic_... |
6,284,720 | 6,284,797 | Undefined reference C++ | I'm trying to compile my first legit program that I'm converting from Java (I ran a test hello world type program to check my compiler and it works).
There are three files:
main.cpp
#include <iostream>
#include "skewNormal.h"
using namespace std;
double getSkewNormal(double, double);
int main(int argc, char **argv) ... | You may be compiling skewNormal.cpp to a .o file, but you're not including it when you compile main.cpp.
|
6,284,940 | 6,285,254 | Downcasting shared pointer to derived class with additional functionality - is this safe? | Consider the following outline:
class Base { /* ... */ };
class Derived : public Base
{
public:
void AdditionalFunctionality(int i){ /* ... */ }
};
typedef std::shared_ptr<Base> pBase;
typedef std::shared_ptr<Derived> pDerived;
int main(void)
{
std::vector<pBase> v;
v.push_back(pBase(new Derived()));
... | Does the Base has a virtual destructor? If yes then it is safe to use downcasting. In your incorrect sample pDerived should be NULL in result, so you need to check the result of dynamic_pointer_cast every time.
|
6,284,959 | 6,285,050 | Monitor Qt GUI from QThread class | I am trying to run a background thread (qthread) that needs to monitor a checkbox in the gui and it will not run! It builds but during runtime i get this error:
"Unhandled exception at 0x0120f494 in program.exe: 0xC0000005: Access violation reading location 0xcdcdce55."
and it breaks on the "connect" line. What is th... | The event queue of any QThread object is actually handled by the thread that started it, which is quite unintuitive. The common solution is to create a "handler" object (derived from QObject), associate it with your worker thread by calling moveToThread, and then bind the checkbox signal to a slot of this object.
T... |
6,285,150 | 6,285,205 | string::insert at end of string | The following two lines do the same thing in Visual Studio 2005:
myString.insert(myString.size(),1,myNewChar);
and
myString.append(1,myNewChar);
Is the first one supposed to throw an out_of_range exception or is this the correct behavior?
| This is correct behavior -- the index you pass is the index of the position behind the point of insertion of the new characters, not before. In fact, the C++03 standard specifically says (§21.3.5.4/2):
Requires pos1 <= size() and pos2 <= str.size()
(where pos1 is the index you're passing and pos2 == npos in the overl... |
6,285,212 | 6,285,282 | Difference between "%include" and "#include" | In SWIG, what is the difference between the "%include" directive, and the standard C "#include"?
For instance, in all the tutorials, why do they typically look something like this:
%module my_module
%{
#include "MyHeader.h"
%}
%include "MyHeader.h"
This seems redundant to me. Perhaps somebody with knowledge can clar... | The stuff in %{ ... %} is passed through directly to the output; it is not itself interpreted by SWIG. So the #include is there to make sure the generated C/C++ code includes that header.
%include, by contrast, is a SWIG directive. It tells SWIG to process that header file before proceeding. This way SWIG will learn... |
6,285,270 | 6,285,501 | How can I get the mouse position in a console program? | How can I get the mouse click position in C++ in a Windows console program? (A variable that returns the position of the mouse when clicked)
I want to draw a menu with simple text commands, so when someone clicks, the game will register it and know the position. I know how to do everything I need to do except get the m... | You'll need to use the *ConsoleInput family of methods (peek, read, etc). These operate on the console's input buffer, which includes keyboard and mouse events. The general strategy is:
wait on the console's input buffer handle (ReadConsoleInput)
determine the number of waiting events (lpNumberOfEventsRead)
handle the... |
6,285,284 | 6,285,343 | Consequences of caching string length in a native C++ class? | So we have a custom string class that just wraps a basic C string: char* or a wchar_t*. The only data member of our custom string class is this pointer. Anyways, here at work we are debating adding another member that caches the length of the internal char array. So instead of
MyString::Count { return _tcslen(foo); }
... | First thing: don't do it unless you have profiling data showing this is really a bottleneck. If you don't have that, you've all been wasting your time arguing about this IMO. Make your code correct first, then attack the important bottlenecks.
If you do cache it, make sure all the paths that could modify the internal s... |
6,285,315 | 6,285,591 | Architectural strategies for avoiding dynamic casts | One often reads how it's worth designing your code to avoid needing to make casts, and how finding yourself needing to cast might suggest that there is a better implementation available. I'm trying to achieve this holy grail of "cast-free code" in the implementation of a virtual world engine, where many objects have a ... | This is a fundamentally flawed proposition. dynamic_cast exists for a reason. Trying to aim for cast-less code is just naive- casts serve a purpose. Sure, it might be the best thing to reduce them wherever you can, but that's very different from trying to ban them. Code without dynamic_cast isn't some kind of holy grai... |
6,285,335 | 6,286,834 | Differentiate between ambiguous member request error and member does not exist error in SFINAE context? | Edit: Posted an answer of my own, kept the original accepted answer... got me thinking about aliases.
Edit: My question is directed at the possibility of differentiating ambiguity vs existence of a member var/func in SFINAE (or other) contexts. My question isn't about how to make a has_member template, it's about dete... | Alright, I think I managed to take the expression SFINAE approach and add type deduction. Here is a very crudely hacked-together answer that appears to be doing something useful (see the usage example at the bottom).
(The presentation could probably made a lot more succinct and clean, but this way you see it broken dow... |
6,285,597 | 6,289,855 | Invalid or Corrupt lib file opencv_core220d.lib | I'm struggling with trying to get OpenCV 2.2 libraries to work with my project (running VSC++, 2010). I followed the instructions at http://opencv.willowgarage.com/wiki/VisualC%2B%2B. When I run my code (sample code from above link) I get the following message...
...\OpenCV-BUILD-2.2\lib\Debug\opencv_core220d.lib :
... | I found the answer on the OpenCV Wiki FAQ
Make sure "c:\Program Files\OpenCV\bin" (or the equivalent for your installation) is included in your PATH variable.
Once I added the bin folder to my path, everything worked fine.
|
6,285,707 | 6,286,349 | Why the ror op in this inline assembly not working properly? | I have written a program to process some data written to disk in big-endian format, so the program needs to swap bytes in order to do anything else. After profiling the code I found that my byte swapping function was taking 30% of the execution time. So I thought to myself, how can I speed this up?
So I decided to writ... | First of all, use
#include <arpa/inet.h>
little_endian = ntohs(big_endian);
This will compile into optimal code on whatever system you are using, and it will even work if you happen to port your code to a big-endian platform.
However, this will not fix your performance problem because I believe you have misidentified ... |
6,285,715 | 6,287,195 | openmp parallel for with non-PODs | I'm trying to speed up a program, in the heart of which is a trivially-looking loop:
double sum=0.;
#pragma omp parallel for reduction(+:sum) // fails
for( size_t i=0; i<_S.size(); ++i ){
sum += _S[i].first* R(atoms,_S[i].second) ;
}
While the looping itself is trivial, the objects inside it are not PODs: Here _S is... | The access to _S[i].first and _S[i].second is perfectly safe (can't guarantee anything about atoms). This means that your function call to R must be what's causing the problem. You need to find out what R is and post what it's doing.
In another point, names which begin with an underscore and begin with an uppercase cha... |
6,286,167 | 6,286,846 | When TinyXML visitor function returns false, why does it stop parsing siblings? | We have adopted Tiny XML as our XML parser. I am writing code to grab palettes out of an XML file, and wrote a visitor function like this:
PALETTE_PARSER::VisitEnter( const TiXmlElement& Element, const TiXmlAttribute* First Attribute)
{
if( Element.ValueStr() == "palette" )
{
AddPalette( Element );
... |
What is the reason for this behavior?
The purpose is to allow you to search a tree of nodes recursively, and stop as soon as you have found whatever it is you are looking for.
I am interested only in the palette elements, but there may be more than one of them (as well as other elements)... So I guess I am looking f... |
6,286,194 | 6,286,212 | Will enabling -msse, -msse2 and -mfpmath=sse always make my program run faster? | I have a C++ program that is doing a lot of math (mostly calls to sin(), sqrt() and so regular operations). I know that in theory enabling -msse, -msse2, and -mfpmath=sse should expose more registers for GCC/G++ to use therefor potentially making my program run faster, in practice will it always do so? In the worst cas... | When worried about performance, you should always profile.
SSE instructions use different CPU resources, so they could cause a decrease in performance (e.g. because those resources are not available for Hyperthreading), but in real life this should be very rare indeed.
|
6,286,276 | 6,286,288 | Conversion from radians to degrees | I am trying to do a simple trigonometric calculation in C++. The following is an example of the problem I am having with this. As far as I know, C++ works in radians, not degrees. So conversion from radians to degrees should be a simple case of multiplying by 180 and dividing by pi. A simple test is tan(45), which shou... | You're doing it backwards. Don't apply the formula to the output of tan, apply it to the parameter.
Also you'll want to multiply by pi and divide by 180, not vice versa.
|
6,286,371 | 6,286,423 | How do you get the remaining string after a string extracted from a sstream variable? | Like I have a stringstream variable contains "abc gg rrr ff"
When I use >> on that stringstream variable, it gives me "abc". How can I get the remaining string: " gg rrr ff"? It seems neither str() nor rdbuf() does this work.
| You can use std::getline to get the rest of the string from the stream:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss("abc gg rrr ff");
string s1, s2;
ss >> s1;
getline(ss, s2); //get rest of the string!
cout << s1 << endl;
cou... |
6,286,400 | 6,286,939 | Can you begin programming OpenCL without downloading an SDK? | I am trying to get a program that will run on both ATI and NVidia, and as such, I want to avoid using either SDK. Is it possible to do this without an SDK, using only VS2010 and Windows (XP or 7)?
If so, how can I go about configuring VS2010 Linker so that it will work?
| Strictly speaking, no SDK is needed. In fact, no SDK is desired, as both the NVIDIA and AMD/ATI SDKs tie the code to their environments, and, by extension, their hardware. What you do need is:
1) A GPU that will run OpenCL code. See this Question: List of OpenCl Compliant CPU/GPU
2) The OpenCL library (libOpenCL.so on ... |
6,286,439 | 6,286,456 | what does the .f in 1000.f mean? c++ | I am following a tutorial on how to make a game with SDL. At a certain point in the tutorial I need to calculate the game's FPS. The tutorial does the following:
caption << "Average Frames Per Second: " << frame / ( fps.get_ticks() / 1000.f );
Now, I know exactly what the code does, except for the part where it divide... | 1000 is an int literal.
1000. is a double literal.
1000.f is a float literal.
|
6,286,444 | 6,286,488 | Using a class from another project in C++ | I have access to a large C++ project, full of files and with a very complicated makefile courtesy of automake & friends
Here is an idea of the directory structure.
otherproject/
folder1/
some_headers.h
some_files.cpp
...
folderN/
more_headers.h
more_files.cpp
build/
lots_of things here
... | Generally the project's .o files should come grouped together into a library (on Linux, .a file if it's a static library, or .so if it's a dynamic library), and you link to the library using the -L option to specify the location and the -l option to specify the library name.
For example, if the library file is at /path... |
6,286,656 | 6,286,720 | Dependencies in Initialization Lists | Is this behavior well-defined?
class Foo
{
int A, B;
public:
Foo(int Bar): B(Bar), A(B + 123)
{
}
};
int main()
{
Foo MyFoo(0);
return 0;
}
| No, it's undefined. A will be initialized first (it's first in the class definition), and it uses uninitialized B.
Class members are initialized in the order they appear in the class definition, irrespective of their order in the initialization list. Indeed, it is bad practice to mismatch the member definition order wi... |
6,287,019 | 6,287,026 | ! meaning in c++ (following context) | I know what != is when if(x!=value){...}, but what does it mean in the following context:
if (! ReadConsoleInput(
hStdin, // input buffer handle
irInBuf, // buffer to read into
128, // size of read buffer
&cNumRead) ) // number of records... | It's the "Not" operator: true (1) if the operand is zero, false (0) otherwise.
|
6,287,186 | 6,287,203 | How can a subclass call a method of the superclass with the same method name of the subclass? | #include <iostream>
using namespace std;
class Person {
public:
void sing();
};
class Child : public Person {
public:
void sing();
};
Person::sing() {
cout << "Raindrops keep falling on my head..." << endl;
}
Child::sing() {
cout << "London bridge is falling down..." << endl;
}
int main() {
Chi... | suzie.Person::sing();
|
6,287,395 | 6,287,522 | Prevent two object internals from aliasing | I have a function signature similiar to this
void Mutliply(const MatrixMN& a, const MatrixMN& b, MatrixMN& out);
Internally the matrix class has a float* data; that represents the m x n components. I'd like to tell the compiler that a and b do not alias the out matrix so it doesn't do a ton of load-stores.
How would I... | Write a non-exported (file-static, private) multiplication function that takesfloat* arguments, mark the arguments with restrict. Make Multiply call this function.
|
6,287,523 | 6,287,589 | Using Core Audio to extract float from default line out sound device | I am in need for some assistance/guidance with using Core Audio to extract floats from the sound out device. I have read similar posts regarding the extraction of floats from AIFF. My end goal is something along the lines of:
iTunes is playing a song
C/C++ program using Core Audio
extracts float values from the sound
... | This question comes up frequently on the Core Audio mailing list. There is no easy way to accomplish what you want to do. See:
http://lists.apple.com/archives/coreaudio-api/2007/Jul/msg00066.html
http://lists.apple.com/archives/coreaudio-api/2009/Nov/msg00308.html
You'll need to write either a kext or a user-land dri... |
6,287,541 | 6,287,950 | Bounding box frustum rendering - Distance rendering - OpenGL | I am rendering an old game format where I have a list of meshes that make up the are you are in. I have finally gotten the PVS (regions visible from another region) working and that cuts out a lot of the meshes I don't need to render but not by much. So now, my list of meshes I should render only includes the other mes... | AABB or Axis Aligned Bounding Box is a very simple and fast object for testing intersection/containment of two 3D regions.
As you suggest, you are calculating a min and max x,y,z for the two regions you want to compare, for example, the region that describes a frustum and the region that describes a mesh. It is axis al... |
6,287,593 | 6,288,044 | FIR filtering using window function: implementation problem | I want to make a FIR filter using a window function. I have some sample data and size variable is a count of samples. The windowSize variable is a size of the window function.
At first I create the window function (blackman window): the variable window
Then I need to multiply it by sin(x) / x function and convolve wit... | The sin(x)/x filter is a lowpass filter. That is, it suppresses all frequencies above a certain cutoff frequency.
If the sampling frequency is Fs (Hertz) and you want a cutoff frequency of fc (Hertz), You should be using x = 2*PI*fc/(2*Fs)*n where n goes from -N to +N and N is large enough that the sin(x)/x function i... |
6,287,796 | 6,288,324 | QImage (or images generally) conversion to 3 1D arrays for RGB | A function that I am trying to conform to requires three 1-Dimensional arrays of type double[19200]. The following arrays are RGB arrays such that:
double r[19200]; // r
double g[19200]; // g
double b[19200]; // b
So far, I can extract pixel information from a QImage and populate the above arrays.
The problem is wi... | I don't really understand why you're having a problem if you managed to do it one way. The process is essentially the same:
for (int x=0; x<w; x++)
for (int y=0; y<h; y++)
image.setPixel(x,y, convertToRGB(r[x*w+y], ...);
Where convertToRGB is the inverse transform of what you to to convert and RGB value to your... |
6,287,841 | 6,288,435 | exporting symbols in a dynamic qt library | I'm trying to create a dynamic library using Qt on OS X 10.6.7 and Qt 4.7.3. I have created the most basic test I can think of (see below or https://gist.github.com/1016045) and yet
otool -T build/libstackoverflow.dylib
still reports
build/libstackoverflow.dylib:
Table of contents (0 entries)
module index symbol inde... | I don't think just exporting will disable C++ name mangling. If you have "plain C" functions you want to export without mangling, you'll need to wrap their declaration in an extern "C" {} block (in a header preferably of course).
Name mangling doesn't prevent successful linking, as long as the "client" code is also com... |
6,288,193 | 6,288,219 | Forcing a function to only accept a certain set of data types | is there any way to force functions to only take in vectors of integers (int, unsigned int, uint32_t, etc.) and only those? im trying to write a simple function that returns the sum of all the values with the same return type (since i cant be sure whether or not the value will be greater than (2^32 - 1). however, since... | SFINAE to the rescue.
#include <type_traits>
//#include <tr1/type_traits> // for C++03, use std::tr1::
template<bool, class T = void>
struct enable_if{};
template<class T>
struct enable_if<true,T>{
typedef T type;
};
template<class T>
typename enable_if<
std::is_arithmetic<T>::value,
T
>::type sum(std::vec... |
6,288,285 | 6,289,260 | What is the Python counterpart to an Ada record / C++ struct type? | Suppose I am recording data and want to associate some number of data elements, such that each recorded set always has a fixed composition, i.e. no missing fields.
Most of my experience as a programmer is with Ada or C/C++ variants. In Ada, I would use a record type and aggregate assignment, so that when the record ... | A namedtuple (from the collections library) may suit your purposes. It is basically a tuple which allows reference to fields by name as well as index position. So it's a fixed structure of ordered named fields. It's also lightweight in that it uses slots to define field names thus eliminating the need to carry a dictio... |
6,288,387 | 6,288,874 | Using 'new' to allocate memory dynamically in C++? | I am working on some C++ code and am having some problems with the function described below. I haven't used much C++ before, at least not for a long time and so i'm trying to learn as I go along to a large extent. The win32api doesn't help much with the confusion factor either...
The function is succesfully called twic... | I tried sanitizing your code a bit. One of the big tricks to C++ is to not explicitly use memory management when it can be avoided. Use vectors instead of raw arrays. Strings instead of char pointers.
And don't unnecessarily allocate objects dynamically. Put them on the stack, where they're automatically freed.
And, as... |
6,288,436 | 6,288,469 | Undefined reference of header variable in Qt C++ | I am having a problem with my program where in I declared the variable from a header file and execute it on a CPP file. I am getting an error which is the undefined reference to the variable.
here a sample code of my project:
CPP FILE
#include "function.h"
CClass::CClass() : m_Db(HOST,USER,PASSWORD,DATABASE)
{
...
}... | This line in your header file:
extern CCrypt *c_crypting;
does not create a c_crypting pointer. It only says "one of my code modules will have a pointer to CCrypt that is called c_crypting" so that the other code files can use that. You'll need to have something like:
CCrypt *c_crypting; // possibly '= 0;'
in one of ... |
6,288,518 | 6,288,681 | Is there a list of which compiler supports which part of the C++ standard? | I'm just confused about c++'s standards right now,
I know there is three versions right now: c++98, c++03 and c++0x;
It is said that VC6 was wrote before C++ was standardized, so I don't mind if it does not support the standards, BUT, I found that vs2010 can't even support C++03, here is the code:
class A
{
class B... | It seems you're specifically interested in MS VC++ versions... see http://msdn.microsoft.com/en-us/library/x84h5b78.aspx - vary the version number in the "Other Versions" drop-down combobox to see the various releases.
|
6,288,750 | 6,291,922 | Box2d anti-gravity question | im using cocos2d with box2d.
Currently im trying to optimize a system that i have installed to make certain objects have 0 gravity.
In my tick method, if an objects property object.isGravitated = NO, an anti-gravity method will be called to use object.body->applyForce(b2Vec2(0,10)); to counteract the downward force. B... | You could modify b2body directly, for it to contain a gravity factor. By default, set it to 1.0f, which means normal gravity. Set it to 0.0f for no gravity.
Gravity is calculated using b2Island, so in b2Island.cpp look for the line (it's in the Solve method):
b->m_linearVelocity += step.dt * (gravity + b->m_invMass * b... |
6,288,787 | 6,288,830 | How to detect a tab in a text file? | Is detecting tabs same as detecting the spaces? i.e. for detecting a space, I would just compare the space character with its ascii number.
For a tab do I have to search for '\t' character in the file or there is some other way?
| Assuming you are working with ASCII data, you can just search for a byte with value '\t' (9) in the text file. Tabs are represented as a single byte in text files and most libraries for reading files don't do anything special with those bytes.
|
6,288,791 | 8,830,148 | Why does wxWidgets not leak Frames? | I'm trying to learn wxWidgets, but I'm stuck on a point which I can't find an explanation for anywhere in the documentation. I am trying to understand this minimal wxWidgets program:
#include <wx/wx.h>
class MyApp : public wxApp
{
virtual bool OnInit();
};
IMPLEMENT_APP(MyApp)
bool MyApp::OnInit()
{
wxFrame ... | Cleanup is discussed here: http://docs.wxwidgets.org/2.9.2/overview_windowdeletion.html
|
6,288,812 | 6,288,840 | What is the meaning of template<> with empty angle brackets in C++? | template<>
class A{
//some class data
};
I have seen this kind of code many times.
what is the use of template<> in the above code?
And what are the cases where we need mandate the use of it?
| template<> tells the compiler that a template specialization follows, specifically a full specialization. Normally, class A would have to look something like this:
template<class T>
class A{
// general implementation
};
template<>
class A<int>{
// special implementation for ints
};
Now, whenever A<int> is used, t... |
6,288,895 | 6,296,958 | How to compile a cpp to a dll in visual studio 2010 express | I have a cpp which depends on couple of headers in the same folder. I need to compile this cpp to a dll. How do I do it in visual studio 2010 expresS?
I found few articles on web for visual studio 2008 but I could not use it in 2010. Any pointers would be highly appreciated. Btw, I am a java programmer. CPP is all new ... | Right-click on your project in the Solution Explorer, and select Properties.... Under Configuration Properties -> General there's an option called Configuration Type. If you change it to Dynamic Library (.dll), your project will generate a DLL when it is built.
|
6,289,052 | 6,289,780 | How come my execution result is correct, but watch list result is wrong? | I wrote a c++ program, and when I'm using debug mode,
I put a pointer type variable (say m_pdummy) into the watch list, but it shows "bad ptr";
If I expand this pointer(by clicking the "+" left to the name) and wants to see other variables under this pointer, all variables show "expression cannot be evaluated";
Howeve... | Maybe the code you are debugging with is not exactly the one running, or the VS Compiler optimize your code so some of the code doesn't exist anymore.
In the case of the former, the breakpoint and debug value cannot be watched, you should check out the code match the debugging one. I come up with this when I regist... |
6,289,090 | 6,289,131 | Creating threads that work with dialog boxes | I need to make a thread using AfxBeginThread in a MFC application that uses some dialog boxes, but because the thread function is inside a class I have to make it static, and then I can't use any controls because they are not static, and even if I make them static I get some linker errors.
Can someone tell me how its... | The thread function is supposed to receive a parameter that you pass to AfxBeginThread as pParam, and you can pass there the pointer to your class, and from the thread function call whatever class member function you want. That's how I do it.
Something like this (pseudo code):
CWinThread* thread = AfxBeginThread(
My... |
6,289,196 | 6,289,255 | Window message: Different between WM_CREATE and WM_NCCREATE? | I tried to create button (child window) inside WM_NCCREATE message, and its position seemed to be created respected to screen coordinates, rather than client coordinates. At first, I thought WM_CREATE and WM_NCCREATE provide us the same handle to window, but this seem to be untrue. Therefore, can anyone explain me the ... | Per MSDN:
WM_NCCREATE:
Sent prior to the WM_CREATE message
when a window is first created.
Return Value:
If an application processes this
message, it should return TRUE to
continue creation of the window. If
the application returns FALSE, the
CreateWindow or CreateWindowEx
function will return a NULL han... |
6,289,424 | 6,289,466 | Zipping a file from memory in linux | I'm working on application that must enrypt and zip files. So, I create some data in memory (text, binary or whatever), encrypt it and save to disk (file1 and file2). The I call e.g. "zip out.zip file1 file2 ".
I do not want to save this files to disk, but immediately create zip and pack these files from memory.
How sh... | You could try to use the zlib library to be able to create zip files from memory buffers.
The boost:iostreams could also be a good solution.
|
6,289,513 | 6,290,975 | Where Is color_map defined in BGL? | Example code from BGL:
breadth_first_search(g, vertex(s, g), color_map(get(&VertexProps::color, g)).visitor(vis));
What is color_map, where is it defined? And where is it documented?
| It's defined as a named parameter in http://www.boost.org/doc/libs/1_46_0/boost/graph/named_function_params.hpp
|
6,289,573 | 6,290,280 | Boost.Filesystem crashes | Does anyone had this problem ? When searching a partition with recursive_directory_iterator, when it reaches the end it crashes.
I get this in Visual Studio 2008 with boost 1.39 but also at home using MinGW with boost 1.46. I don't think I am doing something wrong:
#include "stdafx.h"
#include <iostream>
#include <boos... | Windows does not allow you to look inside the directory "System Volume Information".
So unleashing a recursive_directory_iterator on "System Volume Information" is a bad idea.
Edit: You may be able to solve the problem with recursive_directory_iterator::no_push(). From The Boost docs:
void no_push(bool value=true);
... |
6,289,623 | 6,297,354 | Using SQLite custom functions with Qt | I'm trying to create a custom function for a SQLite database I'm using with Qt. I found information on how to create the function and it seems to work correctly on a x86 system.
Instead, it seems to be failing with a segfault on an ARM device. This is the code I wrote:
static bool createSQLiteFunctions(const QSqlDataba... | If it's failing on ARM, it may have to do something with compilation (what sqlite3 are you using?) or with the callback function itself (_sqlite3DeleteFile). How is it defined, where is it located / linked. Depending on the ARM (what ARM are you using) the processor can be very picky with alignment.
Check your map fil... |
6,289,668 | 6,342,943 | programs paralyzing each other on the server (c++ with openMP and python) | I have an urgent problem because my time is running out: I let my calculations process on a server with 8 cores therefore I'm using openMP in my c++ code and it works fine. Of course I'm not the only one who is using the server, so my capacity is not always 800%CPU.
But it happened now several times that someone who s... | As Emil Vikström listed, there are several reasons which can cause such a paralysis. I could fix the problem by enabling dynamic adjustment of the number of threads available:
omp_set_dynamic(1);
I assumed that it's on by default. It is not.
|
6,289,947 | 6,289,960 | Is memcpy() safe when copy some content larger than dst? | Is it safe when the request_token.size() is larger than LEN?
char dst[LEN];
memcpy(dst, request_token.c_str(), request_token.size());
| No, it's not safe; you'll cause a buffer overflow. The reason is, memcpy has no way to know the size of your target buffer, other than the size you pass in the third argument.
|
6,289,970 | 6,290,333 | failed to execute this c++ code on android | i am trying to call native opengl methods from java. Everything compiles ok but i still get this horrible error in android log cat
ERROR/AndroidRuntime(536): java.lang.UnsatisfiedLinkError:init
at com.deo.Glut.Init(Native Method)
according to oracle
UnsatisfiedLinkError is Thrown if the
Ja... | Because your file is a cpp file, you will need extern "C" { } around your exported functions. Otherwise the compiler will mangle the function names and Java won't find the ones it's looking for.
|
6,290,172 | 6,290,201 | Qt smart pointer equivalent to Boost::shared_ptr ? | I have used Boost::shared_ptr in my previous projects and now I want to find a smart-pointer in Qt which does the same/similar thing.
Since there are many smart-pointer classes in Qt I was wondering which one to use.
Is it QSharedPointer?
| You want QSharedPointer. You'll find a comparison of all the pointer classes offered by Qt in the detailed description of QSharedPointer.
|
6,290,460 | 6,291,283 | if/else statement in SSE intrinsics | I am trying to optimize a small piece of code with SSE intrinsics (I am a complete beginner on the topic), but I am a little stuck on the use of conditionals.
My original code is:
unsigned long c;
unsigned long constant = 0x12345678;
unsigned long table[256];
int n, k;
for( n = 0; n < 256; n++ )
{
c = n;
for( k = ... | You can get rid of the if/else entirely. Back in the days when I produced MMX assembly code, that was a common programming activity. Let me start with a series of transformations on the "false" statement:
c >>= 1;
c = c >> 1;
c = 0 ^ (c >> 1);
Why did I introduce the exclusive-or? Because exclusive-or is also found ... |
6,290,653 | 7,666,353 | Can I serialize/deserialize JSON from protocol buffers with C++? | There are frameworks for Java and other languages that help connect protocol buffers to JSON, but I have not seen a native solution in C++.
Is there a library/framework that I can use to connect C++ protocol buffer objects to JSON?
| I'm developing one. I'm using the protobuf's reflection mechanism to parse any generated protobuf. Here http://corbasim.googlecode.com/svn/trunk/protobuf2json_exported.zip you can find an initial implementation of this idea. It currently just parse string fields, but I want to support any type as soon as possible.
For ... |
6,290,704 | 6,290,735 | Accessing a array of Structs using pointer notation | I am trying to learn C++ on my own and was trying out this. I have a struct one of whose member is an array of another structs. I have a question about alternative notation.
The structs that I have defined are
struct employeeRecordT {
string name;
string title;
string ssnum;
double salary;
int with... | (payroll.array+i)->name = "Vikas";
array is a member of payroll, so when you were doing payroll.(array+i), the bracket notation (i.e. "do this first") was trying to use a variable array, and not the one within the scope of payroll.
Of course, using C++, the better solution is Neils. Use a std::vector instead of your o... |
6,291,008 | 6,291,076 | Can you please help explain this code? | I have this function that I'm trying to convert but I just cant understand what is happening in some parts of the code. Could anyone please help me out and explain the code. I just want to know what they do with the pointers. There are some blank comments in the code where they do hell with the pointers, i just dont ge... | int count = *pPixels++;
Dereferences the pPixels pointer to get the value and assigns it to count and increment the pointer - this will make the pointer to point to the next element in the array (m_Pixels)
index += *pPixels++;
Increment index with the value, pointed by pPixels and increment the pointer - this will m... |
6,291,093 | 6,291,122 | C++ Compiler Implementing Namespace | From the C++ compiler's point of view, is namespace just a name decoration convention? I have inspected the generated assembly listing and found that everything just looks the same except the identifiers are decorated by the namespace's name.
| As you point out, name mangling is part of the story (but the reasons for doing it have more to do with linkers rather than compilers).
However, name mangling is far from the whole story as far as the handling of namespaces in the compiler is concerned. Among other things, the compiler has to be able to figure out unqu... |
6,291,134 | 6,291,154 | C++ Crash Dumps on POSIX | I have a big C++ code (server for some application).
This application is big, and catch a crash per 2 months in average.
And i can't simulate this crash to catch her with gdb.
Is exists some cool api to analyze memory on crash dump (stacktrace, local vars)?
What is best way to catch stack corruption time?
| Enable core dumping, wait for it to crash. Then load the core into gdb and debug as usual.
ulimit -c unlimited
|
6,291,350 | 6,291,520 | Decorator design pattern, function bug | This is homework...I'm not asking for answers, I just have a bug I'm not sure what to do with. Thanks!
The bug in question probably has nothing to do with the assignment itself, but here is the assignment description anyways:
I'm working on an assignment (in C++) meant to teach use of the decorator design pattern thro... | Do you have currentPizza also declared as an field of the Pizza class and you are using that somewhere else? If so, the currentPizza you are updating in newPizza is specific to that method, and you need to do just currentPizza = new Plain(); instead of declaring a new currentPizza variable in the scope of the method.
... |
6,291,458 | 6,291,495 | How to convert a TCHAR array to std::string? | How do I convert a TCHAR array to std::string (not to std::basic_string)?
| TCHAR is just a typedef that, depending on your compilation configuration, either defaults to char or wchar_t.
Standard Template Library supports both ASCII (with std::string) and wide character sets (with std::wstring). All you need to do is to typedef String as either std::string or std::wstring depending on your co... |
6,291,533 | 6,357,770 | How to obtain iframe html document in NPAPI | I am trying to obtain the document inside a frame.
The following does not fail:
NPN_GetProperty(aInstance, windowObject, NPN_GetStringIdentifier("frames"), &frames))
but the following fails, returning a null element:
NPN_Invoke(aInstance, NPVARIANT_TO_OBJECT(frames), NPN_GetStringIdentifier("item"), &index, 1, &curre... | Finaly , i've figured out why contentWindow was returning a void element.
Here's the code for obtaining an iframe document :
STRINGZ_TO_NPVARIANT("IFRAME", searchString);
NPN_Invoke(instanceNPP,NPVARIANT_TO_OBJECT(document), NPN_GetStringIdentifier("getElementsByTagName"), &searchString, 1, &frameCollection);
if (!NP... |
6,291,749 | 6,291,773 | Reference functions in C++ | I have a function that gives me the error "cannot convert from 'int' to 'int &'" when I try to compile it.
int& preinc(int& x) {
return x++;
}
If I replace x++ with x, it will compile, but I'm not sure how that makes it any different. I thought that x++ returns x before it increments x, so shouldn't "return x++" ... | x++ creates a temporary copy of the original, increments the original, and then returns the temporary.
Because your function returns a reference, you are trying to return a reference to the temporary copy, which is local to the function and therefore not valid.
|
6,292,018 | 6,292,078 | Using EOF Function as a Condition | I am trying to import data from a file in my project but I am having trouble finding EOF. Firstly, I used the EOF function as a condition but I after reading this, I tried changed the code but still it is giving same error. Please help me out.
Thanks
#include <iostream>
#include <string>
#include <fstream>
using namesp... | It seems you have one or two syntax problems:
you've got code outside of a function or main (the while and infile commands) they need to be put into main or a function.
your second while needs a do (do{....}while(1), also it runs forever
All your variables are defined outside of main. This makes them global variables... |
6,292,097 | 6,292,644 | NSButton event handling in C++ | I'm creating a thin layer of C++ on top of Cocoa widgets and there's a problem of handling NSButton events without ObjC object as a target.
Any ideas how could I use c++ class methods to handle button click?
For example:
[button setTarget:cppObj];
[button setAction:@(cppObjMethod:)]
The code above doesn't work, of cou... | You would need to set the target and action to an Objective-c class / method which itself calls the C++ code.
|
6,292,178 | 12,719,899 | Custom IDL generation with JACORB maven compiler | I need to integrate Java system with legacy C++ system. Those two system communicate through CORBA.
Since Java system runs on JBoss we use JacORB.
To generate java stubs from .idl files we use maven-idl-compiler plugin (using JacORB)
org.codehaus.mojo
idlj-maven-plugin
org.jacorb
ja... |
Everything works fine but I would like to modify the way stubs are being generates (changes names of methods,classes etc). Is there any way to do it?
This is not possible.
The Server Skeleton and the Client Stub are generated by Corba in the implementation you have chosen. They basically contains Marshaller and Unm... |
6,292,179 | 6,292,200 | VARIANT type punkVal gives undefined values? | I am using few CComVariant type variables to store interface pointers.However, sometime I need to pass interface pointer as NULL.In this case when I do this:
CComVariant vAData,vBData;
......
....
CComQIPtr<IBData> pAData = vAData.punkVal; //vAData is {0, VT_I4} when I pass NULL
CComQIPtr<IBData>pBData = vBData.pun... | CComVariant calls VariantInit() in constructor and that sets vt to VT_EMPTY, but leaves punkVal uninitialized (doesn't make it null).
What you try to do is therefore undefined behavior since you try to construct a CComQIPtr passing it an uninitialized pointer.
If you want a CComVariant holding a null IUnknown* you can ... |
6,292,332 | 6,292,437 | What really is a deque in STL? | I was looking at STL containers and trying to figure what they really are (i.e. the data structure used), and the deque stopped me: I thought at first that it was a double linked list, which would allow insertion and deletion from both ends in constant time, but I am troubled by the promise made by the operator [] to b... | A deque is somewhat recursively defined: internally it maintains a double-ended queue of chunks of fixed size. Each chunk is a vector, and the queue (“map” in the graphic below) of chunks itself is also a vector.
There’s a great analysis of the performance characteristics and how it compares to the vector over at Code... |
6,292,553 | 6,292,602 | c++: new multi dimensional array of strings |
Possible Duplicate:
C++ multi dimensional array
I'm trying to create a class that creates an arbitrary sized array of strings based on one of the objects constructor arguments.
Here, the code for the object constructor I'm trying so far:
commandSpec::commandSpec(int numberOfCommands)
{
std::string * commands = n... | This should probably be implemented as a structure and a vector, like this:
struct command {
std::string first;
std::string second;
std::string third;
};
commandSpec::commandSpec(int numberOfCommands)
{
std::vector<command> commands(numberOfCommands);
}
Of course, you should choose appropriate names f... |
6,292,759 | 6,292,784 | What is currently most widely used set collection in C++ | I'm searching for a set container in C++. I want something where I could add elements but they would not repeat more than once and search in that collection would be O(1). What is current defacto cross-compiler container for this now.
I seen some in boost (like mpl) and there is one in future c++ standards, but what i... | You can use std::unordered_set if you have a C++0x compliant compiler that supports it.
If you are not in that situation, intercepts are available in Microsoft VC++ as stdext::hash_set, or in general using boost::unordered_set. The latter is your best bet for portability at present, pending wider C++0x availability.... |
6,292,766 | 6,292,815 | A generic set operations class i.e. intersection, union, minus etc | I want to write a C++ class that offers set operations that work on vectors of strings and vectors of my own data type. Are there any easy ways of doing this rather than writing a different function for each data type? So far I have written operations for string vectors. Below shows an example of my set union:
vecto... | There are already such algorithms (union, intersection, sorting, ...): http://www.cplusplus.com/reference/algorithm/
Your elements simply need to meet the requirements for STL container elements (see http://msdn.microsoft.com/fr-fr/library/bb385469.aspx):
All reference types that are inserted
into STL/CLR containers... |
6,293,021 | 6,293,466 | Android NDK: gnustl_static library documentation? | I'm a Java developer by trade and my exposure to C++ / JNI has been limited until now.
I've managed to do pretty well so far but now that I'm venturing into doing "Clever" things I'm becoming more and more limited by flying blind:
I'm using the gnustl_static library because of other code which I've ported in the same n... | gnustl_static is GNU stdlibc++ as it comes with gcc. It's official documentation is here, but it's probably useless as tutorial, so preferably get some decent book on C++.
The library does not appear to be cut down. It may look like that to you because standard C++ library defined in the specification is simply lot sma... |
6,293,075 | 6,293,154 | Is C++11 (C++0x) a complete super set of C++03? | C++ considered (almost) super set of C; but still there are certain things which works in C and not in C++.
Is there any feature/facility which is a valid C++03 but not working in C++11 ?
|
Is there any feature/facility which is
a valid C++03 but not working in C++11
?
There are few incompabilities :
export template is removed (not deprecated, really removed)
you can't use auto as storage specifier anymore
there are new reserved words : alignof, char16_t, char32_t, constexpr, decltype, noexcept, nu... |
6,293,158 | 6,293,187 | one c++ syntax question | Sorry if the question is silly. I come from java background.
In the following code, base_list is a parent class of SqlAloc, but what's the meaning of public memory?
class base_list :public memory::SqlAlloc
{
protected:
list_node *first,**last;
uint32_t elements;
public:
};
| Memory is probably a namespace (kind of like an outer class) in which SqlAlloc is defined.
C++ has both public and private inheritance (protected, too, actually.) public inheritance is just like Java inheritance; in private inheritance, though, code outside the derived class doesn't know about the base class. It's a wa... |
6,293,362 | 6,293,547 | Basic development on the Gnome platform | I'm trying to write a C++ application on Gnome/Ubuntu as my first non-academic exercise in programming and I'm having trouble getting started with it. I can't find any information on the different header files I need to include in order to access the functions in the Gnome API. I've looked around the Gnome developer si... | You can find all documentation and tutorials at developer.gnome.org.
Additionally you can use pkg-config tool which will tell you include and library paths. For Gnome Keyring it gives the following:
user@home:~$ pkg-config gnome-keyring-1 --libs
-L/usr/lib/i386-linux-gnu -lgnome-keyring -lglib-2.0
user@home:~$ pkg-c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.