question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,510,853 | 5,510,882 | C++ access member-function from friend class | Is there a way to access member-function from the friend class?
// foo.h
template<typename T>
class A
{
bool operator()(Item* item)
{
ObjectClass c = get_class_from_item(item); // compiler error
...
}
};
class B
{
...
template<typename T> friend class A;
...
ObjectClass get... | If get_class_from_item is supposed to be some kind of Factory function, which it seems to be, you need to make it static. You get the error because your compiler is looking for a function named get_class_from_item in class A. It will never see the function in B because it is not in the scope and you don't have an insta... |
5,510,914 | 5,511,306 | How I can send a Ctrl + P to window if i khow a handle of this window? | How I can send a Ctrl + P to window if i khow a handle of this window?
I think that i must use
PostMessage(hWnd...
| Consider using ControlSpy and, as Thomas Sampson says, check what messages are sent when you press Ctrl-P. After that you can use PostMessage and reproduce this behaviour. However, do check the state of a WM_CHAR and what you need to fill in. That's a lot. This is why they created keybd_event, which has been superseded... |
5,510,922 | 5,511,023 | Template class specialization | I did read some of the related threads but still the issue was not clear:
#include <stdio.h>
#include <vector>
#include <iostream>
template <> class stack <int>
{
public:
std :: vector <int> stackVector;
};
The compilation error:
templateSpecializ.cpp:5: error: ‘stack’ is not a template
templateSpecializ.cpp:6... | That is a template specialisation of a template called stack. stack is not defined inany of those header files. If you wish to define a new template class you must first define the base case
template<typename T>
class stack
{
//implementation goes here
};
template<>
class stack<int>
{
public:
std::vector<int> sta... |
5,511,050 | 5,511,113 | Is there any way to call the Windows Native API functions from the user mode? | I want to call some Native API function from the user mode with C++.
I was wondering if it is possible to circumvent the Windows API interface
completely and call directly the Native API functions from the user mode.
If possible then any code examples will be really helpful.
| Yes it is possible, as all functions are exposed ntdll.dll. However you would need to write your own header file for those API functions you want to use. There is no official documentation on the NT API and it is not really meant to be used directly. But it is possible.
Here is a starting point.
|
5,511,158 | 5,511,263 | Question on STL internals | I am currently writing some abstractions on IO for binary data. At this point I am currently not sure on how well the STL performs on some of these tasks. For example I have a lot of stuff I can encode binary to either char * or std::vector. For now whenever I have an object of this kind of byte type I either just writ... | iostream is for formatted (ie. text) IO only. If you want binary IO, you have to use streambuf classes.
Also, iostreams have the reputation of being slow (for various reasons, and your mileage will vary).
Iostreams use streambuf internally, which adds a layer of indirection, and provides you with automatic buffering. I... |
5,511,482 | 5,511,556 | Help with c++ stl map and operator overloading | i'm trying to use the stl map with a class that i've created, from what i've gathered if i want an object of my class Vertex to be the key for the map, i should also overload the < operator, i've attempted to do this in the class Vertex the file graph.h can be seen below:
#ifndef GRAPH_H
#define GRAPH_H
class Vertex
{... | The prototype for operator< should be:
bool operator<(const Vertex& b) const { ... }
Same thing for your operator==, should be const, and take a const reference.
The Vertex::get_name() should also be const.
|
5,511,486 | 5,514,360 | OpenCv fill pixel of onechannel image and show it | I wanna fill a black and white image and show it.
I can't understand what's the metter with this code:
IplImage * imageOut;
int window = 100;
cvNamedWindow("mappa", CV_WINDOW_AUTOSIZE );
imageOut = cvCreateImage(cvSize(window,window),8,1);
for(int i=0; i<window; i++){
for(int j=0; j<window;j++){
... | The correct procedure would be:
imageOut = cvCreateImage(cvSize(window,window),IPL_DEPTH_8U,1);
int width = imageOut->width;
int height = imageOut->height;
int bpp = imageOut->nChannels;
for (int i=0; i < width*height*bpp; i+=bpp)
{
imageOut->imageData[i] = i & 0xff; // some casting might be needed here
}
|
5,511,568 | 72,004,689 | Detecting active exceptions in the destructor | I have a class that is using RAII for cleanup in case something goes wrong. This means the class contains a flag, that tells it whether the work has been completed, and if this flag is not set when the constructor is called it is performing it's cleanup tasks and produces a log messages. Now I would like this class to ... | There was no way to use bool std::uncaught_exception() correctly, so it was removed in C++20. We now have int std::uncaught_exceptions().
You need to call it twice: once beforehand (e.g. in the constructor), then again in the destructor. If the second call returned a larger number, it means the destructor was called du... |
5,511,596 | 5,511,654 | How to do a widget in Qt that expands above his layout | How would you do a widget in Qt that expands above his layout without affecting it and not being a dialog.
My idea is to be like in word 2007 :
- Collapsed : http://i.stack.imgur.com/Yp90t.png
- Expanded : http://i.stack.imgur.com/Y0nNE.png
| The second one is actually a popup widget. You get what I mean? When the user press a expand button. Create a popup widget in that position.
|
5,511,650 | 5,511,752 | Implement a presistent B-Tree | I'm interested to implement a presistent B-Tree using either c++ or java, as I need to store some path expressions e.g. //scientist/person/... /[Albert Einstein].
I tried google, but I was not satisfied. Some hints on this would be very helpful, or any ideas as where to start with. The BTree must be stored on the the d... | Avoid using pointers, instead use index from a base address.
This way you can simply mmap the btree into memory and use the base address along with the index as a lookup.
If using windows look at mapview of file instead.
|
5,511,762 | 5,547,550 | Link to OS X framework with boost build | How do I link to an OS X framework using boost build? I have tried the following (in Jamroot):
frameworks_directory = "/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/" ;
lib CoreFoundation
:
: <file>$(frameworks_directory)"CoreFoundation.framework/CoreFoundation"
:
: <include>$(frameworks_directory)"CoreFoun... | The simple way:
exe Test : main.cpp : <framework>CoreFoundation ;
This is of course assuming you are using the "darwin" toolset. And have set it up correctly such that it knows about all the SDKs you have installed.
|
5,511,776 | 5,511,792 | how to use linux command in c++? | i am writing a c++ function that will parse .xml file.
i Used system("grep"); type system call to use linux command. now my problem is that i want to select more than one line in given tag. ex.
content of .xml file
====================
<state>
<text> hi this is first li </text>
<sec> dsfn sdlkf sfd </sec>
</state>
... | exec, execve or system calls: demo
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char* args[])
{
exitcode = system("xsltprox textonly.xslt input.xml > output");
// exitcode = exec("xsltproc", "textonly.xslt", "input.xml");
int exitcode;
}
Proceed to fopen output (or std::fstream reader("ou... |
5,511,883 | 5,511,911 | How can I print a blank char using printf? | I'm currently using the following code to print the elapsed time (in seconds) on the screen:
for(int i = 1; i < 20; i++)
{
char cheese[0];
if(i < 10)
{
cheese[0] = '0';
}
else cheese[0] = '\0';
system("CLS");
printf("%c%i", cheese[0], i);
Sleep(1000);
}
I would like to ... | Use something like:
printf("%02i", i);
This will always produce at least two digits, with leading zeros if necessary.
If you wanted to pad with a space instead of zero, you should use:
printf("%2i", i);
Would produce:
1
2
10
Not recommended:
If you wanted to do that without using the size specifier in the format s... |
5,511,973 | 5,512,511 | undefined reference to vtable | i have a class afporoills that helps find data in our memory managment module. (dont ask why such a wierd name i have no idea)
class afporoills{
void** test(int pos);
};
void** afporoills::test(int pos){
int x=(pos<<3)|1023*x;
void** ret=(void**)x;
if((int)ret%16) return this.test(pos+1);
void* (*fp... | It is likely you got this error because you declared a virtual method in the Base class and did not define it, i.e no function body for the virtual function supplied in base class.
Try giving it some dummy body and compiling it might just work. I got this error just recently in a similar scenario that got fixed by prov... |
5,512,024 | 5,513,189 | Assert fires in boost::intrusive_ptr when used in a container | I have a Producer-Consumer arrangement to process events coming from the network. A Dispatcher gives work to multiple EventHandler threads via a mutex protected queue owned by the worker thread. The event objects placed in the queue use boost::intrusive_ptr
class Event { ... }
typedef boost::intrusive_ptr<Event> EventP... | Look at intrusive_ptr docs:
http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/intrusive_ptr.html#indirection
In order to dereference it, it must hold a non-NULL pointer.
|
5,512,058 | 5,512,230 | VTable and Polymorphism | After reading alot about VTables, I still have one unanswered question.
Given the next class:
#include <iostream>
using namespace std;
class Shape {
public:
int* a;
Shape(){
cout<<"default Shape ctor"<<endl;
a = new int(15); // default
}
Shape(int n){
a = new int(n);
c... | What you're missing is that s points to a Circle -- and the Circle contains a data member called b. When s->draw(); is called, the compiler calls Circle::draw(), as you recognise, and within Circle::draw(), the type of *this (i.e. the current object) is Circle not Shape. So Circle::draw() has access to b.
EDIT: In answ... |
5,512,154 | 5,516,038 | Replacing data in binary file with fstream and seekp | I'm writing a method to replace a specified string from a binary file and it writes NULLs before the position I set with seekp, then writes the string and closes the stream. I only want to replace some bytes in the file. Before this piece of code I tried out with ofstream with ios::binary and ios::out flags. What's wro... | I know this sounds silly, but the only way to open a file for writing
and not to truncate it is to open it for reading as well: if you're
really doing ios::in | ios::out | ios::binary, it should work. (But
since you obviously reentered the code, and didn't copy/paste it, I'm
not sure if this is really what you did.) ... |
5,512,254 | 5,512,480 | Safely contain arbitrary data in a smart pointer | First off: I searched half the web to find an answer with this as a solution that came closest. It is, however, too heavyweight for me though so I am looking a little less complex.
Well then, some context: I am building a system which should be able to process incoming messages from a queue and then store the outcome o... | Normally polymorphism is used for a system like this; any item that can be put in the Outbound queue derives from QueueItem and the queue contains QueueItem* or a smart pointer to a QueueItem.
Since the items all derive from a common base, you can safely delete the QueueItem* or allow a smart pointer to handle it. This... |
5,512,255 | 5,512,703 | How do I use a C# library in C++ OpenCV project with a VB.net GUI? | I have developed an application written in unmanaged C++ that makes use of OpenCV and till now have just been using the built in highgui lib to display the results.
Together with VB.net developer I would now like to package it into a product suitable to sell.
The two enhancements I have decided to make are add a GUI, a... | Is it possible in your situation to implement some simple, high level API of your OpenCV native code, so that it is easly interoperable with C# using PInvoke? I had similar problem in the past, what I did was to pack my native code with about 15 functions that were easly usable from C# (using PInvoke). I don't know if ... |
5,512,551 | 5,512,674 | how to make pattern for grep command on linux? | I hav to grep a file whos content is as follw:
bla bla bla
this is not requred
above is my simple text file content. from which i need to get each line containing and line next to this line.
that is in above case i need first 2 lines. how i can get them using grep command?
| I think you mean
grep -A1 wekobj inputfile
If not, you mean
man grep
and you should go over to https://unix.stackexchange.com/
|
5,512,895 | 5,512,933 | gdb cannot step into printf | here is my sample program:
#include<stdio.h>
int main()
{
printf("hello good morning \n");
return 0;
}
gcc -Wall -g temp.c
/opt/langtools/bin/gdb a.out
HP gdb 3.3 for PA-RISC 1.1 or 2.0 (narrow), HP-UX 11.00.
Copyright 1986 - 2001 Free Software Foundation, Inc.
Hewlett-Packard Wildebeest 3.3 (based on GDB) is cov... | This means there's no available source/debug symbols for printf. You can use stepi to step into printf anyway, you'll only have disassembly available (use the disas command).
|
5,512,910 | 5,513,109 | explicit specialization of template class member function | I need to specialize template member function for some type (let's say double). It works fine while class X itself is not a template class, but when I make it template GCC starts giving compile-time errors.
#include <iostream>
#include <cmath>
template <class C> class X
{
public:
template <class T> void get_as();
}... | It doesn't work that way. You would need to say the following, but it is not correct
template <class C> template<>
void X<C>::get_as<double>()
{
}
Explicitly specialized members need their surrounding class templates to be explicitly specialized as well. So you need to say the following, which would only specialize t... |
5,513,451 | 5,513,566 | C++ how to know if number ends with some bit pattern | I want to know if a number ends with some predefined bit patterns.
for example
i want to know if a number N end with B
where, N is any number
and B is also any number
for example
if N = 01011100
B = 100 then this C++ function should return 1 here in this case 1
if N = 01011100
B = 101 then this function shoul... | For the first case:
unsigned n = 0x5C;
unsigned m = 0x7; // "mask"
unsigned b = 0x4;
if ((n & m)==b) {
...do something...
}
Here's how it works:
01011100 n
00000111 m
00000100 n & m (bitand operator)
00000100 b
|
5,513,532 | 5,515,550 | Reading binary istream byte by byte | I was attempting to read a binary file byte by byte using an ifstream. I've used istream methods like get() before to read entire chunks of a binary file at once without a problem. But my current task lends itself to going byte by byte and relying on the buffering in the io-system to make it efficient. The problem i... | The >> extractors are for formatted input; they skip white space (by
default). For single character unformatted input, you can use
istream::get() (returns an int, either EOF if the read fails, or
a value in the range [0,UCHAR_MAX]) or istream::get(char&) (puts the
character read in the argument, returns something whic... |
5,513,545 | 5,513,626 | Template & memory-allocation | #include <iostream>
template<class T> T CreateArray(T a, int n)
{
a = new T [n]; // mistake: double* = double**
return a;
}
int main()
{
double* a;
int n = 5;
a = CreateArray(a,n);
return 0;
}
can I allocate memory using a template and new? And what my mistake?
| Your code has some wrong things. First, you can do something like what you're trying to do, but you should write something like this:
template<class T> T* CreateArray(int n)
{
T* a = new T [n];
return a;
}
int main()
{
double* a;
int n = 5;
a = CreateArray<double>(n);
return 0;
}
Note that you... |
5,513,654 | 5,514,248 | How to set breakpoint at the very beginning of program execution | How can I stop the program before loading any of the linked DLLs?
I've tried to set LoadLibraryExW function in the Break At Function debugging option and it stops at that function, but before that I have the following in Visual Studio output windows:
'test.exe': Loaded 'C:\Windows\System32\ntdll.dll', Symbols loaded (... | You can do this by adding a registry key to "Image File Execution Options" with the name of your exe. Add a value of type string named "Debugger" and set it to vsjitdebugger.exe to launch the just-in-time debugger dialog. Which then lets you pick one of the available debuggers, including Visual Studio. This dialog i... |
5,513,718 | 5,513,888 | How do I convert from LPCTSTR to std::string? | I have an LPCTSTR and want to call a function that takes a std::string parameter.
What conversion do I need to do?
| Tip of the iceberg
LPCTSTR can be either a single-byte or a multibyte string (depends on the UNICODE constant being defined during compilation or not), while std::string's users (including your function) normally use it to hold a single-byte string.
You 'd need two conversions: one for LPCSTR (non-UNICODE build) and on... |
5,513,881 | 5,513,928 | Meaning of = delete after function declaration | class my_class
{
...
my_class(my_class const &) = delete;
...
};
What does = delete mean in that context?
Are there any other "modifiers" (other than = 0 and = delete)?
| Deleting a function is a C++11 feature:
The common idiom of "prohibiting copying" can now be expressed
directly:
class X {
// ...
X& operator=(const X&) = delete; // Disallow copying
X(const X&) = delete;
};
[...]
The "delete" mechanism can be used for any function. For example, we
can eliminate an und... |
5,514,152 | 5,599,236 | Linker issues in C++ / ObjC | I'm porting a sizeable codebase to iOS. The simplified version of my scenario is as follows:
I have a C++ library, built from the command line. I can run code from it from the iOS simulator, so I believe it's correctly built.
I have the skeleton iOS application created by Xcode
I want to add logging to the C++ libra... | I was able to fix this by using libtool instead of ld, passing it -framework Foundation, and passing -fobjc-abi-version=2 to gcc.
|
5,514,471 | 5,514,498 | XML file from internet and Qt | I want to parse some XML-file in Qt, but that file is located at some server in web. When I used QML I was able to use XMLHttpRequest class which takes address of file in internet (what I do need).
I have only one idea: use network request and download that xml directly. The idea is maybe there is a special interface i... | As I know, you should download it. QHttp provides easy way to download it to a temporary file.
QTemporaryFile temp_file;
QHttp http("example.com");
http.get("/your.xml",&temp_file);
New version (based on QNetworkAccessManager):
QNetworkAccessManager * manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(... |
5,514,583 | 5,514,660 | C++: I have this config class that I want to use between all my CPP files, how do I initialize it? | class Config
{
public:
static int OUTPUT_TO_FILE;
static int NEED_TO_TRAIN;
static int NO_FILE_TRAIN;
static int NEED_TO_TEST;
}
Above is my header.h file (i followed: http://weblogs.asp.net/whaggard/archive/2004/11/05/252685.aspx)
and I want to be able to do things like Config.OUT... | Header (Config.h):
#pragma once
class Config
{
public:
static int OUTPUT_TO_FILE;
static int NEED_TO_TRAIN;
static int NO_FILE_TRAIN;
static int NEED_TO_TEST;
};
Source (Config.cpp):
#include "Config.h"
int Config::OUTPUT_TO_FILE = 0;
int Config::NEED_TO_TRAIN = 0;
int Config::NO_FILE_TRAIN = 0;
int Config::... |
5,514,980 | 5,515,715 | C++ dynamically show or hide FLTK widgets? | I'm new to C++ and never used macros before but I beleive they may allow me to solve the following problem although I would welcome alternative solutions.
I have written the following macro:
#define COMMAND(NUMBER){ button_ ## NUMBER ## ->hide(); }
and I want to call it like this
for (int i = 1; i < 10; i++)
{
COM... | I'm pretty sure there is a way to make a macro trick work, but there are better options.
You can, for example, store your buttons in an array.
Assuming your buttons have a type called struct button, declare your buttons like this:
struct button *buttons[42];
You need to initialize all of them as you would have for you... |
5,515,700 | 5,515,854 | How to properly update vertex buffers in DirectX 10 | For a little background: I am working on a project in C++ in which I am trying to draw 3D representations of objects based on real time profile data. The profiling data is gathered from external profiling hardware. The system travels along an object and at a rate of 300 times per second provides my software with a pr... | You can always update the points within a vertex buffer as long as you make the buffer dynamic (specify D3D10_USAGE_DYNAMIC and use ID3D10Device::CopySubresourceRegion to update only parts of the buffer efficiently). That should be more efficient than re-creating buffers too frequently.
Having different sizes for each... |
5,515,784 | 5,515,833 | is this invalid C++? | struct HybridExpression {
RawExpressionElement *ree;
ExpressionNode *en;
};
vector<HybridExpression> hexpression;
hexpression.insert(hexpression.begin() + starti,
(HybridExpression) {NULL, en});
gcc builds without warning but visual studio 2010 wont even compile it.
It doesnt like this bit: (Hy... | This is using a part of the C programming language that is not included in C++, it's called "compound literal". g++ -ansi will diagnose this, saying
warning: ISO C++ forbids compound-literals
This is not a part of C++0x.
The C++0x compatible syntax would have been
hexpression.insert(hexpression.begin() + starti, Hybr... |
5,515,883 | 5,515,896 | C++ -- where does the system store the returned characters? | #include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
const char* funA()
{
return "aa"; // where does system to store this temporary variable?
}
// this is not an valid function
const char* funB()
{
string str("bb");
return str.c_str();
}
int _tmain(int argc, _TCHAR* argv[])
{
... | "aa" is a string literal, so it has static storage duration. That means it exists from when the program starts to when it ends. It isn't explicitly allocated on the stack or on the free store (heap).
The only temporary object there is the pointer to that string literal, which is returned by value (that means a copy o... |
5,515,892 | 5,516,543 | Undefined symbols when linking with g++? How do I solve this? | my make file:
all: hPif clean
hPif : src/main.o src/fann_utils.o src/hashes.o src/Config.o
g++ src/Config.o src/main.o src/fann_utils.o src/hashes.o -lfann -L/usr/local/lib -o hPif
Config.o : src/Config.cpp src/Config.h
g++ -c src/Config.cpp
hashes.o : src/hashes.cpp src/hashes.h
g++ -c src/hashes.cpp
... | I refer you to the accepted answer in the other question where the static variables are properly defined:
Source (Config.cpp):
#include "Config.h"
int Config::OUTPUT_TO_FILE = 0;
int Config::NEED_TO_TRAIN = 0;
int Config::NO_FILE_TRAIN = 0;
int Config::NEED_TO_TEST = 0;
Note the Config:: qualification to the variable... |
5,516,044 | 5,516,161 | System where 1 byte != 8 bit? | All the time I read sentences like
don't rely on 1 byte being 8 bit in size
use CHAR_BIT instead of 8 as a constant to convert between bits and bytes
et cetera. What real life systems are there today, where this holds true?
(I'm not sure if there are differences between C and C++ regarding this, or if it's actually l... | On older machines, codes smaller than 8 bits were fairly common, but most of those have been dead and gone for years now.
C and C++ have mandated a minimum of 8 bits for char, at least as far back as the C89 standard. [Edit: For example, C90, §5.2.4.2.1 requires CHAR_BIT >= 8 and UCHAR_MAX >= 255. C89 uses a different ... |
5,516,098 | 5,516,130 | Pointer in copy constructor | I have a copy constructor that looks like this:
Qtreenode(const QtreeNode * & n) {
x=n->x;
y=n->y;
height=n->height;
width=n->width;
element=n->element;
}
I wrote this a week ago, and I looked back at it today and I was surprised by the line that when called the copy constructor with say swChild=n... | That is not a copy constructor. A copy constructor for a class is a constructor that takes a reference of the class's type. Any of the following would be copy constructors, though the second, taking a const reference, is by far the most commonly used:
QTreeNode(QTreeNode&);
QTreeNode(const QTreeNode&);
QTreeNode(vola... |
5,516,293 | 5,516,850 | Controlling visibility of enum values | Consider a C++ class that exports an enum, maintains an internal array over that enum, and wants to export a command that accepts values from the enum.
class foo {
public:
enum color {
red,
yellow,
green,
NUM_COLORS
};
private:
something somebody[NUM_COLORS];
public:
void command(color c);
};
I... | My first thought would be to try and solve the problem as you lay it, but after a bit reflexion, I would shift the burden to command:
void command(color c) {
assert(0 <= c && c < NUM_COLORS && "Invalid argument");
}
Since enums are so weak types, you need to check the input anyway, as anyone could easily provide cra... |
5,516,365 | 5,528,118 | Interesting stdext::hash_value() implementation | I was trying some hashing algorithms with stdext::hash_value() on VS2010 and realized this:
#include <iostream>
#include <xhash>
using namespace std;
int main()
{
#ifdef _WIN64
std::cout << "x64" << std::endl;
#else
std::cout << "x32" << std::endl;
#endif
std::cout << stdext::hash_value(345.34533) << std... | stdext::hash_value isn't a hash function. It's the input to a hash function, you specialize it for your type so that it can be used as a key for the stdext hash classes. There doesn't seem to be any documentation for it however. The actual hash function is stdext::hash_compare.
But because there is no default specia... |
5,516,500 | 5,516,649 | IPv6 address problem in `ifreq` struct | I am working with the following code:
struct sockaddr_in6 *sin;
struct ifreq ifr;
sin = (struct sockaddr_in6 *)&ifr.ifr_addr;
ifr_addr is of type struct sockaddr, which for convenience is reported here under:
struct sockaddr {
sa_family_t sa_family; /* address family, AF_xxx */
char ... | Fortunately struct ifreq is declared to contain the addresses in a union at the end of the structure:
struct ifreq
{
union
{
char ifrn_name[16];
} ifr_ifrn;
union
{
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
... |
5,516,574 | 5,516,740 | QPixmap::fromImage() gives segmentation fault in QX11PixmapData | I have written some code that looks more or less like this:
QVector<QRgb> colorTable(256);
QImage *qi = new QImage(lutData, imwidth,imheight, QImage::Format_Indexed8);
while (index < 256)
{
colorTable.replace(index, qRgb(2552,255, 255));
index++;
}
qi->setColorTable(colorTable);
QPixmap p(QPi... | The QImage constructor you called is:
QImage::QImage ( const uchar * data, int width, int height, Format format )
Which requires the scanline data to be 32-bit aligned. So make sure it is and also has enough bytes in it. Or you can use:
QImage::QImage ( uchar * data, int width, int height, int bytesPerLine, Format form... |
5,516,641 | 5,516,812 | Smoothing function for battery voltage display to reduce spikes in embedded system | Reading a battery voltage in an embedded device. However, the actual voltage varies greatly depending upon system load. We need a method to reduce the fluctuation of the voltage to display the best value.
Currently, we're using a rolling/moving average. However, over the last 15 readings, the result still fluctuates... | Well, it's a bit tough to tell what you need without specifics on your situation. For example, what is your sensor sampling rate, and how is the sensor fluctuation and noise that you're trying to remove characterized?
However, if you already have moving average implemented, I might recommend trying a moving median ins... |
5,516,652 | 5,516,925 | Functions with pointers | Just when I thought I had pointers down, it looks like I'm still a bit confused. I'm writing the operator= overload, so I want to deallocate memory then assign new. I'm dealing with a Quad tree class, where each tree has a pointer to root node and a root node has 4 pointers to 4 children, and those each have 4 children... | Taking away the arguments of nodeCopier, this part doesn't look right to me..
root=new QtreeNode;
root=nodeCopier( /* ... */ );
nodeCopier returns QNode (which based on your return statement is implicitly castable from QtreeNode) however from the first line we can it is being assigned to a QtreeNode*. Or put more gen... |
5,517,006 | 5,517,034 | C++ libraries for working with MySql | I'm searching for a good C++ library for MySql, I read about MySQL++ and SQLAPI++, from your experience witch one should I use from this two or is there another library that you would recomand ?
Thank you.
| A couple more to consider are SOCI and DTL. Most of the general purpose frameworks like Qt, Ultimate++, and wxWidgets include database access capabilities.
|
5,517,085 | 5,517,203 | Why this code keeps crashing | Why this code gives error:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
char x='\0',i=0;
vector<char> text;
do
{
cout<< "Enter a char" << endl;
cin>>x;
if(x<65||(x>90&&x<97)||x>123)
{
cout<<"Out of Range-Please Enter Letters"<<endl;
... | It will crash because i is a character, therefore cin will read a character. For example if someone enters a value 8, the value of i will be 38 (if you platform is using ASCII encoding).
Plus testing characters for their values is very bad practice use isalpha() from cctype header instead.
|
5,517,161 | 5,517,336 | Why does MinGW automatically include <windef.h> | I am trying to typedef DWORD in a platform agnostic manner, and I am running into the following compiler error:
...\mingw.org\mingw_gcc_4.5.0\bin\../lib/gcc/mingw32/4.5.0/../../
../../include/windef.h:229:23: error:
'DWORD' has a previous declaration as 'typedef long unsigned int DWORD'
I'd like to be able to depend ... | My MinGW doesn't seem to automatically pull in windef.h. I suspect that your program is including some other header that's indirectly pulling it in. Can you post a short program that displays the problem?
Note that I see you're using whether or not _WINDEF_H is defined to determine if these things have already been typ... |
5,517,436 | 5,517,537 | scroll clistviewctrl in wtl, when new item is added | I want to scroll to the end of the listview, when a new item is added. I'm using CListViewCtrl from WTL. Here is my function for adding a new item and scrolling:
void CMainDlg::addMessage(CString msg)
{
m_wndList.InsertItem ( n++, msg);
SIZE size;
size.cx = 0;
size.cy = n;
m_wndList.Scroll(size);
}
... | Yep, you scroll by pixels. Use the EnsureVisible function instead (it sends LVM_ENSUREVISIBLE).
|
5,517,513 | 5,517,612 | Logging in multithreading environment and testing | Please let me know your suggestions about how to design logging and how to test it, in the following scenario.
I've an API which can be called by multiple threads. One call of this API by a single thread generates a log of 50 KB.
Does any design pattern exist for logging in multi-threaded environment. i.e one log file ... | Wrap your logging instance in a thread-safe singleton. Don't use double check locking! Also, it probably makes sense to use a logging library like log4net or Enterprise Library 5.
|
5,517,615 | 5,517,869 | Counting number of same values in map | is there any command that counts the number of same values in a map?
like:
map<int, string> m;
m[1] = "A";
m[22] = "A";
m[53] = "C";
m[12] = "A";
m[6] = "A";
int count = m.count("A");// 4
or should i just write it myself, since its not too hard?
| You can use std::count with a custom value parameter:
struct Compare {
std::string str;
Compare(const std::string& str) : str(str) {}
};
bool operator==(const std::pair<int, std::string>&p, const Compare& c) {
return c.str == p.second;
}
bool operator==(const Compare& c, const std::pair<int, std::string>&p)... |
5,517,679 | 5,517,868 | Error: Conversion from derived* to base& | Although I made the members of both base and derived classes public, Why does the conversion says that it is inaccessible?
class B
{
public:
int var;
};
class D: private B
{
public:
int var;
};
int main()
{
D d;
Base &b = d; //my error
}
| You can't convert from a derived class to a non-public base class (well, outside the class itself anyway). Private inheritance is typically used as a form of composition, not for substitution so there's no need to convert to the base. In your case it looks like you want substitution so you should use public inheritance... |
5,517,698 | 5,518,008 | Check for "self-assignment" in copy constructor? | Today in university I was recommended by a professor that I'd check for (this != ©) in the copy constructor, similarly to how you should do it when overloading operator=. However I questioned that because I can't think of any situation where this would ever be equal to the argument when constructing an object.
He a... | Personally, I think your professor is wrong and here's why.
Sure, the code will compile. And sure, the code is broken. But that's as far as your Prof has gone with his reasoning, and he then concludes "oh well we should see if we're self-assigning and if we are, just return."
But that is bad, for the same reason why ... |
5,517,756 | 5,518,837 | Program is Killed During Testing | When I run my program I get the message Killed with some information about the script. After doing some research on the problem, I found out that I wasn't deleting my dynamically allocated variables (stupid me!). However, Now, I feel like I have taken care of that problem but I am still getting the Killed message in ... | In the exhibited code you are calling new and then delete four times on objects of two types. That looks pretty good if the destructors of Array_HashTable and LinkedList_HashTable are correctly freeing any memory allocated by their objects.
If you are still leaking memory from this code, those objects would be my first... |
5,517,786 | 5,517,833 | Why am I getting linker issues when passing a c-style array to a method expecting a std::string? | I have a Logger class which is expecting a std::string in the following way:
class Logger
{
public:
void Log(const std::string message);
};
And another class is calling it as:
class MyClass
{
public:
void MyMethod()
{
Logger logger;
logger.Log("Hello World!"); // This line is causing linker... | Your problem is that you haven't defined the Log (aka Logger::Log) method. You've declared it, but not defined it anywhere.
Another small issue is that you really ought to declare it like this:
void Log(const ::std::string &message);
There is no particularly good reason to force callers to make a copy of the string th... |
5,517,799 | 5,518,011 | STLPort ambiguous copy constructor in VS2008 with smart pointer class | We've written a smart pointer class and have been using it with great success with the built-in Visual Studio STL implementation.
The problem is we've realized our performance bottlenecks are in the STL library in code ported from Linux (where the STL is significantly faster the way we're using it). So I'm trying to l... | It's actually your operator& that's causing ambiguity. In g++ the ambiguity is in destruct rather than construct but I assume it's a similar problem.
The compiler tries to take the address of your T to construct/destruct it, and gets back a T** instead of a CRefCountPtr<T>*, causing confusion.
I bet you could create yo... |
5,517,892 | 5,518,367 | Is there any way to take array size from user in c++? | i want to know if there is a way to take size of a dimentional array from user?
for example for size of a matrix i have tried to definition a pointer,and after takeing size of matrix make memory.
this is: `
void getMatrixSize(&int,&int);
void makeMatrix(int **mat,int,int);
void getMatrixData(int **mat,int,int);
... | Other than your use of cin and cout, your code reads like C, not C++.
There is no notion of the size of an array in C++. The way that you're doing it, you'll have to keep track of it manually, so if you plan to write matrix code in C++, I would suggest that you implement Matrix as a class, that you seriously consider u... |
5,518,083 | 5,518,208 | What is a 'linkonce' section | What is a 'linkonce' section, and for extra kudos how does it differ from a comdat section?
To be clear, I'm familiar with how comdat sections work, how they're used, etc. In googling, linkonce is almost exclusively discussed in forums where it's assumed the meaning/intent/purpose of that section is already fairly wel... | https://gcc.gnu.org/legacy-ml/gcc/2003-09/msg00984.html seems to discuss this very thing.
According to that thread, COMDAT is a bit more nebulous in the sense that there's no single correct/standard definition of what constitutes a true COMDAT implementation. g++'s linkonce is /an/ implementation of the concept.
In th... |
5,518,129 | 5,518,184 | What's a need for union { } in C++? |
Possible Duplicate:
C/C++: When would anyone use a union? Is it basically a remnant from the C only days?
Hi all.
What are the reasons for unions to exist in C++? And what are they, actually?
I found this code:
#include <iostream>
using namespace std;
union mixture {
short number;
char symbol[2];
main() {
... | The union lets you treat your data as either char or short without having to cast. Casting pointer between types can produce type-punning errors in the optimizer and generate incorrect output.
EDIT: For an example, I use unions to byte swap doubles and floats after reading them from a file. If you read byteswapped floa... |
5,518,172 | 5,518,355 | Is it acceptable to use a hidden window in a server application on Windows? | I'm thinking about using WSAAsyncSelect in a server. But then I need a window to receive the message.
Is such a (hidden) window acceptable in a server app without a GUI? Can it lead to unexpected problems?
| Using a hidden window is probably ok, or even better, use a message only window.
Is there any reason why you can't use WSAEventSelect and events instead?
|
5,518,553 | 5,518,822 | Screen Scroll in a game | I am trying to get my game to scroll as a player along the y axis and the x axis.
Currently the coordinate systems of the window is out. :(
I am using the following line in openGl to scroll:
float tempX=px1;
float tempY=py1;
double left = tempX-screenWidth/2;
double right = screenWidth/2+tempX;
double bottom = tempY ... | Something like this?
#include <GL/glut.h>
#include <map>
using namespace std;
size_t win_w = 0;
size_t win_h = 0;
void Box( int xoff, int yoff, int size = 10 )
{
glBegin(GL_QUADS);
glVertex2f( xoff + -1*size, yoff + -1*size);
glVertex2f( xoff + 1*size, yoff + -1*size);
glVertex2f( xoff +... |
5,518,940 | 5,519,112 | How to get collision detection of circle and triangle | I have one triangle ad one circle moving objects on plane.How will i know both of them are collide to each other. ?
| Circle - triangle interesction test is what you want
http://www.phatcode.net/articles.php?id=459
|
5,519,335 | 5,519,346 | My Simple String Implementation Gone Wrong | I am creating my simple implementation of the String class like in the .Net framework. The only difference, it is less sugary if you know what I am mean. Anyhow, I got it everything to work except for the overloaded operators for the + operator; which end up displaying a garbage buffer. I still have not implemented exc... | Your str is a local variable in your operators - as soon as you return from the operator, str is destroyed, and the pointer you return points to deleted memory (the local str variable owns the memory that c_str() returns a pointer to). If you e.g. return a std::string instead of a const char * the value in str will be ... |
5,519,343 | 5,519,374 | error: invalid declarator before ‘&’ token | I was trying to write a TextQuery program that allow user:
1. inputs a word
2. reads a file
3. prints out which lines the words appear and how many times the word appears on that line.
I created a class called "TextQuery" with 3 member functions:
1. "read_file" to read the file and return a reference to a vector ... | Missing ; after the class definition.
Why the weird error message? Because it's entirely legal to create an object at that level of scope:
class ABC {
...
} globalABC;
|
5,519,688 | 5,524,830 | Kinect and Opencv, the depth image, how to use it | I've using Kinect and OpenCV (I am using c++). I can get both the RGB and the depth image.
With the RGB image I can "play" as usual, blurring it, using canny (after converting it to greyscale),... but I can't do the same with the depth image. Each time I want to do something with the depth image I got exceptions.
I hav... | The problem was that the output from cvGetImage is 16bits depth while canny requires 8bit, therefore I need to convert it to 8bits, something like:
cvConvertScale(depthMetersMat, kinectDepthImage8, 1.0/256.0, 0);
|
5,519,730 | 5,519,917 | std:map iterator returns badptr on find | I have my std::map defined as
typedef std::map<string,ImageData*> ImageDataMap;
typedef std::pair<string,ImageData*> ImageDataPair;
typedef std::map<string,ImageData*>::iterator ImageDataIterator;
The above map stores string which is an image file name and ImageData which is the the image metadata. When i use the fin... | An iterator returned as map::end by map::find() means that the specified key was not found in the container. You cannot dereference it to access its elements. It will crash your application.
EDIT:
Let's be clear. The problem is that you are inverting the logic, ok? You can only use an iterator if it's valid, therefore ... |
5,519,767 | 5,519,817 | Wrapping the Dialog Procedure | I've been using the standard method for wrapping dialog procedures, by using a static dialog procedure in a class, and pure virtual dialog procedure that is derived later on. This works perfectly, but I have some design questions. Consider the definition of my static dialog procedure:
INT_PTR __stdcall ModalDialog::rou... | This gives you less flexibility - It'd be better to call event handlers from the virtual dialog procedure, allowing you to override the behavior for individual subclasses. If you want these "event handlers" to be called by default for all subclasses of ModalDialog, simply don't make the virtual dialog procedure pure vi... |
5,519,824 | 5,519,905 | Cannot access memory at address error | I'm getting this error:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000407265 in Quadtree::deeper (this=0x7fffffffe430,
orig=@0x7fffffffe430, n=@0x7a1da0, tol=Cannot access memory at address 0x7fffff3feffc
) at quadtree.cpp:47
47 int Quadtree::deeper(QuadtreeNode * & orig, QuadtreeNode * & n... | My best guess: you are seeing a stack overflow (What a coincidence, given the site we're on! :). I can't explain why Valgrind isn't catching it though: usually Valgrind uses the same stack size as the OS (at least on my system).
What this error means is that your code tried to access memory at address 0x7fffff3feffc ... |
5,520,111 | 5,520,228 | So I can't dynamic_cast< functionPointer >( ((void*)(myFuncPtr)) )? What should I do? | I have a base class, Parameter, and two derived classes: Scalar & Vector. In each derived class, I have a member function which takes a function pointer as input:
In the Scalar class:
typedef double (*samplerType)(RandNum& rnState);
void RegisterSampler( samplerType input );
In the Vector class:
typedef std::vector<d... | Aside from the design flaw that James points out, it's true that you can't cast from a function pointer to a normal void* pointer. You can however cast between function pointers of arbitary types (free-to-free, member-to-member):
typedef void (*samplerType)();
// in base class ...
samplerType sampler_;
template<class F... |
5,520,235 | 5,520,309 | Error: Function not declared in this scope. Help? | Here is (part of) my code:
...
Node<char*>* nodes[count2];//array of pointers to last level
nodes[0] = f1.rootPtr;
processInput(input, f1.rootPtr, nodes, 0, count2);
//I get an error that says this function is not declared in this scope.
return input;
}
void processInput(istream& input, Node<char*>... | You need to prefix your class functions with the name of their class, do you do that currently? If not, the compiler thinks that they are free functions.
For example,
void processInput(istream& input, Node<char*>* node, Node<char*>** nodeArray,
int level, int& count) {
// ...code...
}
should be
void Forest::pr... |
5,520,269 | 5,520,277 | passing std::vector to a function which modifies an input array | I'm using a third-party API (CryptEncrypt, to be precise) which takes a C array as an in-out parameter. Logically, the API boils down to the following function:
void add1(int *inout, size_t length)
{
for(size_t i = 0; i < length; i++)
{
inout[i] += 1;
}
}
I'm trying to avoid the use of raw arrays, so my que... |
Can I use the 'contiguous storage' guarantee of a vector to write data to it?
Yes.
I'm inclined to believe that this is OK
Your inclination is correct.
|
5,520,429 | 5,520,464 | How can I define a template class which gives the pointer depth/level of a type? | How can I define a template class which provides an integer constant representing the "depth" of a (pointer) type provided as the input template argument? For example, if the class was called Depth, the following would be true:
Depth<int ***>::value == 3
Depth<int>::value == 0
| template <typename T>
struct pointer_depth_impl
{
enum { value = 0 };
};
template <typename T>
struct pointer_depth_impl<T* const volatile>
{
enum { value = pointer_depth_impl<T const volatile>::value + 1 };
};
template <typename T>
struct pointer_depth
{
enum { value = pointer_depth_impl<T const volatil... |
5,520,584 | 5,520,610 | Call Function from Dynamic Library | What would be the best way to, if possible, load a dynamic library and call one of it's functions, when we don't know the name of the function during compile-time?
For example, is there a way to make a program that reads a string from a file and then loads a DLL and searches for and calls a function with its name being... | There is an example on Wikipedia of all places showing how to use the LoadLibrary() function at runtime. You will see that the function name is specified as a string. You would need to write the code to search for the function name and pass it to similar code.
On Linux you can do this with dlopen() and dlsym() function... |
5,520,591 | 5,520,813 | Overallocating with new/delete | Using malloc and free, it is easy to allocate structures with extra data beyond the end. But how do I accomplish the same with new/ delete?
I know I could use placement new syntax along with malloc for the allocation part, but will delete work properly and portably if I place an object in memory allocated by malloc?
W... | If I were you, I'd use placement new and an explicit destructor call instead of delete.
template< typename D, typename T >
D *get_aux_storage( T *x ) {
return reinterpret_cast< D * >( x + 1 );
}
int main() {
char const *hamburger_identity = "yum";
void *hamburger_room = malloc( sizeof( Hamburger )
... |
5,520,882 | 5,520,914 | Instantiating a c++ class in x86 (32bit) assembly (Passing a c++ class by copy to a method in assembly) | In my project, I have, amongst many other things, to call a c++ method from assembly and to pass a class by copy. It would be quite simple if I could pass it by reference, but I cannot.
I assume it would look something like this:
create a new instance of said class;
copy the attributes of the class to the attributes of... | Creating a class object isn't much different from creating a normal stack variable. You just need to call the (copy-)constructor.
You make space on the stack for the local class object, push the object to create the copy from on the stack (as the argument for the copy ctor), pass the address of the local space1) and fi... |
5,521,003 | 5,521,123 | How to get full path of a window in Windows Explorer | When I have to open a folder in Windows Explorer (for example d:\myfolder\test), I use ::GetForegroundWindow() to get its Window Handle, and use ::GetWindowText to get the Title Text. But in the default windows the full path of the current window is not displayed (of course you can through tools-folder option-view-disp... | By using the ShellWindows COM object. See this example on how the get the folder that an Explorer window is viewing.
|
5,521,039 | 5,521,051 | Better to allocate on the stack or heap within a class | This was more of a conceptual question, but I'll provide a particular instance where I'm wondering about this. If I have a class that has several objects as properties, is it better to allocate them statically within the class, or dynamically during construction? For example, I have the following class (unecessary code... | Wherever possible, you should avoid explicit dynamic allocation. Dynamic allocation is relatively expensive and makes object lifetime management more difficult.
Note that your question is somewhat misleading: in the first case, BaseText and BackgroundText aren't necessarily allocated on the stack. If the OutlinedTex... |
5,521,146 | 5,521,163 | What is the best, most accurate timer in C++? | What is the best, most accurate timer in C++?
| The answer to this is platform-specific. The operating system is responsible for keeping track of timing and consequently, the C++ language itself provides no language constructs or built-in functions for doing this.
However, here are some resources for platform-dependent timers:
Windows API - SetTimer: http://msdn.mi... |
5,521,208 | 5,521,275 | Forward declare possible typedef c++0x | I understand from the answer to the question Forward declare a class's public typedef in c++, forward declaring something which may be typedef is impossible in C++.
Is it possible to do what this question asks in C++0x?
Otherwise, making changes like:
class X {...};
typedef X Z;
to
class Y {...};
typedef Y Z;
breaks ... | Assume that headers are included at the "head" of the user's sources and that they won't forward declare your classes. If users want a lighter-weight header, give them one.
The Standard Library includes one header consisting of forward declarations, <iosfwd>. You might adopt or adapt that convention, for example "foo_f... |
5,521,470 | 5,521,500 | Class Templates Partial Specialiazation | The following code compiles successfully, and I fail to understand why:
#include <stdio.h>
#include <vector>
#include <iostream>
// Template definition
template <typename T1, typename T2> class stack
{
};
// Template specialization
template <> class stack <float, float>
{
};
int main ()
{
stack <char, char> objSta... | Template specialization is for when you want to do something specifically different for specific template parameters. The compiler will instantiate anything non-speficied from the original template.
This is useful for when you want different behavior for a specific data type, but can also be used for more complex patte... |
5,521,578 | 5,521,623 | Peeking at a UDP message in c++ |
I'm trying to receive a UDP message using sockets in c++.
I'm sending the size of the message in the header, so I can know how much memory should I allocate, so I try to peek at the beggining of the message like this:
int bytesRead = recvfrom(m_socketId, (char*)&header, Message::HeaderSize, MSG_PEEK, (struct sockadd... | Given that the maximum size of a UDP packet is 65507, you could just allocate a single 64k 'bounce buffer' for all your recvfrom() calls -- once you've copied it in, read the size, allocate a new buffer, and make a copy of your packet at exactly the right size.
It is a little wasteful to be copying packet data around s... |
5,521,838 | 5,524,230 | Sending a keyboard buffer via Winsock | Now I'm new to the WINSOCKs, and not super fluent in C++, so bear with me. I've written a NetworkServer and NetworkClient class, mostly based off of the MSDN tutorials. The client will be sending the server a char array of size 256, containing the state of each standard keyboard button (0 means the key is not being pre... | Problem ended up being how I was assigning the values in the keyBuffer. I was doing
void key(unsigned char key, int x, int y)
{
player.keyDown[key] = 1;
}
Instead of
void key(unsigned char key, int x, int y)
{
player.keyDown[key] = '1';
}
|
5,521,892 | 5,531,308 | How can I use the flex lexical scanner generator as part of my program? | How can I use a scanner I've written using Flex as part of a program I'm designing? Specifically, within a c++ class as a method of the class, and from a separate file with just a main method to perform testing.
I don't wish to use the %option c++, but will compile with g++.
To answer the problem of how to test the sc... | The simplist example I have is:
mylex.l
%option noyywrap
%%
: return ':';
%%
main.cpp
#include <stdio.h>
#include <iostream>
extern "C"
{
extern int yylex(void);
extern FILE* yyin;
}
int main()
{
yyin = fopen("plop", "r");
std::cout << yylex() << "\n";
}
Then to build:
> flex -o mylex.... |
5,521,983 | 6,454,056 | How can an int be an AssetManager? | Why does this work?
AssetManager* am = (AssetManager*)env->GetIntField(obj, gAssetManagerOffsets.mObject);
env->env->GetIntField() returns an Int. Why can it be converted to an AssetManager? This code is from the file android_util_AssetManager.cpp.
| The int being returned is a pointer to an AssetManager. The (AssetManager*) tells you that it's a pointer to an AssetManager.
So, it's returning an int, which happens to be a pointer to an AssetManager. It's not returning an AssetManager.
This Tutorial on Arrays and Pointers in C might help you. Chapter 5 shows the... |
5,522,008 | 5,522,649 | Is the code in "The C++ Programming Language Third Edition" on page 854 correct? | I try to learn C++. In "The C++ Programming Language Third Edition" book I found code on page 854 (Appendix C.13.1):
template<class T> class X {
static T def_val;
static T* new_X(T a = def_val);
};
template<class T> T X<T>::def_val(0, 0);
template<class T> T* X<T>::new_X(T a) { /* ... */ }
template<> int X<i... | Don't forget to mail Stroustrup. From his homepage:
"As a small token of my gratitude to
people who report problems and thereby
help me improve the book, I offer a
reward to someone who first reports a
misspelling, a bug in a code example,
or a factual error in the text to me.
The bounty for new errors in ... |
5,522,123 | 5,522,147 | Segmentation fault when accessing a list inside a struct | I'll try to make things clear.
Here is my struct:
struct scopeList{
int id;
list<int> internal_list;
};
typedef struct scopeList scopeList_T;
Here is the code that gives me the segmentation.
int main(){
scopeList_T* t1 = (scopeList_T*) malloc(sizeof(scopeList_T));
t1->id = 5; //works fine
t1-... | Use new instead of malloc!
sopeList_T* t1 = new scopeList_T;
malloc doesn't run any constructors. When you need to release that struct, use delete rather than free - you can't free objects allocated with new (and free doesn't call destructors).
You don't need that typedef either, the struct declaration is enough.
stru... |
5,522,183 | 5,522,261 | type definition in parameter list | int func(struct x{int a;}y);
int main()
{
}
The above code gives following error in c++
error: types may not be defined in parameter types
while its run fine in c with warning,means in c type may be define in parameter list
thus the following code should give redefination error in c
int func(int a,int a);
int main()... | It's an error to have a parameter have the same name twice, because parameter names are in scope in their parameter list. I think it's obvious that having two parameters have the same name isn't useful?
// Explain why you want to have them say "int a, int a"
int func(int a, int b);
In C it is allowed to define the con... |
5,522,529 | 5,523,929 | Boost Enum 256 Element Limit | I'm using the enum v4.6 library from the Boost Vault (mentioned here [stackoverflow.com]), but have come across an element limit of 256 (that is, the max number of elements per enum = 256).
I understand this has something to do with the boost preprocessor library and some investigation led me to boost/preprocessor/conf... | Unfortunately, there is no way to increase the upper limit of elements/arguments you can use with the Boost preprocessor library. Therefore, since the enum library depends on Boost.PP you seem to be out of luck.
|
5,522,626 | 5,522,690 | Separating public interface from implementation details | I have to design a Font class that will have multiple implementations spanning platforms or different libraries (Win32 GDI or FreeType for example). So essentially there will be single shared header/interface file and multiple .cpp implementations (selected during build time). I would prefer to keep the public interfac... | You can use the PIMPL design pattern.
This is basically where your object holds a pointer to the actual platform dependent part and passes all platform dependent calls through to this object.
Font.h
class FontPlatform;
class Font
{
public:
Font();
void Stuff();
void StuffPlatform();
private... |
5,522,783 | 5,523,316 | Java Generics, support "Specialization"? Conceptual similarities to C++ Templates? | I know quite a bit how to use C++-Templates -- not an expert, mind you. With Java Generics (and Scala, for that matter), I have my diffuculties. Maybe, because I try to translate my C++ knowledge to the Java world. I read elsewhere, "they are nothing alike: Java Generics are only syntactic sugar saving casts, C++ Templ... | No, generics in Java don't work this way.
With generics you can't do anything which would not be possible without Generics - you just avoid to have to write lots of casts, and the compiler ensures that everything is typesafe (as long as you don't get some warnings or suppress those).
So, for each type variable you can ... |
5,522,913 | 5,523,078 | Does gcc optimize my cycle with condition? | I have the following cycle:
//condition will be set here to true or false
for (int i = 0; i < LARGE_NUMBER; i++) {
if (condition) {
//do foo
} else {
//do bar
}
}
Assumption: A cycle if faster without a condition than with a condition. (Is this true?)
Question: Will gcc factor out my if, i... | For those who don't wish to read a lengthy post, this optimization is called (in LLVM) Loop Unswitch.
Why not ask a compiler ?
void foo(char* c);
int main(int argc, char **argv) {
bool const condition = argc % 2;
for (int i = 0; i != argc; ++i) {
if (condition) {
foo(argv[1]);
} else {
foo(arg... |
5,522,984 | 5,523,168 | Windows folder password | I have been thinking to implement the following program, just out of curiosity and learning experience. I want to write a program for password protecting a folder, so you can only open the folder after entering the correct password. I know this is specific to the operation system, so let it be Windows. I guess this is ... | If you want a bulletproof protection of your files, then just protecting access to the folder is not enough, you'd have to encrypt them and there're secure containers and file system encyptions on the market.
If it does not need to be high security, you can hook into Windows I guess. You'll especially need to hook into... |
5,523,067 | 5,523,104 | SQLite with Android NDK | Is it somehow possible to use SQLite with C++ on an Android phone? I haven't found any documentation around how this could be possible.
| It isn't possible to use the built-in SQLite via NDK (or it wasn't six months ago when I looked into this), that can only be accessed with Java. However it may be possible to link in your own completely separate C++ build of SQLite.
|
5,523,109 | 5,523,125 | C++ define class member struct and return it in a member function | My goal is a class like:
class UserInformation
{
public:
userInfo getInfo(int userId);
private:
struct userInfo
{
int repu, quesCount, ansCount;
};
userInfo infoStruct;
int date;
};
userInfo UserInformation::getInfo(int userId)
{
infoStruct.repu = 1000;
return infoStruct;
}
bu... | You need to change the order of the members of UserInformation and put struct UserInfo above the declaration of getInfo. The compiler complains that it can't work out the signature for getInfo because it hasn't seen the definition of its return type yet.
Also, if you are returning a struct from the function the type of... |
5,523,111 | 5,523,641 | Keypress event in C++ | I'm currently using GetAsyncKeyState() to detect Keydown events, but then the events will be repeated while you are holding down the key.
What would be an easy way to stop the event from repeating?
Example
If I hold down the key i on my keyboard for a while, I will get an output like this:
iiiiiiiiiiiiiiiiiiiiiiiii
I... | Avoid using a keyboard related message like WM_KEYDOWN or WM_CHAR to detect a key, Windows repeats WM_KEYDOWN when the user holds it down. You simply need a your own bool flag that keeps track of the state of the key. Only change your game object state when you see a difference between the state as reported by GetAsy... |
5,523,182 | 5,523,690 | Is it problem with parsing/instantiating templates in VS2010? | Please don't mind the length of this code (just copy and paste). When you do it run it and it won't compile under VS2010. In order to compile this code, in struct Range remove "class IntType," from template parameters and in main instead of:
Range<int,float> r;
make
Range<float> r; //int is removed
Code:
templat... | Well it looks like the < operator throws the compiler off the wrong track. If you:
static_assert( Assign_Low_High<L>::low_value > -1, "Incorrect Range");
or
static_assert( (Assign_Low_High<L>::low_value) < 1, "Incorrect Range");
it will work.
If you do:
static_assert( Assign_Low_High<L>::low_value < 1 > 0, "Incorrect... |
5,523,227 | 5,523,268 | Efficent way of mapping bit mask values (1, 2, 4, 8, etc.) into a vector index (1,2,3,4, etc.) | I have an enmeration with a set of values which can be bitwise or'd together:
enum EventType_e
{
EventType_PING = 1,
EventType_PANG = 2,
EventType_PONG = 4,
EventType_PUNG = 8
};
I expect this enumeration to grow to contain at most 15-20 items. On receiving one of these enumerated values I would li... | Most modern CPU architectures have opcodes to discover the most or least significant non-zero bit in a number (e.g., BSF and BSR on x86). These are also available as intrinsics on some compilers, such as _BitScanForward and _BitScanReverse on Microsoft and Intel compilers.
The above bit-scan is hands-down the fastest s... |
5,523,244 | 5,523,366 | Sequence Points and Method Chaining | The following expression is often used to demonstrate undefined unspecified behaviour:
f() + g()
If f() and g() both have side effects on some shared object then the behaviour is undefined unspecified because the order of execution is unknown. f() may be evaluated before g() or vice versa.
Now I was wondering what hap... | f() + g()
Here the behavior is unspecified (not undefined), because the order in which each operand is evaluated (that is, each function is called) is unspecified.
obj.foo().bar();
This is well-defined in C++.
The relevant section §1.9.17 from the C++ ISO standard reads,
When calling a function (whether or
not th... |
5,523,562 | 5,523,901 | main.cpp|| undefined reference to `MyClass::loadDatas(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'| | I encounter a problem using std::string in parameters :
MyClass has a method like this
public:
void loadDatas(string filename);
In my main.cpp I have the following simple code :
#include <iostream>
#include <string>
#include "myclass.hpp";
using namespace std;
int main()
{
string foo = "test.txt";
co... | The problem is that you've defined class Personnage as having a member function chargerPersonnage, but in personnage.cpp you define a free function chargerPersonnage instead.
You appear to know the correct syntax, as you did Personnage's constructor and destructor correctly, but just to make it clear: Change void charg... |
5,523,752 | 5,523,769 | C++: How to pick out last quarter of elements in a vector? | What is the best way to pick out the last quarter of the elements in a vector containg N elements?
| size_t n = src.size();
std::vector<int> dest(src.begin() + (3*n)/4, src.end());
dest contains the last quarter elements from the source vector src.
You can also use std::copy from <algorithm> header file as,
std::vector<int> dest_copy;
std::copy(src.begin() + (3*n)/4, src.end(), std::back_inserter(dest_copy));
See ... |
5,523,891 | 5,523,904 | Why does sizeof(intArray)/sizeof(int) give different values? |
Possible Duplicates:
C++: sizeof for array length
Sizeof array passed as parameter
#include "stdafx.h"
#include <iostream>
using namespace std;
void PrintArrayLength(int arr[])
{
cout << "Function Array length is: " << sizeof(arr)/sizeof(int) << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[] = {... | Because when you pass an array by value to a function, you're actually passing a pointer (to the first element of the array).
void PrintArrayLength(int arr[])
{
cout << "Function Array length is: " << sizeof(arr)/sizeof(int) << endl;
}
is actually:
void PrintArrayLength(int* arr)
{
cout << "Function Array leng... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.