question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,859,499 | 1,859,643 | Using C++, how do I read a string of a specific length, from a non-binary file? | The cplusplus.com example for reading text files shows that a line can be read using the getline function. However, I don't want to get an entire line; I want to get only a certain number of characters. How can this be done in a way that preserves character encoding?
I need a function that does something like this:
ifs... | I really suspect that there's some confusion here regarding the term "character." Judging from the OP's question, he is using the term "character" to refer to a char (as opposed to a logical "character", like a multi-byte UTF-8 character), and thus for the purpose of reading from a text-file the term "character" is in... |
1,859,614 | 1,859,657 | A bot to Access data on grid of a windows application (like a human) | I'm so desperate to use a vpn application. In this app there are some limitations that I've found no solutions for them for example multiple users can connect to the vpn server using one username at the same time. In order to stop that I have to look at the 'connected vpn clients' and see if a username exists more than... | Any solution which reads the GUI will leave connections open for a short amount of time, and be brittle against changes in the GUI, you will be better off asking Kerio support or serverfault if there is any proper, integrated way to achieve what you want.
It can be done, although C++ is probably the wrong choice, pytho... |
1,859,788 | 1,859,810 | Compiling a gnu program without sse3 | I'm compiling an app for a device where the architecture does not support sse beyond sse2, and was wondering is it possible to disable compiling with sse3 instructions from GNU autoconf generated configure scripts? I know you can turn it off in gcc/g++ with mno-sse3 option, but it would be nice if I could turn it off a... | Sure. Just set the required flags before calling configure:
$ CFLAGS="-mtune i386" ./configure --enable-this --disable-that ...
You might want to try -march if -mtune does the wrong thing, I haven't tested this lately.
|
1,860,065 | 1,860,080 | Problem with operator == | I am facing some problem with use of operator == in the following c++ program.
#include < iostream>
using namespace std;
class A
{
public:
A(char *b)
{
a = b;
}
A(A &c)
{
a = c.a;
}
bool operator ==(A &other)
{
retu... | bool operator ==( const A &other)
Use const reference, so a temporary object that is constructed in if statement can be used as parameter for operator==.
|
1,860,187 | 1,860,275 | How do I read binary C++ protobuf data using Python protobuf? | The Python version of Google protobuf gives us only:
SerializeAsString()
Where as the C++ version gives us both:
SerializeToArray(...)
SerializeAsString()
We're writing to our C++ file in binary format, and we'd like to keep it this way. That said, is there a way of reading the binary data into Python and parsing it ... | I'm not an expert with Python, but you can pass the result of a file.read() operation into message.ParseFromString(...) without having to build a new string type or anything.
|
1,860,404 | 1,860,431 | A C++ library for Arrays, Matrix, Vector, and classical linear algebra operations | Which library do you use for N-dimensional arrays?
I use blitz++ at work and I really dislike some aspect of it.
Some aspect of it are even dangerous. The need for resizing before
using operator=. A(Range::all(), Range::all()) throws for an (0,0)
matrix, etc. and the linear algebra operations are to be
done via clapac... | boost::array and also boost::MultiArray. There's also a pretty good linear algebra package in boost called uBLAS
|
1,860,461 | 1,860,704 | Why is `i = ++i + 1` unspecified behavior? | Consider the following C++ Standard ISO/IEC 14882:2003(E) citation (section 5, paragraph 4):
Except where noted, the order of
evaluation of operands of individual
operators and subexpressions of individual
expressions, and the order in
which side effects take place, is
unspecified. 53) Between the previous
... | You make the mistake of thinking of operator= as a two-argument function, where the side effects of the arguments must be completely evaluated before the function begins. If that were the case, then the expression i = ++i + 1 would have multiple sequence points, and ++i would be fully evaluated before the assignment be... |
1,860,615 | 1,860,953 | Code with undefined behavior in C# | In C++ there are a lot of ways that you can write code that compiles, but yields undefined behavior (Wikipedia). Is there something similar in C#? Can we write code in C# that compiles, but has undefined behavior?
| As others have mentioned, pretty much anything in the "unsafe" block can yield implementation-defined behaviour; abuse of unsafe blocks allows you to change the bytes of code that make up the runtime itself, and therefore all bets are off.
The division int.MinValue/-1 has an implementation-defined behaviour.
Throwing ... |
1,860,705 | 1,860,726 | On declarative programming in C++ | Often I face the problem of mapping the parameter space of one API onto the parameter space of another one. Often I see this solved by nested nested nested ... switch statements.
And I was wondering if there would happen to be a library or a technique that allows you to 'declare' the mapping instead of 'program' it.
A... | You can use Boost.Bimap, which provides a bidirectional mapping between two types.
It has a bit of runtime overhead (generally, roughly the same amount of overhead you would get by using a pair of std::maps for this purpose, which isn't a whole lot).
It does allow you to define mappings about as densely as your example... |
1,860,783 | 1,860,807 | strange double to int conversion behavior in c++ | The following program shows the weird double to int conversion behavior I'm seeing in c++:
#include <stdlib.h>
#include <stdio.h>
int main() {
double d = 33222.221;
printf("d = %9.9g\n",d);
d *= 1000;
int i = (int)d;
printf("d = %9.9g | i = %d\n",d,i);
return 0;
}
When I compile and run the program, I ... | Floating point representation is almost never precise (only in special cases). Every programmer should read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic
In short - your number is probably 33222220.99999999999999999999999999999999999999999999999999999999999999998 (or something like tha... |
1,860,796 | 1,860,862 | Your thoughts on "Large Scale C++ Software Design" | Reading the reviews at Amazon and ACCU suggests that John Lakos' book, Large-Scale C++ Software Design may be the Rosetta Stone for modularization.
At the same time, the book seems to be really rare: not many have ever read it, and no pirate electronic copies are floating around.
So, what do you think?
| I've read it, and consider it a very useful book on some practical issues with large C++ projects. If you have already read a lot about C++, and know a bit about physical design and its implications, you may not find that much which is terribly "new" in this book.
On the other hand, if your build takes 4 hours, and yo... |
1,860,955 | 1,862,211 | Why does 'unspecified_bool' for classes which have intrinsic conversions to their wrappered type fail? | I have recently read the safe bool idiom article. I had seen this technique used a few times, but had never understood quite why it works, or exactly why it was necessary (probably like many, I get the gist of it: simply using operator bool () const allowed some implicit type conversion shenanigans, but the details we... | AutoHandleTemplate<ModuleHandlePolicy> hModule( ... );
HMODULE raw_handle = hModule; // if we want to this line works,
// AutoHandleTemplate<ModuleHandlePolicy> should \
// be implicitly converted to it's raw handle type - HMODULE.
If one smart-ptr can implicitly converted to it's raw handle type and the raw handle... |
1,861,294 | 1,861,337 | How to Calculate Execution Time of a Code Snippet in C++ | I have to compute execution time of a C++ code snippet in seconds. It must be working either on Windows or Unix machines.
I use code the following code to do this. (import before)
clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (dou... | You can use this function I wrote. You call GetTimeMs64(), and it returns the number of milliseconds elapsed since the unix epoch using the system clock - the just like time(NULL), except in milliseconds.
It works on both windows and linux; it is thread safe.
Note that the granularity is 15 ms on windows; on linux it i... |
1,861,506 | 1,862,286 | Prevent Modal Dialog on win32 process crash | We have a legacy build infrastructure for nightly builds (implemented in Perl) to compile, link and unit tests our applications/plugins. On Windows, if the unit testing process crashes, this pops up a Modal Dialog which "locks" our build farm.
Is there a way (win32 API call, system config, env var, something...) to dis... | Depending on who's throwing the dialog, you may have to combine multiple approaches.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
...will shut up one set of dialogs.
|
1,861,541 | 1,861,574 | Array of char or std::string for a public library? | my question is simple:
Should I use array of char eg:
char *buf, buf2[MAX_STRING_LENGTH]
etc or should I use std::string in a library that will be used by other programmers where they can use it on any SO and compiler of their choice?
Considering performance and portability...
from my point of view, std str... | Depends on how this library will be used in conjunction with client code. If it will be linked in dynamically and you have a set of APIs exposed for the client -- you are better off using null terminated byte strings (i.e. char *) and their wide-character counterparts. If you are talking about using them within your co... |
1,861,568 | 1,861,595 | .c_str() weirdness? Data changes without rhyme or reason? | I have this simple function:
const wchar_t *StringManager::GetWCharTStar(int stringId)
{
std::wstring originalString = StringManager::GetString(stringId);
const wchar_t *retStr = originalString.c_str();
return retStr;
}
At the second line of that function, I have the correct wchar_t*. However, when I go t... | originalString is allocated on the stack. The .c_str() method just returns a pointer to some contiguous internal memory of the wstring object. When the function returns, originalString goes out of scope and is destroyed, therefore the pointer value you return points to deleted memory.
If you need to do this, you shou... |
1,861,581 | 1,861,623 | Does defining a function inside a header always make the compiler treat it as inline? | I just learned that defining a c++ function inside a class's header file make the function inline. But I know that putting the inline keyword next to a function is only a suggestion and the compiler wont necessarily follow it. Is this the same for header defined c++ functions and is there a difference in behavior be... | "defining a c++ function inside a class's header file make the function inline"
That's not true. Defining a function (that is to say, providing the body of the function instead of just a declaration) inside a class definition makes it inline. By "makes it inline", I mean it's the same as giving it the inline keyword. B... |
1,861,654 | 1,861,790 | Is there a way to prevent a header defined c++ function from being treated as inlined | I am making a Qt application and as I was coding, I took the habit of defining my slots in the header. I found it was easier for me to develop that way though I still define normal functions in the .cpp (unless the function is really small). But now there are some worries from my colleague that putting these in the h... | Your colleague needs to check up on the meaning of inlining in C++.
There are two meanings of the word, and it's important to keep them separated:
According to the C++ standard, a function is inline if it is marked with the inline keyword, or defined inside the class definition.
The only required effect of this, is to ... |
1,861,679 | 1,861,695 | Is it possible to define multiple classes in just one .cpp file? | I'm working on a project for school and the instructor insists that all code go into one .cpp file (for easier grading on his part). I would like to define multiple classes within this file. Will I run into any problems in doing this?
| There is no rule you have to follow (like in java). You're free to place and name classes in however named files you like (besides the suffix).
However its another question if that is good practices (its not!).
|
1,861,837 | 1,861,977 | Workarounds for the forward-declared class enumeration problem? | I am maintaining a large code base and am using a combination of forward declarations and the pImpl idiom to keep compile times down and reduce dependencies (and it works really well,)
The problem I have is with classes that contain public enumerations. These enumerations cannot be forward declared so I am left with n... | Put the enumeration into its own type:
struct FooEnum
{
enum Type
{
TYPE_A,
TYPE_B,
};
};
Then Foo and Bar can both access FooEnum::Type and Bar.h doesn't need to include Foo.h.
|
1,861,912 | 1,861,933 | Should "delete this" be called from within a member method? | I was just reading this article and wanted SO folks advice:
Q: Should delete this; be called from within a member method?
| Normally this is a bad idea, but it's occasionally useful.
It's perfectly safe as long as you don't use any member variables after you delete, and as long as clients calling this method understand it may delete the object.
A good example of when this is useful is if your class employs reference counting:
void Ref() {
... |
1,861,964 | 1,862,017 | Qt QString cloning Segmentation Fault | I'm building my first Qt app using Qt Creator, and everything was going fine until I started getting a strange SIGSEGV from a line apparently harmless.
This is the error:
Program received signal SIGSEGV, Segmentation fault.
0x0804e2fe in QBasicAtomicInt::ref (this=0x0) at /usr/lib/qt/include/QtCore/qatomic_i386.h:12... | In c++'s map, if the element doesn't exist when you try to access it by its key, it just creates one for you. You are attempting to do the same thing here, and if QMap works the same way, this is what is causing your segfault.
What you should be doing is testing for the key's presence in the map before accessing it.
ed... |
1,862,214 | 1,862,227 | Why are operators sometimes stand-alone and sometimes class methods? | Why is that sometimes an operator override is defined as a method in the class, like
MyClass& MyClass::operatorFoo(MyClass& other) { .... return this; };
and sometimes it's a separate function, like
MyClass& operatorFoo(MyClass& first, MyClass& bar)
Are they equivalent? What rules govern when you do it one way and w... | If you want to be able to do something like 3 + obj you have to define a free (non-member) operator.
If you want to make your operators protected or private, you have to make them methods.
Some operators cannot be free functions, e.g., operator->.
This is already answered here:
difference between global operator and me... |
1,862,287 | 1,866,779 | Optimizing a pinhole camera rendering system | I'm making a software rasterizer for school, and I'm using an unusual rendering method instead of traditional matrix calculations. It's based on a pinhole camera. I have a few points in 3D space, and I convert them to 2D screen coordinates by taking the distance between it and the camera and normalizing it
Vec3 ray_to_... | It is difficult to understand exactly what your code doing, because it seems to be performing a lot of redundant operations! However, if I understand what you say you're trying to do, you are:
finding the vector from the pinhole to the point
normalizing it
projecting backwards along the normalized vector to an "image... |
1,862,360 | 1,862,367 | Error making C++ functions virtual | The error states:
"error: virtual outside class definition"
Cpp members in question:
virtual void Account::creditBalance(double plus)
{
if(plus > 0)
balance += plus;
else
cout << "Cannot credit negative.";
}
virtual void Account::debitBalance(double minus)
{
if(minus <= balance)
balance -= m... | Simply strip the virtual off of the method definition. The virtual keyword is only necessary at the declaration.
Example:
class Account {
public:
virtual void creditBalance(double);
virtual void debitBalance(double);
};
void Account::creditBalance(double plus)
{
if(plus > 0)
balance += plus;
else
... |
1,862,453 | 1,862,592 | portable signed/unsigned byte cast,C++ | I am using signed to unsigned byte(int8_t) cast to pack byts.
uint32_t(uint8_t(byte)) << n
This works using GCC on Intel Linux. Is that portable for other platforms/compilers, for example PowerPC?
is there a better way to do it? using bitset is not possible in my case.
I am using stdint via boost
| If you are using boost/cstdint.hpp from the Boost Integer library, then yes, the typedefs are portable (cross-platform.) The boost/cstdint.hpp header is meant to implement C99 stdint.h functionality in C++.
From the Boost documentation:
The header
provides the typedef's useful for
writing portable code that requ... |
1,862,645 | 1,862,664 | should i put .hpp and .cpp in the same fold or in ./src and ./hdr respectively? | it seems that separate them into src and hdr is a popular solution. however, this is not the case in Netbeans: by default, netbeans will put both hpp and cpp files in the same directory.
questions:
should I separate them or not? why?
if 1 is yes, is there any way to automatically set this in Netbeans?
| If you plan to distribute a library as binaries and headers, it might be easier to have the headers in a separate directory to begin with.
|
1,862,658 | 1,862,673 | what's the difference between hpp and hxx? | for gcc they should be the same, right? which one of them is more popular , i am now preparing a project from scratch and i would like to pick one among these 2.
thanks
| In C++, the file extension doesn't actually matter. The use of .h, .hpp, .hxx, or no file extension are all by convention.
The standard library uses no file extension for its header files. Many projects, including Boost, use .hpp. Many projects use .h. Just pick one and be consistent in your project.
|
1,862,821 | 1,862,863 | Who can tell me what this bit of C++ does? | CUSTOMVERTEX* pVertexArray;
if( FAILED( m_pVB->Lock( 0, 0, (void**)&pVertexArray, 0 ) ) ) {
return E_FAIL;
}
pVertexArray[0].position = D3DXVECTOR3(-1.0, -1.0, 1.0);
pVertexArray[1].position = D3DXVECTOR3(-1.0, 1.0, 1.0);
pVertexArray[2].position = D3DXVECTOR3( 1.0, -1.0, 1.0);
...
I've not touched C++ for ... | m_pVB points to a graphics object, in this case presumably a vertex buffer. The data held by this object will not generally be in CPU-accessible memory - it may be held in onboard RAM of your graphics hardware or not allocated at all; and it may be in use by the GPU at any particular time; so if you want to read from i... |
1,862,867 | 1,865,852 | What is the best single-source shortest path algorithm for programming contests? | I was working on this graph problem from the UVa problem set. It's a single-source-shortest-paths problem with no negative edge weights. From what I've gathered, the algorithm with the best big-O running time for such problems is Dijkstra with a Fibonacci heap as the priority queue, although practically speaking a bina... | Based on my own experience, I never needed to implement Dijkstra algorithm with a heap in a programming contest. You can get away most of the time, using a slower but efficient enough algorithm. You might use a best Dijkstra implementation to solve a problem which expects a different/simpler algorithm, but this is rare... |
1,862,952 | 1,862,966 | Why do C++ class definitions on Windows often have a macro token after 'class'? | I am trying to understand an open source project, where I came across the following class declaration:
class STATE_API AttributeSubject : public AttributeGroup, public Subject
{
public:
AttributeSubject(const char *);
virtual ~AttributeSubject();
virtual void SelectAll() = 0;
virtual const std::string T... | It's probably a typedef to __declspec(dllimport) or __declspec(dllexport) and is used inside DLLs on windows platform to export classes.
Neil is right, it's a macro.
It usually looks like this:
#ifdef INDSIDE_DLL
#define STATE_API __declspec(dllexport)
#else
#define STATE_API __declsped(dllimport)
#endif
You d... |
1,863,153 | 1,863,219 | Why unsigned int 0xFFFFFFFF is equal to int -1? | In C or C++ it is said that the maximum number a size_t (an unsigned int data type) can hold is the same as casting -1 to that data type. for example see Invalid Value for size_t
Why?
I mean, (talking about 32 bit ints) AFAIK the most significant bit holds the sign in a signed data type (that is, bit 0x80000000 to for... | C and C++ can run on many different architectures, and machine types. Consequently, they can have different representations of numbers: Two's complement, and Ones' complement being the most common. In general you should not rely on a particular representation in your program.
For unsigned integer types (size_t being ... |
1,863,380 | 1,863,392 | Cross platform c++ with libcurl | I am a perl developer that has never went into the client side programming of things. I'd like to think that I'm a pretty good developer, except I know that my severe lack of knowledge of the way desktop programming really takes away from my credibility.
That said, I really want to get into doing some desktop applicat... | You need to write the code portably - basically make it a console application. You then transfer the source code (not the exe) to the other platforms and compile it there and link with the version of llibcurl on each specific platform.
|
1,863,597 | 1,863,988 | C++ "Scrolling" through items in an stl::map | I've made a method to scroll/wrap around a map of items, so that if the end is reached, the method returns the first item and vice-versa.
Is there more succinct way of doing this?
MyMap::const_iterator it = myMap.find(myKey);
if (it == myMap.end())
return 0;
if (forward) {
it++;
if (it == myMap.end()) {... | You can do this with a template. As was stated by a previous poster, this can be cumbersome from the standpoint that it never reaches the end so the user must somehow control this. I'm assuming you have a good reason, perhaps producing some round robin behavior.
#include <iostream>
#include <string>
#include <vecto... |
1,863,613 | 1,863,924 | What does "symbol value" from nm command mean? | When you list the symbol table of a static library, like nm mylib.a, what does the 8 digit hex that show up next to each symbol mean? Is that the relative location of each symbol in the code?
Also, can multiple symbols have the same symbol value? Is there something wrong with a bunchof different symbols all having the ... | Here's a snippet of code I wrote in C:
#include
#include
void foo();
int main(int argc, char* argv[]) {
foo();
}
void foo() {
printf("Foo bar baz!");
}
I ran gcc -c foo.c on that code. Here is what nm foo.o showed:
000000000000001b T foo
0000000000000000 T main
U printf
For this example... |
1,863,751 | 1,863,767 | Array decay to pointers in templates | Please consider this code:
#include <iostream>
template<typename T>
void f(T x) {
std::cout << sizeof(T) << '\n';
}
int main()
{
int array[27];
f(array);
f<decltype(array)>(array);
}
Editor's Note: the original code used typeof(array), however that is a GCC extension.
This will print
8 (or 4)
108
I... | Use the reference type for the parameter
template<typename T> void f(const T& x)
{
std::cout << sizeof(T);
}
in which case the array type will not decay.
Similarly, you can also prevent decay in your original version of f if you explicitly specify the template agument T as a reference-to-array type
f<int (&)[27]>(... |
1,863,827 | 1,863,835 | GCC Compiler Warning: extended initializer lists only available with c++0x | Using this member initialization...
StatsScreen::StatsScreen( GameState::State level )
: m_Level( level ) {
...//
}
I get the following warning...
extended initializer lists only available with -std=c++0x or -std=gnu++0x
Any information regarding this warning?
Edit: Warning went away after I removed one of the m... | I think you are initializing the object with {...} instead of (...):
StatsScreen ss{...}; // only available in C++0x
StatsScreen ss(...); // OK in C++98
To compile your code as C++0x code, just add the following flag when compiling:
g++ test.cpp -std=c++0x
|
1,864,032 | 1,864,060 | In .cpp file, defining methods with "class Foo { void method() {} };" instead of "void Foo::method() {}"? | When you have inline definitions of functions in the header file, and you want to move the the function definition bodies out of the header and into a .cpp file, you can't just cut-and-paste the functions as they were defined in the header; you have to convert the syntax from this:
class Foo
{
void method1() { definiti... | This will not work: the compiler will see this as you redefining the class. I'm afraid there is no way around this, it's part of the language.
[ps: I know these kinds of jobs are tedious, but we all have to do them at one time or another. If it is that big a job, you could look at writing a script to do it for you, b... |
1,864,103 | 1,864,138 | Reading Superblock into a C Structure | I have a disk image which contains a standard image using fuse. The Superblock contains the following, and I have a function read_superblock(*buf) that returns the following raw data:
Bytes 0-3: Magic Number (0xC0000112)
4-7: Block Size (1024)
8-11: Total file system size (in blocks)
12-15: FAT length (... | Yes, I think you'd be better off reading this into a structure. The fields containing useful data are all 32-bit integers, so you could define a structure that looks like this (using the types defined in the standard header file stdint.h):
typedef struct SuperBlock_Struct {
uint32_t magic_number;
uint32_t block_si... |
1,864,373 | 1,864,388 | What common application types are created with Visual C++? | C# and VB .net (higher level languages) tend to be good for n-tier business applications and such.
I find C++ a very interesting language and would like to spend more time developing in it.
What kinds of applications are better suited to C++ applications? Are many windows forms apps (for example) created using C++?
| C++ is best suited for system programming. For example, creating windows services. Also, traditionally it has been the language of choice for writing high-performance code such as in 3D graphics or scientific applications.
In general, C++ frameworks (MFC, etc) are tedious for creating graphical applications compared to... |
1,864,506 | 1,864,694 | Native Makefile alternative for windows | What is a good alternative to Makefile on windows?
I'm compiling a collection of c++ files (.cpp's and .h's) using cl.exe.
I'd rather not use Makefile, as I want to minimise the amount of 3rd party utilities people will need to build my application.
Drew J. Sonne.
| VisualStudio comes with nmake which would not require any 3rd party tools.
|
1,864,615 | 1,864,643 | How to declare a static variable but not define it | Some times we need to pre-declare a static variable and then use it.
But the variable name of this declaration may be wrong, and the compiler can not detect it, oops!
Example:
/* lots of codes */
static some_type some_name; /* pre-declaration */
/* but it may define "some_name" */
/* use som... | gcc will give a warning in the case you've described:
./x.c:3010: warning: 'someName' defined but not used
Solution: Do what you're currently doing, but don't ignore compiler warnings ;)
Edit:
With your updated question: No, I don't believe there is a way to simply declare a static variable (without also defining it).... |
1,865,069 | 8,582,538 | How to compile a 64-bit application using Visual C++ 2010 Express? | Is there a simple way to compile a 64 bit app with the 32-bit edition of Visual C++ 2010 Express? What configurations, if any, are necessary?
| Here are step by step instructions:
Download and install the Windows Software Development Kit version 7.1. Visual C++ 2010 Express does not include a 64 bit compiler, but the SDK does. A link to the SDK: http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx
Change your project configuration. Go to Properties of ... |
1,865,236 | 1,865,248 | Is it necessary to learn Java for contributing to an open source project? | I am more into C/C++. But many of my seniors here in college ask me to learn Java if I want to contribute to an open source project.. I'm in dilemma. what to do? Can't we do a design project in C/C++?
| There are plenty of open source C and C++ projects - as well as loads in virtually any other language you can come up with.
Of course it's never a bad idea to learn another language, but don't feel too constrained by "only" knowing C and C++.
If you want to contribute to a specific open source project which is written ... |
1,865,557 | 1,865,570 | Which C++ does Visual Studio 2008 (or later) use? | I find C++ is very controversial language in microsoft world. By default we have ISO C++ and then microsoft has Managed C++ and now C++ CLI.
I just know standard (ISO) C++. I don't know microsoft's version of C++.
I'm confused about interpretation of any c++ code by visual studio 2008 (or later). Thats why I'm using gn... | Everything is in the build settings:
Common Language Runtime Support (/clr) - add or remove CLR support
Advance Compile as C++ Code (/TP) - to choose if c++ or c..
Language: Disable Language Extention - use this to force ANSI.
|
1,865,629 | 1,865,653 | Generic VC++ vs g++ query | I have trouble understanding the compilers.
The following code does work in UNIX under g++, but under VC++ it would not even compile. Anyone can provide valid reasons why?
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string tmp_nw_msg, crc_chksum, buffer;
cout... | You need to replace #include <string.h> by #include <string>
C++ headers don't have the .h extension to differentiate them from C headers that would have the same name.
Also, you don't need the #include <stdio.h> header for your program -- and in case you need to call stdio functions from a C++ program you should #incl... |
1,865,631 | 1,866,237 | Loading an EXE as a DLL, local vftable | I have an exe named test.exe which is usually used as a stand-alone application. I want to use this exe as a module (a dll) inside another application, app.exe.
The code in test.exe does something really simple like:
void doTest()
{
MyClass *inst = new MyClass();
inst->someMethod();
}
Where someMethod() is vir... | The workaround I ended up using is to simply add a compile configuration and compile the exe as a real dll instead of forcing it to act like one.
using /fixed:no didn't solve the problem for some reason.
Another difference I between exes and DLLs is that the entry point is different. a DLL's entry point is DllMain wher... |
1,865,652 | 1,866,840 | Using (void*) as a type of an identifier | In my program, I have objects (of the same class) that must all have a unique identifier. For simplicity and performance, I chose to use the address of the object as identifier. And to keep the types simple, I use (void*) as a type for this identifier. In the end I have code like this:
class MyClass {
public:
typedef... | You are violating logical constness returning the object as mutable in a const method.
As Neil points out, no cast is needed.
class MyClass {
public:
typedef const void* identity_t;
identity_t id() const { return this; }
};
|
1,865,719 | 1,866,030 | How to NOT generate debug information for specific source files / source sections? | Is there a way to create a Debug build of our Vs2005 (C++) project and exclude specific modules or code sections from being included into the debug information? Or is there an option to have VS generate multiple PDB files from a single project?
It looks like our generated PDB file is getting too large for Visual Studi... | I agree with Andreas' comment - you're almost certainly better splitting the project.
However, if you right-click a C++ source file (don't think you can do this with C#), and open the properties you've got complete control over how that specific file (or files) is built.
K
|
1,865,800 | 1,891,603 | C++ vs Java constructors | According to John C. Mitchell - Concepts in programming languages,
[...] Java guarantees that a
constructor is called whenever an
object is created. [...]
This is pointed as a Java peculiarity which makes it different from C++ in its behaviour. So I must argue that C++ in some cases does not call any constructor... | Giving an interpretation, I have a suggestion about why the author says that for Java, without looking for any corner cases which I think don't address really the problem: you could think for example that PODs are not objects.
The fact that C++ has unsafe type casts is much more well known. For example, using a simple ... |
1,866,080 | 1,866,123 | Is there any standard to consume a webservice inside of native C++? | I am looking for resources to show me how I can consume web services inside native C++ . Are there any popular libraries I can use?
TIA
Andrew
| It really depends on what webservice architecture you are talking about... For XML-RPC IBM has a nice article showcasing XMLRPC++, for SOAP there is e.g. gSOAP or WSO2 WSF/C++, ...
|
1,866,181 | 1,867,920 | Why can I not perform a sizeof against a static char[] of another class? | Why does the following code generate a compile error?
Edit: My original code wasn't clear - I've split the code up into separate files...
First.h
class First
{
public:
static const char* TEST[];
public:
First();
};
First.cpp
const char* First::TEST[] = {"1234", "5678"};
First::First()
{
uint32_t len =... | sizeof only works on complete types. const char* TEST[] is not a complete type until it is defined in First.cpp.
sizeof(char*[10]) == sizeof(char*) * 10 == 40
sizeof(short[10]) == sizeof(short) * 10 == 20
// a class Foo will be declared
class Foo;
sizeof(Foo) == //we don't know yet
// an array bar will be defined.
i... |
1,866,193 | 1,866,211 | To what extent is using "delete this" compliant to C++ standard? | When implementing reference counting in objects the "release and possibly delete object" primitive is usually implemented like this:
void CObject::Release()
{
--referenceCount;
if( referenceCount == 0 ) {
delete this;
}
}
First of all, delete this looks scary. But since the member function returns i... | Yes, that will behave like deleting any other object.
|
1,866,461 | 1,866,543 | Why should I not try to use "this" value after "delete this"? | In this paragraph of C++ FAQ usage of delete this construct is discussed. 4 restrictions are listed.
Restrictions 1 to 3 look quite reasonable. But why is restriction 4 there that I "must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it"?
I mean this is yet a... | The reason that you cannot do anything with a pointer after you delete it (this, or any other pointer), is that the hardware could (and some older machines did) trap trying to load an invalid memory address into a register. Even though it may be fine on all modern hardware, the standard says that the only thing that y... |
1,866,884 | 2,408,109 | GUI Control For Audio Presentation | I need GUI control for audio file presentation. The language is not very important but it should run on windows platform.
I should be able to :-
load the file
play the sound
put and move markers across the audio bar.
it would be nice if it can load itself from RTP wireshark captures (and not wav files).
An example... | Try AudioExCs example from Alvas.Audio library http://alvas.net/alvas.audio.aspx
|
1,867,030 | 1,867,286 | Combinations of Multiple Vector's Elements Without Repetition | I have n amount of vectors, say 3, and they have n amount of elements (not necessarily the same amount). I need to choose x amount of combinations between them. Like choose 2 from vectors[n].
Example:
std::vector<int> v1(3), v2(5), v3(2);
There cannot be combinations from one vector itself, like v1[0] and v1[1]. How c... | If I understand you correctly you have N vectors, each with a different number of elements (call the size of the ith vector Si) and you which to choose M combinations of elements from these vectors without repetition. Each combination would be N elements, one element from each vector.
In this case the number of possibl... |
1,867,067 | 1,867,201 | Read from same file (until EOF) using ifstream after file contents change | Requirement :
I must read until EOF (16 bytes a
time) from a particular file , and
then say sleep for 5 seconds. Now,
after 5 seconds, when I try to read
from the file (whose contents would
have been appended by that time), the
intended design must be in such a way
that it reads from the point where it... | You'll have to:
save your position
close the file
reopen the file
seek to your saved postion and resume reading until EOF
|
1,867,262 | 1,867,368 | What is the fastest way to deconstruct a fixed length binary/alpha message? | What would you suggest as the fastest or best way to parse a fixed length message in c++ which has fields defined like
field = 'type', length = 2, type = 'alphanumeric'
field = 'length', length = 2, type = 'binary' (edit:length = 2 means 16 bit)
...
...
and so on
I read about making a struct and then using reinterpr... | Is this what you mean?
char* binaryMessage; //From somewhere
struct Fields {
short type; // 2 bytes
short length; // 2 bytes
};
Fields* fields = reinterpret_cast<Fields*>(binaryMessage);
std::cout << "Type = " << fields->type;
std::cout << "Length = " << fields->length;
A safer alternative is boost::basic_buff... |
1,867,634 | 1,867,667 | Properly extending a COM interface (IDL) | I am working with some legacy c++ code and I need to extend an interface. The current interfaces are for example:
[
object,
uuid(guid),
version(1.0),
dual,
nonextensible,
oleautomation
]
interface IInfo : ITask {
// Methods here
}
[
object,
uuid(guid),
version(1.0),
dual,
nonextensible,
olea... | The proper way to do this is to create an IExtendedInfoTask2 that extends the new IInfo2 interface. COM requires that an interface, once defined, is immutable.
You can have the same class implement both IExtendedInfoTask and IExtendedInfoTask2, so the caller can use either version. It's only a vtable difference -- yo... |
1,868,492 | 1,870,536 | How to do hardware accelerated alpha blending in SDL? | I'm trying to find the most efficient way to alpha blend in SDL. I don't feel like going back and rewriting rendering code to use OpenGL instead (which I've read is much more efficient with alpha blending), so I'm trying to figure out how I can get the most juice out of SDL's alpha blending.
I've read that I could bene... | Decided to just not use alpha blending for that part. Pixel blending is too much for software surfaces, and OpenGL is needed when you want the power of your hardware.
|
1,868,993 | 1,869,052 | Continuous Streaming PCM data in C++? | I have a stream of PCM audio captured from a cell phone, and I want to play it.
I am trying to find a lightweight method of playing this audio in C++.
I can already slap on a wave header and create a file that plays in any media player, but I want to play the file in real time as it streams in. I would like to avoid wr... | Use the waveOut API in Windows
|
1,869,171 | 1,869,616 | Returning std::pair versus passing by non-const reference | Why is returning a std::pair or boost::tuple so much less efficient than returning by reference? In real codes that I've tested, setting data by non-const reference rather than by std::pair in an inner kernel can speed up the code by 20%.
As an experiment, I looked at three simplest-case scenarios involving adding two ... | I tried that with VC++2008, using cl.exe /c /O2 /FAs foo.cpp (that's "compile only and do not link", "optimize for speed", and "dump assembly output with matching source code lines in comments"). Here's what getLine() ended up being.
"byref" version:
PUBLIC ?getPair@@YAXHAAH0@Z ; getPair
; Function comp... |
1,869,305 | 1,869,474 | Guide to switch from Visual Studio to Emacs on windows? | I do not want to learn an IDE or similar software which is only made for one platform only. I want to spend my time+energy in learning something which is a timeless-truth.
I want to switch to an editor-religion, which has no religion but of development and progress, it sees & treats all with equality.
Yes, please prov... | You'll need to consider whether you want to use Emacs as your editor only, but continue to maintain your project settings, source files and build/debug environment in Visual Studio, or switch completely to Emacs as you editor and use some other tools (e.g., make) to build your project using VS compilers or other compil... |
1,869,308 | 1,869,351 | Trouble with objects and Pointers | vector < Shape* > shapes;
void createScene()
{
image = QImage(width, height, 32); // 32 Bit
Color amb(0.1,0.1,0.1);
Color difCoef(0.75,0.6,0.22);
Color spec(0.5,0.5,0.5);
double shine= 3.0;
Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shine);
shapes.push_back(s);
}
int main(){
//... | I think object slicing occures (since you'r using a Shape object and assigning to it). What you would want to do in order to preserve polymorphism is use a pointer or a reference. In this case I would use a pointer:
Shape *x = shapes[0];
If shapes is an odd container which does de-reference (this is what i understand ... |
1,869,439 | 1,869,518 | Header inclusion optimization | Is there an automatic way to optimize inclusion of header files in C++, so that compilation time is improved ? With the word "automatic" I mean a tool or program. Is it possible to find which headers files are obsolete (e.g exposed functionality is not used) ?
Edit: Having each include header "included only once is on... | Update
I think what you really want is "include what you use" rather than a minimal set of headers. IWYU means forward declare as much as possible, and include headers that directly declare the symbols you use. You cannot mindlessly convert a file to be IWYU clean as it may no longer compile. When that occurs, you need... |
1,869,504 | 1,869,688 | c++ registry read/write from a non-admin Windows Service | I'd like to read/write some registry information from my non-admin Windows Service, and have it applied regardless of the user logged in. Would using a subkey of HKEY_USERS/.DEFAULT do the trick?
Essentially, something like CSIDL_COMMON_APPDATA but in the registry.
Thanks!
| What do you mean by "have it applied"? I assume you mean write it to one place and all other users can read it; in that case, HLKM is the only answer. Why not change your service to run under one of the service accounts?
|
1,869,701 | 1,871,689 | Drawing text on a framebuffer in Linux from C | How can a program draw text on a frame buffer mapped in as an array? What is needed is both a means of representing the individual characters, and of drawing the characters pixel by pixel in a manner that is not too inefficient. The representation of the characters should ideally be defined solely in code, and no third... | I don't have any information specific to frame buffers, but I do have an interesting way of encoding a font.
If you have an application that can write to the XBM format, you can encode a font just by creating an image containing all the characters. The XBM file can be included as a C or C++ file, and by using the prope... |
1,869,970 | 1,870,046 | C++ Switch won't compile with externally defined variable used as case | I'm writing C++ using the MinGW GNU compiler and the problem occurs when I try to use an externally defined integer variable as a case in a switch statement. I get the following compiler error: "case label does not reduce to an integer constant".
Because I've defined the integer variable as extern I believe that it ... | A case label requires an integral constant expression which have strict requirements that enable their value to be determined at compile time at the point of use.
From 5.19 [expr.const], "an integral constant expression can involve only literals (2.13), enumerators, const variables or static data members of integral or... |
1,870,035 | 1,870,052 | struct vs class as STL functor when using not2 | Studing STL I have written a a simple program to test functors and modifiers. My question is about the difference aon using CLASS or STRUCT to write a functor and try to operate on it with function adaptors.
As far as I understand in C++ the difference beetween CLASS and STRUCT is that in the last case the members are ... | The difference you read from other answers is correct. struct is just a class with public accessibility by default. This includes the inheritance modifier. Basically, you should mention public before the base class name when you're using a class to make those definitions equivalent:
template <class T>
class mystruct : ... |
1,870,047 | 1,870,345 | What encryption scheme meets requirement of decimal plaintext & ciphertext and preserves length? | I need an encryption scheme where the plaintext and ciphertext are composed entirely of decimal digits.
In addition, the plaintext and ciphertext must be the same length.
Also the underlying encryption algorithm should be an industry-standard.
I don't mind if its symmetric (e.g AES) or asymmetric (e.g RSA) - but it mus... | Use AES/OFB, or any other stream cipher. It will generate a keystream of pseudorandom bits. Normally, you would XOR these bits with the plaintext. Instead:
For every decimal digit in the plaintext
Repeat
Take 4 bits from the keystream
Until the bits form a number less than 10
Add this number to the plaintext ... |
1,870,249 | 1,870,267 | Question about Pointers and Objects | My last question was a mess. I'm getting the wrong output.
So here I have in my main:
image = QImage(width, height, 32); // 32 Bit
Color amb(0.1,0.1,0.1);
Color difCoef(0.75,0.6,0.22);
Color spec(0.5,0.5,0.5);
double shineExp = 3.0;
Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shineExp);
shapes.... | The problem is that you're repeating your variable declarations in the derived class. You don't need to redeclare variables like double shine, which are already in Shape, in the derived class Sphere. Since Sphere inherits from Shape, all the public member variables in Shape are automatically inherited in Sphere, and ... |
1,870,329 | 1,870,359 | (c/c++) do copies of string literals share memory in TEXT section? | If I call a function like
myObj.setType("fluid");
many times in a program, how many copies of the literal "fluid" are saved in memory? Can the compiler recognize that this literal is already defined and just reference it again?
| I believe that in C/C++ there is no specified handling for that case, but in most cases would use multiple definitions of that string.
|
1,870,389 | 1,871,322 | Qt tells me that my SLOT doesnt exist, but with a make clean, make it doesnt complain anymore | when i download a fresh copy from our SVN, make then run my program, Qt tells me that one of my SLOTS doesn't work but with a handy-dandy make clean then make, it seems to solve the problem. i continue to make changes in the code on my PC and that message never shows again.
C++
Qt 4.6
gcc
has anyone had this problem?
a... | Qt creates a whole bunch of metadata about your Q_OBJECT classes when you build. That metadata is stored in 'moc' files, one of which may have become inconsistent with your C++ code. It's usually a bad idea to store intermediate build stages in your version control system. I'd suggest running make clean, then looking a... |
1,870,627 | 1,870,664 | Type traits definition. Traits blobs & Metafunctions | Reading some source code, I have found next traits definition:
namespace dds {
template <typename Topic> struct topic_type_support { };
template <typename Topic> struct topic_data_writer { };
template <typename Topic> struct topic_data_reader { };
template <typename Topic> struct topic_data_seq { };
}
#d... | Having a single template class is now called a "traits blob". "Traits blob" are not recommended as they do not work well with meta-function (i.e. compile-time functions).
A meta-function is a template that takes a class and performs some operation on it. Something like:
template <class T>
class metafunction
{
typ... |
1,870,662 | 1,870,679 | How do you use a C++ iterator? | I have a vector like so:
vector<MyType*> _types;
And I want to iterate over the vector and call a function on each of MyTypes in the vector, but I'm getting invalid return errors from the compiler. It appears the pos iterator isn't a pointer to MyType, it's something else. What am I not understanding?
Edit: Some code..... | If the vector contained objects, not pointers, you could do pos->foo(). The iterator "acts like" a pointer. But your vector contains pointers, so an iterator will act like a pointer to a pointer, so needs to be dereferenced twice.
MyType *pMyType = *pos; // first dereference
if (pMyType) { // make sure the p... |
1,871,198 | 1,871,213 | Member function still const if it calls functions that break "constness"? | I'm wondering if a class's member function should be const if it calls other functions that modify its data members. A good example would be a public member function that uses private member functions to do the brunt of the work.
void Foo::Show() const { // Doesn't directly modify data members in this function
Show... | If a function calls functions that modify certain data, then it should be said that the function itself modifies data. It just happens to be abstracted.
So no, that function should not be const.
|
1,871,375 | 1,871,409 | Python ctypes: initializing c_char_p() | I wrote a simple C++ program to illustrate my problem:
extern "C"{
int test(int, char*);
}
int test(int i, char* var){
if (i == 1){
strcpy(var,"hi");
}
return 1;
}
I compile this into an so. From python I call:
from ctypes import *
libso = CDLL("Debug/libctypesTest.so")
func = libso.test
fun... | The string which you initialized with the characters "bye", and whose address you keep taking and assigning to charP, does not get re-initialized after the first time.
Follow the advice here:
You should be careful, however, not to
pass them to functions expecting
pointers to mutable memory. If you
need mutable m... |
1,871,379 | 1,871,527 | C++ static member functions and their scope | I have two questions.
In C++, a static member function has direct access to a public non-static data member defined in the same class?
False
In C++, a non-static member function has direct access to a private static data member defined in the same class?
True
My note say false for the first question and true for the s... | Everyone's in agreement, but should be very careful about their wording, because actually static member functions do have access to public non-static data members. For that matter, they have access to private non-static data members too. They just need an object to operate on, to access its members. This could be a par... |
1,871,563 | 1,871,640 | Building libcurl library in c++, Noob Question | I wanna write a little c++ program using libcurl. It's for a school project so I need to be able to package everything in a zip file and email it to my instructor.
I've just downloaded the tar from the libcurl website but now I'm not sure what the next step is... What else do I gotta do in order to be able to do #inclu... | 1) Download the source from here.
2) unpack with "tar xvzf tarfilename"
3) cd to newly created directory from the unpack
4) enter "./configure"
5) enter "make" and "make install"
6) write your program and remember to link against the library.
7) When ready to send to prof, I would zip the original libcurl source along ... |
1,871,570 | 1,871,583 | Operation on different data types | Considering the basic data types like char, int, float, double etc..in any standard language C/C++, Java etc
Is there anything like.."operating on integers are faster than operating on characters".. by operating I mean assignment, arithmetic op/ comparison etc.
Are data types slower than one another?
| For almost anything you're doing this has almost no effect, but purely for informational purposes, it is usually fastest to work with data types whose size is machine word size (i.e. 32 bits on x86 and 64-bits on amd64). Additionally, SSE/MMX instructions give you benefits as well if you can group these and work on the... |
1,871,688 | 1,871,699 | is it possible to have a C/C++ GUI application in linux bare-bone server? | I am very disappointed with my school linux server when doing the homework on it.
The reason is: my homework requires to make GUI application.
All the tool that I have is:
- ssh from my local machine to school machine
- gcc/g++ in my school machine
I have been thinking and tried out different solutions for a week.
... | It should be possible to install most things, like ncurses or even X11, in user space (in your home directory), if you install them from source. With a Gnu package, you just use --prefix= as an argument to configure, like this:
./configure --prefix=/name/of/directory/to/install/into
I'm not sure about the other packa... |
1,872,571 | 1,872,860 | NULL pointer compatibility with static_cast | Q1. Why does using NULL pointers with static_cast cause crashes while dynamic_cast and reinterpret_cast give a NULL pointer in return?
The problem occurred in a method similar to the one given below:
void A::SetEntity(B* pEntity, int iMyEntityType)
{
switch (iMyEntityType)
{
case ENTITY1:
{
... | What compiler are you using? A static cast from a base type to a derived type might result in an adjustment to the pointer - especially likely if multiple inheritance is involved (which doesn't seem to be the case in your situation from your description). However, it's still possible without MI.
The standard indicat... |
1,872,575 | 1,872,590 | How to write a binary algorithm for C/C++ | I am having trouble to write the binary algorithm in C/C++.
My question is like that:
Apply binary algorithm to search for a number from 1 to 100 in a number guessing game.
The user will respond with 'y' for a correct guess, 'h' if the guess is too high or 'l' if the guess is too low.
I don't have any idea to apply i... | Detailed instructions here plus various implementations.
int low = 1;
int high = 100;
while (low <= high) {
int mid = (low + high) / 2;
char answer = evaluateGuess(mid); //return l, h or y;
if ('y'==answer) {
return mid;
}
if ('l' == answer) {
low = mid + 1;
} else {
high ... |
1,872,624 | 1,872,765 | how to design CPM algorithm? | how to represent a graph with list data structure i have three class (Graph, Node, Edge) and would like to find the critical path in graph.
how to calculate
ES : Earliest Start
EC : Earliest Complete
LS : Latest Start
LC : Latest Complete
thanks
| Another alternative for storing the graph is the Boost Graph Library (BGL). From what I see at wikipedia, the critical path is the longest path between two vertices. Furthermore it seems like finding the longest path is NP Complete for the general case but for a directed acyclic graph (DAG), which I think is your case,... |
1,872,714 | 1,872,839 | Can I use std::basic_string with things that aren't character types? | I've got a loop in my code that uses std::basic_string<HANDLE>, and then waits on it like this:
DWORD dwWaitResult = WaitForMultipleObjects((DWORD)handles.size(),
handles.data(),
FALSE, POLL_INTERVAL_MS);
It works fine, but when I ... |
Yes, if you provide a template specialization of the class traits for your type.
Provide your specialized class traits. (Second template parameter of class std::basic_string).
It is. But have you thought about using std::vector instead of std::basic_string? (It does not have this traits template argument that provides... |
1,872,759 | 2,048,835 | Statically linking against library built with different version of C Runtime Library, ok or bad? | Consider this scenario:
An application links to 3rd party library A.
A is built using MSVC 2008 and is statically linking (ie. built with /MT) to the C Runtime Library v9.0.
The application is built using MSVC 2005 and is statically linking to A and (using /MT) to the C Runtime Library v8.0.
I can see trouble with this... | It should not be a problem. Each library links to its own runtime and mostly functions independently from other libraries in the process. The problem comes about when the libraries ABI is badly defined. If any kind of heap allocated object is allocated in one library, passed across a library boundary and 'freed' in ano... |
1,872,799 | 1,872,854 | Simple Distributed Computation (similar to summation) (in C++) | I'm looking for a framework / approach to do message passing distributed computation in C++.
I've currently got an iterative, single-threaded algorithm that incrementally updates some data model. The updates are literally additive, and I'd like to distribute (or at least parallelize) the computation hereof over as man... | You probably want MPI (Message Passing Interface.) It's essentially the industry-standard for distributed computing. There are many implementations, but I would recommend OpenMPI because it's both free, and highly regarded. It provides you with a C API to pass messages between nodes, and also provides higher-level f... |
1,872,806 | 1,873,345 | Is there any heap compaction in C++? | I have a notion that C++ runtime doesn't do any heap compaction which means that the address of an object created on heap never changes. I want to confirm if this is true and also if it is true for every platform (Win32, Mac, ...)?
| The C++ standard says nothing about a heap, nor about compaction. However, it does require that if you take the address of an object, that address stays the same throughout the object's lifetime.
A C++ implementation could do some kind of heap compaction and move objects around behind the scenes. But then the "addresse... |
1,872,949 | 1,872,959 | Loading text from a file into a 2-dimensional array (C++) | I'm making a game and I have stored the map data in a 2-dimensional array of size [34][10]. Originally I generated the map using a simple function to fill up the array and saved this data to a file using the following code:
ofstream myFile;
myFile.open("map.txt");
for ( int y = 0 ; y < MAP_HEIGHT ; ++y )
{
for ( i... | while (!myFile.eof())
{
myFile.getline(line, MAP_WIDTH);
should be:
while ( myFile.getline(line, MAP_WIDTH) )
{
It would however be safer to read into a std::string:
string line:
while ( getline( myFile, line ) )
{
You might also want to read my blog on this subject, at http://punchlet.wordpress.com.
|
1,873,110 | 1,879,588 | How to check if application runs from \program files\ | Is there a reliable method to check if an application is run from somewhere beneath program files?
If the user installs the application to program files on local machine, we need to put writable files somewhere else to avoid virtualization on Vista and Win7. When installed to a network disk, though, we want to keep the... | This is not a terribly good idea, as a user can install it wherever they want to, and then the check might fail. Instead have a checkbox when the user installs the app, deciding if it is installed locally or on a server.
|
1,873,113 | 1,921,274 | How to implement a video widget in Qt that builds upon GStreamer? | I want to use Qt to create a simple GUI application that can play a local video file. I could use Phonon which does all the work behind the scenes, but I need to have a little more control. I have already succeeded in implementing an GStreamer pipeline using the decodebin and autovideosink elements. Now I want to use a... | To connect Gstreamer with your QWidget, you need to get the window handle using QWidget::winId() and you pass it to gst_x_overlay_set_xwindow_id();
Rough sample code:
sink = gst_element_factory_make("xvimagesink", "sink");
gst_element_set_state(sink, GST_STATE_READY);
QApplication::syncX();
gst_x_overl... |
1,873,219 | 1,873,233 | Strange Behaviour Class Objects Inside Union | Hi I wanted know the reasons of the following code
void main()
{
class test
{
public:
test(){}
int k;
};
class test1
{
public:
test1(){}
int k;
};
union Test
{
test t1;
test1 t2;
};
}
For the Above code it gives error "error C2620: union 'Test' : member 't... | According to the C++ standard (§9.5.1, cited as well in other answers):
A union can have member functions (including constructors and destructors), but not virtual functions. A union shall not have base classes. A union shall not be used as a base class. An object of a class with a non-trivial constructor, a non-trivi... |
1,873,334 | 1,873,409 | Staying away from virtual memory in Windows\C++ | I'm writing a performance critical application where its essential to store as much data as possible in the physical memory before dumping to disc.
I can use ::GlobalMemoryStatusEx(...) and ::GetProcessMemoryInfo(...) to find out what percentage of physical memory is reserved\free and how much memory my current proce... | Even if you're able to stop your application from having memory paged out to disk, you'll still run into the problem that the VMM might be paging out other programs to disk and that might potentially affect your performance as well. Not to mention that another application might start up and consume memory that you're c... |
1,873,352 | 1,875,190 | How do I convert a value from host byte order to little endian? | I need to convert a short value from the host byte order to little endian. If the target was big endian, I could use the htons() function, but alas - it's not.
I guess I could do:
swap(htons(val))
But this could potentially cause the bytes to be swapped twice, rendering the result correct but giving me a performance p... | Something like the following:
unsigned short swaps( unsigned short val)
{
return ((val & 0xff) << 8) | ((val & 0xff00) >> 8);
}
/* host to little endian */
#define PLATFORM_IS_BIG_ENDIAN 1
#if PLATFORM_IS_LITTLE_ENDIAN
unsigned short htoles( unsigned short val)
{
/* no-op on a little endian platform */
re... |
1,873,766 | 1,873,891 | c++ templated container scanner | here's today's dilemma:
suppose I've
class A{
public:
virtual void doit() = 0;
}
then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function that takes two iterators (one at the beginning of a sequence, the other at the end). The sequence is a sequence of A subcl... | You can use the std::foreach for that:
std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );
The std::mem_fun will create an object that calls the given member function for it's operator() argument. The for_each will call this object for every element within v.begin() and v.end().
|
1,873,773 | 1,873,804 | How can a template function 'know' the size of the array given as template argument? | In the C++ code below, the templated Check function gives an output that is not what I would like: it's 1 instead of 3. I suspect that K is mapped to int*, not to int[3] (is that a type?). I would like it to give me the same output than the second (non templated) function, to which I explicitly give the size of the ar... | template<class T, size_t S>
void Check(T (&)[S]) {
cout << "Deduced size: " << S << endl;
}
|
1,873,782 | 1,873,822 | Create thread with specific privilege c++ | I have multi-thread application that I want to create a thread with different user privilege (for example : multi domain admin privilege).
but I can't find any Win32 API CreateThread to do that.
How to create thread with specific user privileges?
thanks.
| Call CreateThread() with CREATE_SUSPENDED flag, then call SetThreadToken(), then ResumeThread().
|
1,874,051 | 1,874,109 | c++ multiple enums in one function argument using bitwise or "|" | I recently came across some functions where you can pass multiple enums like this:
myFunction(One | Two);
Since I think this is a really elegant way I tried to implement something like that myself:
void myFunction(int _a){
switch(_a){
case One:
cout<<"!!!!"<<endl;
break;
cas... | For that you have to make enums like :
enum STATE {
STATE_A = 1,
STATE_B = 2,
STATE_C = 4
};
i.e. enum element value should be in power of 2 to select valid case or if statement.
So when you do like:
void foo( int state) {
if ( state & STATE_A ) {
// do something
}
if ( state & STATE_B ) {
// ... |
1,874,056 | 1,874,149 | How to get started with game programming using VC++,C++,DirectX quickly? | Hi I am working in VC++ and I am quite interested in game programming and I have few queries.
1).What one must know before starting game programming ?
2).Can anybody give me info @ resources like tutorial ,links ,etc. which would help me to start as fast as possible ?
3).Also give me info @ some good books on game prog... | Before you start programming you must have a good understanding of the language, how to program and how to structure and test your code. Oh, and a huge amount of either patience or free time. On the maths front, Vectors, Matrices and Quaternions are the main things I found I needed.
The other thing that often goes over... |
1,874,061 | 1,874,169 | template class with overridden operators | I want to add a operator override to perform assignments/__set__s inline.
Template :-
class CBase {
public :
static void SetupVmeInterface(CVmeInterface *in);
protected :
static CVmeInterface *pVmeInterface;
};
template <class T> class TCVmeAccess : public CBase {
public:
TCVmeAcc... | Instead of overwriting the "->" and the "=" operator, you could derive from the template struct.
template <class T> class TCVmeAccess : public CBase, public T {
public:
TCVmeAccess(int address);
T get();
// T *operator->();
unsigned long asLong();
bool set(T);
// vo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.