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 |
|---|---|---|---|---|
7,426,999 | 7,427,039 | php extension value not correct printed why? | I want to send an object through reference. The object represents a class
[test.php]
$car= new Car();
$car->l=1000;
$car2 = new Car2();
$car2->method($car);
[php_cod.cc]
PHP_METHOD(Car2, method)
{
Car2 *car;
Car obj11;
zend_class_entry ce2;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &... | In the php part of code, obj11 is an uninitalized pointer and that is being passed to Car2::method ( (car2->method(*obj11)); ). So-
cout<<"IN THE REFERENCE CLASS"<<carr.l<<endl;
// carr is a garbage reference and is causing the segmentation fault
|
7,427,174 | 7,428,108 | Pointer to a member function in an inaccessible base | The compilation of the next example :
class A
{
public:
void foo()
{
}
};
class B : private A
{
public:
using A::foo;
};
int main()
{
typedef void (B::*mf)();
mf func = &B::foo;
B b;
(b.*func)();
}
fails with next errors :
main.cpp||In function ‘int main()’:
main.cpp|18|err... | Access to members of A is governed by chapter 11 "Member Access Control", but pointer-to-member conversions are covered by 4.11. In particular, 4.11/2 states that you can't convert a T A::* to an T B::* when you can't convert an B* to a A*.
Here's a slight variation of the question:
class A
{
public:
void foo()
... |
7,427,689 | 7,427,787 | How to deal with message fragmentation in Perl TCP socket? | I have a socket comminucation between Perl client and C++ server.
Perl code:
if (!socket(SERVER, AF_INET, SOCK_STREAM, getprotobyname('tcp'))) {
die "Can't allocate socket\n";
} elsif (!connect(SERVER,sockaddr_in($PORT, $tcp_addr))) {
die "Can't connect to server at $tcp_addr port $PORT...\n";
}
SERVER... | Add the message length as a 4byte header to the message. This is not ugly, but just as the "pros" do it. TCP/IP is a stream oriented protocol. You were just lucky that you got your messages in one recv call. It is possible to get any number of bytes, only half a message, one and a half message etc. as tcp/ip is transfe... |
7,427,868 | 7,427,925 | Usage of variadic functions | What are the benefits of using
variadic functions
void fun(int i, ...);
instead of passing a pointer to an array?
void fun(int i*);
When are variadic functions preferred?
| You have to explicitly create the array first. In addition, it would be problematic if you wanted to specify parameters of different types.
Variadic functions do not require creating any array and they can deal with different types.
As an example, I could not bare to use the printf-functions if I always had to create s... |
7,428,055 | 7,428,413 | C++ MapType::iterator using updated value | In my C++ code, I access a map through iterator. Update the map if necessary and re-assign it to class variable. In proceeding statements, I want to use updated map value again. Should I load the map again, refresh the iterator? etc. e.g. the map is:
MapType tbl = device->trust();
MapType::iterator iter_trust = tbl.beg... | MapType tbl = device->trust();
MapType::iterator iter_trust = tbl.find(node->getId().id());
if (iter_trust == tbl.end()) {
tbl.insert(std::make_pair(node->getId().id(), 0.1));
iter_trust = tbl.find(node->getId().id());
}
else {
tbl[node->getId().id()] = 0.1;
}
So you'll be sure you upgrade.
|
7,428,137 | 7,429,308 | How to make the format flags non-binding in C++? |
Possible Duplicate:
“Roll-Back” or Undo Any Manipulators Applied To A Stream Without Knowing What The Manipulators Were
Consider the following code
int temp=256;
cout<<temp<<endl;
cout<<hex<<temp<<endl;
cout<<temp<<endl;
The output is "256","100" and "100" respectively.
Is it possible to make the 'hex' flag non-bin... | Not for the standard manipulators. But in practice, you probably
shouldn't be using the standard manipulators (other than perhaps as an
example); they correspond to physical markup, and in an application, you
want to use logical markup. You want to write something like
cout << temperature << roomTemperature;
, wher... |
7,428,296 | 7,429,507 | overload operator<< for std::stack | Code goes first:
//.cpp file
template <typename T>
ostream &operator<<(ostream &os, stack<T> &st)
{
while(! st.empty()) {
os << st.top() << " ";
st.pop();
}
return os;
}
template <typename T>
void stack_sorter(stack<T> &st)
{
cout << st << endl; //no output, st is empty?
//...
}
i... | As others have pointed out, pop_back makes your output operation destructive. There is simply no way to read the contents of a stack without emptying it… that's the nature of a pure stack.
Also, it is very poor practice to overload operators for standard types. Because of the way name lookup works (ADL, that is, the wa... |
7,428,364 | 7,428,942 | Variable access in multiple threads with out synchronization | I have following code
int i; //gobal var
Thread1:
{
...
i=some value;
}
Thread2:
{
if (i==2) dosomething();
else dosomethingelse();
i = 4;
}
I want to write it to be thread safe without using synchronization objects and in C++ standard way.
my questions is how to have a variable to read/write access by diffe... | Well your code does not have any meaning right now. Becaues you are basically saying`
Thread2:
{
if (i==2) dosomething();
//let's do something if i is 2 at the moment I am reading it.
else dosomethingelse();
i = 4;
}`
It is ok. But if you are doing something with i then you are in trouble.
If not, and if you a... |
7,428,568 | 7,429,470 | C++ cast pointer to static method | I haven't write C++ code in a long while; however now I have to work on a texas instruments F28335 DSP and I am trying to migrate from C to C++.
I have the following code that is trying to initialize an interrupt service routine with a static method of a class:
//type definition for the interrupt service routine
typ... | I think the fundamental problem is that ampersand prefixing the RHS of your assignment to p. Also, "PINT" is "pointer to integer" in other operating systems. So let's avoid any potential name conflicts. But I thinks this will work for you:
// you may have to move "interrupt" keyword to the left of the "void" declara... |
7,428,657 | 7,428,934 | Histogram Calculating program | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arraylength;
int lastbig = 0;
int lastsmall = 0;
int temp = 0;
int numofgroups = 0;
double gg = 0;
cout<<"Enter the number of numbers you are going to enter "<<endl;
cin>>arraylength;
int data[arraylength];... | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arraylength;
int lastbig = 0;
int lastsmall = 0;
int temp = 0;
int numofgroups = 0;
double gg = 0;
cout<<"Enter the number of numbers you are going to enter "<<endl;
cin>>arraylength;
int *data = new int[ar... |
7,428,774 | 7,429,292 | Visual Studio debugger visualizers for Mozilla objects | Are there any Visual Studio debugger visualizers for Mozilla objects (e.g. nsString)?
I'm looking for something like the boost visualizers.
| There are some tips in Debugging Mozilla on Windows FAQ on it. Add the following entries to your AUTOEXP.DAT to improve Mozilla objects visualizing.
;; Mozilla (1.7beta and later)
nsAutoString=<mData,su>
nsString=<mData,su>
nsCString=<mData,s>
nsCAutoString=<mData,s>
nsRect=x=<x,d> y=<y,d> width=<width,d>; height=<heig... |
7,428,912 | 7,442,288 | for( ... ) loop index declaration style | Is there any difference code-wise between:
int i = 0;
for ( i = 0 ; i < n ; i++ )
{
}
and
for ( int i = 0 ; i < n ; i++ )
{
}
Maybe if there are more loops and they all use the same index?
Also, is the first version equivalent to:
int i = 0;
for ( ; i < n ; i++ )
{
}
I know the optimizer should be smart enough to ge... | Ok so I figured out why we were using the index declaration outside the loop.
Apparently our solaris compiler will give a compilation error for code like:
for ( int i = 0 ; ; );
for ( int i = 0 ; ; );
The error is:
Error: multiple declaration for i.
|
7,428,974 | 7,429,151 | What is .NET's relation to the Windows Kernel/OS & other OS's | I am confused as to what exactly .NET actually is. I am a Computer Science student who has done a lot of Win32 (WinAPI) programming in C++ & have a pretty good understanding of how Win32 functions interact with COM & the Windows Kernel itself.
But where does .NET fit into all this?
Specifically, if Win32 is an API wri... | Some brief answers to keep you going:
Specifically, if Win32 is an API written in C, what is .NET? Is it an API written in C also?
.NET consists of multiple parts. One part is called the CLR. That part is written in C++, C++/CLI, and some assembly. This is responsable for Running the .NET appplications. The Just-I... |
7,429,462 | 11,311,786 | Creating C++ string in GDB | I'm having trouble creating an std::string (or any C++ object, I guess) in GDB. I tried lots of variations to the following and none of them seem to work:
(gdb) p std::string("hello")
A syntax error in expression, near `"hello")'.
Is there a way to do it?
(I'm surprised I couldn't find anything about this on the Web. ... | You should be able to construct a new std::string within the GDB. You want to allocate space on the heap to hold the std::string object, invoke the default constructor, and assign your string value. Here is an example:
(gdb) call malloc(sizeof(std::string))
$1 = (void *) 0x91a6a0
(gdb) call ((std::string*)0x91a6a0)->... |
7,429,510 | 7,429,724 | Non-pointer typedef of member functions not allowed? | After getting an answer to this question I discovered there are two valid ways to typedef a function pointer.
typedef void (Function) ();
typedef void (*PFunction) ();
void foo () {}
Function * p = foo;
PFunction q = foo;
I now prefer Function * p to PFunction q but apparently this doesn't work for pointer-to-membe... | For non-member functions, a type such as typedef void(Function)() has several uses, but for member functions the only application is to declare a variable which holds a function pointer. Hence, other than a stylistic preference, there's no strict need to allow this syntax and it has been omitted from the standard.
Back... |
7,429,763 | 7,431,051 | LRC checksum in Delphi | I am trying to convert a C code to Delphi/pascal, but somehow I cannot get it to work, my approach was like this :
function CheckLRC(s : PChar) : Char;
var
sum : char;
begin
sum := #0;
while (^s <> #0) do
begin
sum := (sum XOR ^s);
inc (s)
end;
result := sum;
end;
Original C code was :
Set LRC ... | I guess the exact equivalence of this function may be:
function CheckLRC(const s: AnsiString): byte;
var i: integer;
begin
result := 0;
for i := 1 to length(s) do
inc(result,ord(s[i]));
result := (result xor $FF)+1; // or result := (not result)+1;
end;
All "and $FF" in original code is unneeded here, since w... |
7,429,930 | 7,430,334 | complexity analysis of algorithm | here is code, which fills two dimensional array with random genarated numbers in range [1 19] without duplication, my question is: how to determine it's complexity?
For example, I see that its running time is at least O(n^2), because of its inner and outer cycles, but that about the goto statement?
Here is my code:
#... | As the likelihood of getting a working number decreases, the number of goto-loops increases.
For a uniform random number generator, the behavior is linear with respect to the number of.. numbers. It definitely doesn't add a constant to your complexity.
If n is the number of elements in a, then it'll on average scale wi... |
7,430,593 | 7,430,692 | HowTo get access to structure elements using pointers? | Problem is to create a std::vector data table (struct MegaTable, from the example below), where items (struct DataItem, from the example below) could have a pointer to the whole data array.
Here is my code:
#include <vector>
struct MegaDataItem;
struct DataItem
{
int a_;
char* ch_;
... | The problem is your MegaDataItem structure is not copyable and assignable (if you copy or assign the vector in MegaDataItem, the back pointers will point to the original MegaDataItem, which is incorrect). You have to amend that.
Particularly, you'll have to implement the copy-constructor and assignment operator. In the... |
7,430,870 | 7,431,012 | Error reporting knowing where it is in the code | I have a stream called "err" which is in the namespace Errors. This is how the developer is meant to report errors in a user friendly way. So when something goes wrong the dev will write the error message as such:
Errors::err << "Oh no. That was a bad thing.";
Is it possible to use the preprocessor to append [__FILE__... | This is impossible with your current style. The routines called at runtime don't know who calls them. You can, however, obtain the backtrace using platform-specific functions and write that.
If you could replace all error reporting code eg. with
REPORT_ERROR( "Oh no. That was a bad thing." );
it would be easy. You'd j... |
7,430,922 | 7,431,024 | Ambiguity between overloaded constructors | Can someone please explain to me why in the following code I get an ambiguous call to the overloaded constructors in Foo if I attempt to instantiate MyFooC? My assumption was that the integer used as a constructor parameter would have been promoted to an unsigned int and been resolved but this is obviously incorrect.
t... | An int can be converted to both a double and an unsigned; both are
considered "widening" conversions, and have equal rank. As a general
rule, any time you overload, and one of the overloads is an integral
type, it's a good idea to overload on int as well, to be sure of
getting what you want, and avoiding ambiguities, ... |
7,431,040 | 7,431,087 | Difference between sqrt and sqrtf | I want to consider to code. First it is:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
int s = 25;
cout << sqrt(s) << endl;
return 0;
}
It gave me this mistake:
>c:\users\datuashvili\documents\visual studio 2010\projects\training\training\training.cpp(9): error C2... | Here's a page on MSDN documentation for sqrt() and sqrtf(), that explains the difference:
sqrt, sqrtf
Calculates the square root.
double sqrt(
double x
);
float sqrt(
float x
); // C++ only
long double sqrt(
long double x
); // C++ only
float sqrtf(
float x
... |
7,431,084 | 7,432,413 | How to delete all QGraphicsItem from QGraphicsScene | I've written a derived class from QGraphicsScene. At a point I need to remove all items from the scene and I want the items to be physically destroyed (destructor called). I tried the following:
QList<QGraphicsItem*> all = items();
for (int i = 0; i < all.size(); i++)
{
QGraphicsItem *gi = all[i];
removeItem(gi... | You can remove and delete all items with QGraphicsScene::clear().
|
7,431,182 | 7,431,293 | Compilation error when registering callbacks in openGL | I've just started learning openGL a couple of hours ago for my work and have been tasked with rendering a concave polygon using tessellation. I'm trying to compile the following code:
#ifndef CALLBACK
#define CALLBACK
#endif
#include "GL/gl.h"
#include "GL/glu.h"
void CALLBACK beginCallback(GLenum which);
void draw... | The book is correct. You just have to cast the function pointer to void(*)(). It's needed because the type is not (and cannot be) precise.
gluTessCallback(tessObj, GLU_TESS_BEGIN, (void(*)())&beginCallback);
|
7,431,278 | 7,431,373 | Should I ever use __throw_logic_error? | I've stumbled upon a piece of code that uses a function std::__throw_logic_error to throw exceptions. This function is declared in functexcept.h and apparently does the same as throw logic_error(...). Is there a difference? What is the function for? When, if at all, should I prefer it?
Thank you.
| In general, you shouldn't use it.
The two underscores at the beginning of the name are an indication that it's a compiler-specific addition, and probably it's not even meant for "public" use, but just as a helper for internals of the standard library (I suspect that it's there to support e.g. using the library without ... |
7,431,724 | 7,528,291 | InputBox Cancel using C++ | I am using the InputBox component in Embarcadero or Borland C++ with a default string. The Cancel key returns the same default string as the Enter button.
According to the documentation, the Cancel key is supposed to return an empty string.
String s = InputBox("Title", "Prompt", "Default");
if (s == "") return; // Ca... | I have found a solution that uses InputQuery instead of InputBox. The InputQuery functions returns FALSE if the Cancel button is selected. The DefaultString is returned on Enter.
|
7,432,100 | 7,432,600 | How to get integer thread id in c++11 | c++11 has a possibility of getting current thread id, but it is not castable to integer type:
cout<<std::this_thread::get_id()<<endl;
output : 139918771783456
cout<<(uint64_t)std::this_thread::get_id()<<endl;
error: invalid cast from type ‘std::thread::id’ to type ‘uint64_t’
same for other types:
invalid cast from ty... | The portable solution is to pass your own generated IDs into the thread.
int id = 0;
for(auto& work_item : all_work) {
std::async(std::launch::async, [id,&work_item]{ work_item(id); });
++id;
}
The std::thread::id type is to be used for comparisons only, not for arithmetic (i.e. as it says on the can: an ident... |
7,432,230 | 7,432,325 | what are Parametric and Inclusion polymorphism in C++ | I am reading some C++ text at the address https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.082/content/adhoc.html.
In the section UNIVERSAL POLYMORPHISM, the author mentioned about Parametric and Inclusion polymorphisms. I am not quite sure that I understand the point, especially why Parametric polymorphism i... | "Parametric polymorphism" in C++ means templates.
I think that "inclusion polymorphic" in C++ means polymorphic the way the Standard refers to it: virtual methods, subclasses and the like.
I think the names are clumsy and smack of academia.
|
7,433,591 | 7,433,747 | GetThreadContext returns EBP = 0 | I'm trying to get the value of another process' EBP register on windows7 64 bits.
for this I'm using GetThreadContext like this:
static CONTEXT threadContext;
memset(&threadContext, 0, sizeof(CONTEXT));
threadContext.ContextFlags = CONTEXT_FULL;
bool contextOk = GetThreadContext(threadHandle, &threadContext);
The E... | One possible cause is that the register's value really is zero at the time you inspect it. It's a general-purpose register, so the program can set it to whatever value it wants.
|
7,433,663 | 7,433,688 | (C/C++) How to generate executable file that can run on both Windows and Linux? | I'm new in programming. From what i know, a program that is compiled in Linux should not be able to run in Windows. So, if we want to run the same program in both platform, we need to compile the source code under both platform, and create 2 different executable files.
Recently I am studying the source code of an open ... | There is no way to have a single native executable compiled from C++ source that works on different platforms. I don't believe you that the same executable file is run on Windows and Linux, as you state in your second paragraph.
|
7,433,795 | 7,433,834 | Is it safe to reassign std::map::value_type&? | If I have a map with a set of exist key-value pairs, is it safe for me to reassign direct to an iterator? For example:
bool switchIf(const std::string& key, Widget& widget)
{
WidgetMap::iterator iter = _widgets.find(key);
if(_widgets.end() != iter)
{
iter->second = widget;
}
return (_widget... | Yes. That is completely safe. iter->second is nothing, but a reference to the value in the map.
|
7,433,803 | 7,433,892 | What happens if you return a non-static local when the return type is static const | If you have the following function:
static const map<ushort, ulong> MakeMap()
{
map<ushort, ulong> mymap;
for(int i=0; i<myTableSize; i++)
{
mymap[myTable[i].x] = myTable[i].y;
}
return mymap;
}
and somewhere use you have:
static const map<ushort, ulong> numMap = MakeMap();
will the compiler actually se... | The return type is not static const map<ushort, ulong>. It's only const map<ushort, ulong>. The keyword static applies to the function. That is, it's the function which is static which means the function has internal linkage* and cannot be called from other translation unit*.
* Go through the links to know about them.... |
7,434,062 | 7,434,178 | Detect dynamically allocated object? | Can I check if an object (passed by pointer or reference) is dynamically allocated?
Example:
T t;
T* pt = new T();
is_tmp(&t); // false
is_tmp(pt); // true
Context
I perfectly realise this smells like bad design, and as a matter of fact it is, but I am trying to extend code I cannot (or should not) modify (of course I... | Not portably. Under Solaris or Linux on a PC (at least 32 bit Linux),
the stack is at the very top of available memory, so you can compare the
address passed in to the address of a local variable: if the address
passed in is higher than that of the local variable, the object it
points to is either a local variable or... |
7,434,267 | 7,434,564 | Scripting languages and Game Dev/Programming | Okay, so I've been getting into 2D game developing/programming , and many games I've seen use some sort of scripting language too. So I'm wondering - What's the purpose of using scripts in games? I know there's not simple one reason answer, and I've been trying to consider all the possibilities. Here's what I 'think' I... | your top 3 reasons are all 100% correct and are the main reasons for using scripting languages along with your game engine.
Personally I've only really had experience with Lua through Luabind. It's a little tricky to setup but it was worth it. What you can do with scripting languages is expose the data structures and/o... |
7,434,344 | 7,434,409 | How to sort both data member arrays of a class in code shown | I have a simple C++ code written to understand sort function usage on user defined class data types to sort data members of a class.
But this only sorts array of variable b in the class. Because, the earlier sorted array of variable a, is also disturbed whiel sorting b.
#include <iostream>
#include <cstring>
using nam... | It depends on how you want your elements to be sorted:
Sort as pairs, keyed on a: (1,12), (3,2), (5,8), (10,4)
Sort as pairs, keyed on b: (3,2), (10,4), ...
Sort as pairs lexicographically: same as sorting on a, since there are no repeated values for a.
In case (1) you use compare1, in case (2) you use compare2. (For... |
7,434,620 | 7,702,842 | Windows Mobile 6.5 C++ - Determining internet connection | My application needs to send some packets every 30 minutes, but I don't want to send via charged services like GPRS/EDGE/... I would like to send only if a WiFi / ActiveSync is UP.
How do I find out if:
There is currently Wifi used as network
There is currently GPRS/EDGE/UMTS... used as network
There is currently Acti... | RESOLVED
Ok, found that working :
void TEST()
{
CONNMGR_CONNECTION_DETAILED_STATUS *StatusBuffer;
CONNMGR_CONNECTION_DETAILED_STATUS *StatusBufferTemp;
DWORD pcbBufferSize = 0;
ConnMgrQueryDetailedStatus(NULL, &pcbBufferSize);
StatusBuffer = (CONNMGR_CONNECTION_DETAILED_STATUS *)new BYTE[pcbBuf... |
7,434,638 | 7,434,853 | Force window to be above already top-most windows (like the Task Manager) | I have a window which i would like to display above everything else. My code is able to successfully force it to be above almost every window, except for other top-most windows. Here is the code I use:
SetWindowPos(getSDLWindow(),HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
This line is executed every ... | No, because There is no "super topmost" flag.
Nor should you because all the super-top-most windows will fight each other for control.
|
7,434,797 | 7,435,054 | unordered_map::find() inserts the key of the lookup | Is it a feature of unordered_map::find() to insert the key that we lookup with 0 value automatically?
Let me make this clear
unordered_map<int, int> tempMap;
//some code
if(tempMap.find(1) == tempMap.end()){
//do something but not insert the 1 with a corresponding value into the tempMap
}
so if I... | No, find only searches and returns an iterator.
That said, std::unordered_map (and std::map) both overload operator[] which will insert a default if needed:
// if element with a key value one exists, return that. otherwise, insert
// a default initialized element (zero in this case), and return that
auto& val = tempMap... |
7,434,843 | 7,435,021 | Parsing a string in C++ for assigning parameters |
Possible Duplicate:
How do I tokenize a string in C++?
I have a string of the following form , which is a user input.
a1 10.2 lib_t 50 sv 60 out 'true'
Here, a1 is a parameter of type double, and its value is 10.2 . Similarly, lib_t = 50, sv = 60 and out = 'true' is a string.
This input can be specified... | #include <sstream>
#include <ostream>
#include <istream>
#include <string>
#include <stdexcept>
int main() {
std::string parameters = "a1 10.2 lib_t 50 sv 60 out 'true'";
std::stringstream ss(parameters);
std::string param;
double a1;
int libt; //names ending in _t are not allowed
short sv;
... |
7,434,887 | 7,434,923 | Implicit type casts in expressions with bit shifts | In the code below, why 1-byte anUChar is automatically converted into 4 bytes to produce the desired result 0x300 (instead of 0x0 if anUChar would remain 1 byte in size):
unsigned char anUChar = 0xc0; // only the two most significant bits are set
int anInt = anUChar << 2; // 0x300 (correct)
But in this code, aimed at ... | char always gets promoted to int during arithmetic. I think this is specified behavior in the C standard.
However, int is not automatically promoted to long long.
Under some situations, some compilers (Visual Studio) will actually warn you about this if you try to left-shift a smaller integer and store it into a larger... |
7,435,055 | 7,435,224 | problem with updating a map by removing some keys and also some elements | I have a map. lets say map<int, vector<int> > mymap1.
I want to update mymap1 by deleting some “keys” and also removing unwanted “elements” from the vector part of the selected keys. The “key’ or the “element” going to be deleted is given from another vector, known as “mylabel”. Actually, What I need to remain in my m... | Your erasing logic is wrong, and you end up using invalid iterators. (You're literally pulling the rug out from under your feet if you erase an iterator and then keep using that iterator.)
For node-based containers (list, map, set, unordered), you typically erase as follows:
for (auto it = c.begin(); it != c.end(); )
{... |
7,435,548 | 7,619,824 | gold linker on ubuntu 11.04 does not search /usr/local/lib by default | I am trying to use the gold linker to compile my code, but it does not search for libraries in /usr/local/lib by default. I tried adding /usr/local/lib in /etc/ld.so.conf.d/ and it still does not work. It is as if gold is not checking the /etc/ld.so.conf stuff. I can add
-L/usr/local/lib
in my Makefile and it works, ... | There are also the LDFLAGS enviroment variable, but like ld.so.conf it might be LD specific with gold not respecting them.
In that case, only going through the gold documentation will help.
|
7,435,713 | 7,435,802 | simple istream_iterator question | I am new to C++, sorry if this is a silly question. I cannot seem to figure out why this does not work. It copies into the first vector, and seems to skip past the second copy call.
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main ()
{
vector<int> first;
vector<int> seco... | The istream_iterator is an input iterator, which means you can only dereference each iterator value once. You are literally reading from a stream, and there's no seeking or going back. So once you hit the end-of-stream, there's nothing more to input and the second range is empty.
Why not just say vector<int> second(fir... |
7,435,719 | 7,436,378 | C++ Parse string to integer with specific classes | It might sound stupid, but I was just wondering how can I parse a string to an integer in C++?
This is for a school project, and the explanation sheet says :
"Only the use of iostream and string classes and system() function is permitted; The use of any other class or function is prohibited."
I have searched around a b... | #include <iostream>
#include <string>
int stringToInt(const std::string &text)
{
int number = 0;
int powerIndex = 1;
for (int i = text.length() - 1; i >= 0; i--)
{
number += powerIndex * (text.at(i) - '0');
powerIndex *= 10;
}
return number;
}
std::string intToString (int n... |
7,435,839 | 7,437,378 | QT using addToJavaScriptWindowObject() | I am trying to use void QWebFrame::addToJavaScriptWindowObject(const QString & name, QObject * object). My problem is when I try and call the function in the JavaScript
TypeError: Result of expression 'screen.valueChanged' [undefined] is not a function.
TimeSliceScreen::TimeSliceScreen(QWidget* parent)
:
QWidget( pa... | I think screen is a reserved name in the js. Try changing the name to something else. Otherwise looks like it should work.
|
7,435,847 | 7,580,845 | C++ templated method disambiguation rules with rvalue references | In the following example the ctors #1, #1, #4 and #4 are called (in that order). I would expect #1, #1, #2, #3 to be called instead (discounting RVO).
//-----------------------------------------------------------------------------
struct A
{
A(){} // 1
A(A&&){} // 2
A(co... | This is a compiler bug.
Forgetting discussions about implicit rvalues for return local expressions (and throw local expessions too, by the way), this is clearly a compiler bug because --
none of the templated constructors should have been called in your example code.
No template function can be considered a copy constr... |
7,436,102 | 7,436,146 | Question regarding C++ Copy Constructor call | I'm trying to figure out the difference between these two lines of code..
We are given 'Count' is our Class name, C1 and C2 are objects of that class. No information of how and when the classes have been declared are given.
Count C2(C1); //Statement 1
Count C2=C1; //Statement 2
No other information is given. What is ... | At the grammatical level, the first one is called "direct initialization" and the second one is called "copy initalization". If Count is of class type (i.e. not a typedef of int, say), then both versions, equivalently, cause the copy constructor to be called.
The first version works in any case, the second version does... |
7,436,182 | 7,436,298 | “Partial application” for template parameters | I have the following “main” template:
template <
template <typename> class S
> struct TT { /*...*/ };
and the template I want to use with TT:
template <int N, typename T> struct S1 {};
In particular, I want to use something like
TT< S1<5> > t2; // "Invalid template arguments" here
It is a kind of partial... | Define a class template deriving from S1 as:
template <typename T>
struct S11 : S1<5,T>
{
};
And then use S11, instead of S1 as:
TT< S11> t2; //it is as if TT< S1<5> > t2
Working code : http://ideone.com/y2s7n
Reading your comment, it seems you need this:
template<int N>
struct Magic
{
template <typename T>
... |
7,436,247 | 7,436,312 | Concept difference between pre and post increment operator for STL | Supposedly:
for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
{}
I do understand the difference when it comes to pre/post increment for built-in types like int etc but in terms of an iterator, what's the difference here between ++iter and iter++? (Bear in mind that I do know that both yield t... | The difference is they do not yield the same result, while this particular example will do the same regardless of the increment form used. The pre-increment form first increments the value, and then returns it; while the post-increment form increments the result but returns the value previous to incrementation. This is... |
7,436,319 | 7,437,304 | Make QT Widgets semi-opaque | I am working with a QWidget elements which contains child elements, what I need is some way to make this widget semi transparent, completely, including its childs.
I have seen a method for QWidgets which is QWidget::setWindowOpacity() but this works only if the widget is a window itself, and in my case this widget is p... | You can use QGraphicsOpacityEffect.
A sample code fragment for 50% transparency would be:
ui->setupUi(this);
QGraphicsOpacityEffect * effect = new QGraphicsOpacityEffect(ui->pushButton);
effect->setOpacity(0.5);
ui->pushButton->setGraphicsEffect(effect);
|
7,436,374 | 7,478,637 | Android - Calling System.loadLibrary() causes process to die | I've decided to take on porting a game, that uses SDL libraries and makes heavy use of C++ and the STL, over to Android. I've been successful in getting all the required libraries compiled as well as all the source files for the game. My problem is that when I call System.loadLibrary() to load the .so for the game, t... | After pulling my hair out with this one I finally figured out the problem. It turns out one of the classes was performing some file IO on files that did not exist. In case someone else encounters a problem with loading a shared library, here is what I did to figure this one out.
I enabled a breakpoint at the call to ... |
7,436,462 | 7,436,492 | c++ struct reference types | I have a class called IAckHandler
class IAckHandler {
public:
virtual ~IAckHandler();
virtual void handleAck(long messageType, bool ackrcvd, uint8_t ackByte) = 0;
private:
};
The intended use is for other classes to inherit, so this is basically a "interface" class.
I am using message queues to submit reques... | You seem to be lacking some basic pointers and references knowledge. For the req_doSomething given in the example, &ref will give you a pointer to the referred object so it should be
else req.ackHandler = &ackHandler;
and to get a reference from a pointer, you derreference it with *ptr so the call would be
req_doSomet... |
7,436,481 | 7,461,743 | How to make my split work only on one real line and be capable to skip quoted parts of string? | So we have a simple split:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
vector<string> split(const string& s, const string& delim, const bool keep_empty = true) {
vector<string> result;
if (delim.empty()) {
result.push_back(s);
... | The following code:
vector<string>::const_iterator matchSymbol(const string & s, string::const_iterator i, const vector<string> & symbols)
{
vector<string>::const_iterator testSymbol;
for (testSymbol=symbols.begin();testSymbol!=symbols.end();++testSymbol) {
if (!testSymbol->empty()) {
if (0=... |
7,436,582 | 7,440,271 | c++ overwrite already opened file | I am opening a file with ifstream to check if it exists. Then I close it and open it with ofstream to write to it, and I think setting ios::trunc flag allows me to overwrite it.
However I'd like the ability to keep the file open if it exists, but I used an ifstream to open it so does that mean I can't write to the fil... | Just open a read-write fstream on the file. You can test if the file previously existed (and was non-empty) by seeking to the end and seeing if you're at a non-zero offset. If so, the file existed, and you can do whatever with it. If not, the file didn't exist or was empty. Assuming you don't need to distinguish be... |
7,436,808 | 7,436,960 | Does each file get its own copy of the static variable? | Suppose you have a static global variable in your header file, and you use this variable in your main.cpp.
// header.h
static int variableOne = 100;
//main.cpp
.
.
cout << variableOne << endl;
Will main.cpp get its own copy of variableOne (although the value is still 100...)? Or am I mixing this concept with... | 1. What does it mean #include
When you write #include "header.h" the compiler is basically just copying the whole content of the file instead of that line. In C++ an header file has no semantic meaning, it's just used for textual substitution.
So if you have
---- header.h ----
static int variableOne = 100;
---- main.c... |
7,436,828 | 7,436,906 | Looking for non-Boost::Python C++ Python embedding framework | I have a project of mine, written in C++, that has now progressed to a stage where I require an embedded programming language. I've chosen Python for several reasons, and have been playing around with revealing an API to a dynamically-loaded Python module. It works well, and I think I will stick with Python for the for... | I was facing nearly the same problem but at the end I sticked Boost::Python ;) However an option to Boost::Python is Swig. If you use Swig you also, don't have to write so much boilerplate code than you have to with Boost::Python.
|
7,436,968 | 7,437,211 | Boost::Split using whole string as delimiter | I would like to know if there is a method using boost::split to split a string using whole strings as a delimiter. For example:
str = "xxaxxxxabcxxxxbxxxcxxx"
is there a method to split this string using "abc" as a a delimiter? Therefore returning:
Results would be the string "xxaxxxx" and "xxxxbxxxcxxx".
I am aware o... | split_regex as suggested by @Mythli is fine. If you don't want to deal with regex, you can use ifind_all algo, as is shown in this example. You receive iterator_range (begin/end) of all occurrences of you delimiter. Your tokens are between them (and at the beginning and end of string).
|
7,437,049 | 7,437,230 | ReadDirectoryChangesW doesn't do anything c++ | Am I doing this right?
I am trying to find all the changes that took place in a folder called C:\Perl
After ReadDirectoryChangesW, it just gets stuck there. It doesn't move forward. Am I missing something obvious?
I am trying to achieve: How can I detect only deleted, changed, and created files on a volume?
Once everyd... | You are calling it in synchronous mode, so it's not returning until there's a change to report. This is by design.
The Remarks section in the documentation explains how to call it asynchronously.
It sounds like what you want is to see if something changed since some point in time. If so, this is not the API you're lo... |
7,437,137 | 7,437,953 | Happily linking incompatible types leads to chaos | I've been trying to figure out some boundaries of g++, especially linking (C++) object files. I found the following curiosity which I tried to compress as much as possible before asking.
Code
File common.h
#ifndef _COMMON_H
#define _COMMON_H
#include <iostream>
#define TMPL_Y(name,T) \
struct Y { \
T y; \
void f(... | In your example, you could put the definition of Y in an anonymous namespace like this:
#define TMPL_Y(name,T) \
namespace { \
struct Y { \
T y; \
void f() { \
std::cout << name << "::f " << y << std::endl; \
} \
virtual void vf() { \
std::cout << name << "::vf " << y << std:... |
7,437,423 | 7,437,468 | C++: sizeof of struct with bit fields | Why is gcc giving returning 13 as the sizeof of the following class ?
It seems to me that we should get e (4 bytes) + d (4 bytes) + 1 byte (for a and b) = 9 bytes. If it was alignment, aren't most 32 bit systems aligned on 8 byte boundaries ?
class A {
unsigned char a:1;
unsigned char b:4;
unsigned int d;
A* e;... | You are very likely running on a 64 bit platform and the size of the pointer is not 4 but 8 bytes. Just do a sizeof on A * and print it out.
|
7,437,510 | 7,437,574 | Representation of complex numbers in C++ for Discrete Fourier Transformation | I am currently writing a small tool which should help me check whether my manually calculated fourier vectors are correct. Now i need the n-th Root of Unity specified by omega = exp(2*pi*i / n). Can somebody explain me how to represent this omega as a complex in C++?
| Use Euler's formula:
exp(2πi/n) = cos(2π/n) + i sin(2π/n)
Then it's easy:
complex<double> rootOfUnity(cos(TWOPI/n), sin(TWOPI/n));
(replace TWOPI with either a macro available on your system or just the value of 2π however you see fit).
|
7,437,575 | 7,437,691 | UnitTest++ issues: Trying to use a Predicate that has state | Relevant code, this is from UnitTest++/TestRunner.h:
class TestRunner
{
public:
explicit TestRunner(TestReporter& reporter);
~TestRunner();
template <class Predicate>
int RunTestsIf(TestList const& list, char const* suiteName,
const Predicate& predicate, int maxTestTimeInMs) const
... | You could use the mutable keyword, but the way the test is structured suggests that the test runner might not reuse the same instance of the predicate, so your changes might be lost between tests. Of course, if the posted code is the entire test runner, then it looks like it does call the same Predicate instance every... |
7,437,646 | 7,438,078 | GetLastError called in a catch block yields incorrect value | Fun exploring some legacy code today. Ran into this little number:
function Func1()
{
DWORD dwError;
try
{
dwError = 1;
throw "Hey!";
} catch (LPCTSTR szError)
{
Log("Log1: %d", dwError);
SetLastError(dwError);
throw szError;
}
}
function Func2()
{
try {
Func1();
}
catch (LPCTST... | C++ exceptions in the MSVC compiler and runtime are built on top of native Windows SEH. Stack unwinding is actually performed by Windows. Using Windows api functions is going to affect the value stored for GetLastError(). More details about the connection with SEH in this answer.
|
7,437,649 | 7,437,812 | Access violation on static library call | As an extension of question MSVC unresolved external symbol linking executables. A contains and a class P with two member functions F and G, and also contains a global P MyP. I'm attempting to call functions MyP.F, from Executable T. I finally got past the linking part, but now it fails at runtime with the exception.... | Executables don't have the metadata allowing them to be loaded at an alternate address, and A.EXE can't load into T.EXE at its desired address, because T.EXE's code is already there.
You might be able to work around this by changing the default load address of A.EXE (when building it, it's a linker option), but the cor... |
7,437,727 | 7,438,238 | C++ Beginner - 'error' as a command in code | I am trying to work my way through a c++ textbook to learn some programming, but I've run into an issue with some of the sample code. The goal is to write a simple calculator program, and the text supplies parts of the code as examples. A portion is:
if (!cin) error("no second operand");
The text makes it seem like 'er... | I assume the book is Stroustrup's Programming Principles and Practices?
Check out the pages 149 and 150, it's explained there.
Put this code in a header file and include it in the example program:
#include <stdexcept>
void error(string s)
{
throw runtime_error(s);
}
void error(string s1, string s2)
{
throw ru... |
7,437,766 | 7,437,801 | Help me understand this algorithm (simple) | I have just made a queue class and I now have to use it to do this.
Write a c++ program to generate all strings using A,B,and C as the letters.
The strings must be generated in the following order:
A
B
C
AA
AB
AC
BA
BB
BC
CA
CB
CC
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
etc.
It's supposed to do this until my queue overflow... | Let our behavior be:
For any token X, add XA, XB, and XC to the queue.
Our flow will be something like:
Start with a Queue
A B C
Pop (and display) off A
B C
Behave on token: "A"
add AA
add AB
add AC
B C AA AB AC
Pop (and display) off B
C AA AB AC
add BA
add BB
add BC
C AA AB AC BA BB BC
If we pretend o... |
7,437,997 | 7,442,435 | How can I replace the void pointer with something that has compile time type checks in this callback? | I'm trying to create an event system with notifications via callbacks. I have the code written, but it is dependent on void pointers to work. After how hard void pointers bit me in my last project I would like to replace the void pointers with something that compile time type checks.
Here's the Event class
enum EventT... | Let's apply templates:
enum EventType {
TEST_TYPE_A,
TEST_TYPE_B
};
template <EventType> class EventData {};
template <> class EventData<TEST_TYPE_A> { /*****/ };
template <> class EventData<TEST_TYPE_B> { /*****/ };
// used by event receivers
class EventHandlerBase { public: virtual ~EventHandlerBase() { } };
t... |
7,438,047 | 7,438,134 | C++ / SDL: vector / surface issues | Here is the newest problem I am running into. I have a class called Projectiles which holds the basic makeup of a projectile. It's coordinates, and the image which it uses. Here is the basic structure:
class Projectile
{
private:
void load();
public:
SDL_Surface *surface;
SDL_Surface* r... | Projectile::Projectile( int type )
{
type = 1;
alive = true;
width = 83;
height = 46;
}
void Hero::newProjectile( int type )
{
projectiles.push_back( Projectile( type ) );
projectileCount++;
}
In the code above, you never loaded a surface. You never even initialized surface, so it's pointing... |
7,438,260 | 7,438,281 | difference in two ways of declaring a class instance | Assume we have a class with no default constructor:
class Foo {
public:
Foo(int data) : _data(data) { }
int data(void) const { return _data; }
private:
int _data;
};
Why does this compile and what does it do:
Foo x();
Even though the above compiles, you can't do any of the following:
x.data(); // doesn't co... | Foo x();
This doesn't create object x of type Foo. Instead you are declaring a function x whose return type is Foo.
This C++ FAQ entry should be helpful.
Now,
Foo *x = new Foo; // error: no matching function for call to 'Foo::Foo()
new Foo invokes the default constructor and you don't have one and is the reason fo... |
7,438,327 | 7,438,512 | How to convert Java String to C++ String using bytes as the medium | What would be the algorithm/implementation of the C++ code C++functionX in the following flow chart:
(JavaString) --getBytes--> (bytes) --C++functionX--> (C++String)
JavaString contents should match C++String contents as far as possible (preferably 100% for all possible values of JavaString)
[EDIT] The endianness of b... | Java:
String original = new String("BANANAS");
byte[] utf8Bytes = original.getBytes("UTF8");
//save the length as a 32 bit integer, then utf8 Bytes to a file
C++:
int32_t tlength;
std::string utf8Bytes;
//load the tlength as a 32 bit integer, then the utf8 bytes from the file
//well, that's easy for UTF8
//to turn th... |
7,438,329 | 7,438,397 | Trouble creating assert function | This is my assert function (it wont compile "error C2110: '+' : cannot add two pointers"):
#define CHAR(x) #x
template<typename T>
inline void ASSERT(T x)
{
if(!x)
{
std::string s("ERROR! Assert " + CHAR(x) + " failed. In file " + __FILE__ +
" at line " + __LINE__ + ".");
... | String Literals are easily reduced to char pointers, which cannot be added as you try to do with "ERROR! Assert " + CHAR(x) + " failed. In file ".... However, C++ has the handy feature of doing this automatically before compilation! (the preprocessor does this). Even better, it has a handy tool for making wide string... |
7,438,509 | 7,438,526 | Confusion with member copying of class | After studying the member copying and the assignment operator in C++,
and looking at " member copying of class " which explains the conditions where default assignment operator cannot be generated. I am not very clear about the concepts as the following example I tried actually works on g++4.5
#include<iostream>
using ... | Y y2 = y1; is not an assignment. It's a copy constructor call. If you declare and initialize a variable on the same line, a one parameter constructor is called with the right hand side of the equals sign as the parameter. There's nothing about Y that prevents the default copy constructor from being instantiated (and ca... |
7,438,524 | 7,438,550 | Are Template-less Getters Possible in Variadic Template Container Classes? | A hypothetical variadic template tuple class would, as far as I can tell, have to use getters with template parameters.
int MyInt = MyTuple.Get<int>(0);
This is inconvenient, and introduces potential for error. I can't help but feel that there's a way to construct the class so you you don't have to explicitly specify... | You mean like std::tuple?
The getter's template argument specifies the index of the member, not the type. By definition, the number and types of a tuple are fixed at compile time. Since the type depends on the index, and the type must be known at compile time, the getter must be templated.
template< typename ... types ... |
7,438,539 | 7,438,712 | QAbstractItemModel + ModelTest::rowsInserted ASSERTion problem | I'm trying to debug my model (QAbstractItemModel) with ModelTest. And I can't understand one assertion.
There are two slots in ModelTest that intercept signals generated by my model.
ModelTest::rowsAboutToBeInserted
ModelTest::rowsInserted
Slot/function 1 looks like this
void ModelTest::rowsAboutToBeInserted ( const ... | The idea behind this assert is to check if first row after added ones was correctly moved. If there are some rows after inserted ones, then their data are compared. If there aren't any, your model should both in the line
c.next = model->data ( model->index ( start, 0, parent ) );
and in
Q_ASSERT ( c.next == model->dat... |
7,438,583 | 7,438,688 | converting binary to text in linux | I have a big binary file I have produced by writing an array of float numbers in binary format.
Now how can I simply convert that binary file to text ?
| Use the UNIX od command, with the -t f4 option to read the file as 4 byte floating point values. The -A n option is also useful to avoid printing the file offsets. Here is the output of an example file that I created.
/tmp> od -A n -t f4 b.dump
-999.876 -998.876 -997.876 -996.876
... |
7,438,594 | 7,439,205 | Use LuaBind to call Lua functions inside a class when Lua is bound inside THAT class | Basically, I just want to be able to have a clean Lua instance made inside of my Manager class, then export the functions in the class to Lua, so that I can call functions on the already created C++ class inside of Lua.
This is the current way I am looking at solving the issue. It compiles but nothing happens in Lua.
D... |
so that I can call functions on the already created C++ class inside of Lua.
If you use Luabind to create a class, and then provide members of that class, then Luabind will do exactly that. It will expose a class to Lua that has members.
You cannot call a member function in C++ without an object of that class's type.... |
7,438,708 | 7,438,800 | c++ code compiles but failed at runtime | The code below compiles but after clicking on first button it breaks with msg
Unhandled exception at 0x0133ae9a in deming.exe: 0xC0000005: Access violation writing location 0x014aedbd.
Is it a c++ error as i am novice or is it dragonsdk i use ?
//====================================================
// App.cpp
//======... | The reason of your problem is wrong imagination of what strcat does. It is appending second buffer to the first - in this case your first buffer is static, so appending to it obviously fails. You should use something like
char* image = "Images/image";
char* fullname = new char[strlen(image)+2];
strcpy(fullname, image)... |
7,438,834 | 7,438,847 | C++ What's wrong with this simple class? | Just learning Classes in C++, I thought I had a fairly good grip on it but for some reason this code won't even compile.
#include <iostream>
#include <cstdlib>
using namespace std;
class Position
{
int row;
int column;
public:
Position(); //constructor
~Position(); //destructor
void... | You don't need to prefix instance variables using the class name, instead use row or this->row
EDIT:
Eventually you will want to move the class declaration to a header file ie. position.h and keep the implementation in the position.cpp file with #include "position.h" at the top. This will make your Position class usab... |
7,438,865 | 7,438,893 | In C++, how can I test if an object is an instance of a Child class in the Parent class' constructor? | I'm trying to assert that a pointer passed into a Parent class' constructor is only NULL if the object is of a specific Child class type using dynamic_cast:
#include <iostream>
class Parent {
public:
Parent(void *ptr);
virtual ~Parent(); // to make Parent polymorphic
};
class Child1 : public Parent {
public:
... | I'd guess the issue is that dynamic_cast works off the vtable, which isn't set up until after the constructor finishes. Thus, you can't call dynamic_cast in the constructor.
I can't think of any immediate ways to detect this in the constructor without using templates and making everything static. Why do you want this b... |
7,438,909 | 7,438,932 | c++ sorting names alphabetically | I have a program that is trying to sort some names alphabetically. I run it and it does not have any errors, but the names are not sorted. I compare 2 names and see which one is supposed to be shifted in the array.
Here is the code:
void sort_names(char array[])
{
const int arraysize = 5;
// Step through each... | The Problem is that in this line:
if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))
it doesn't compare string characters, but rather compares memory adresses.
If you still want to use char arrays, you have to use the strcmp function. However, I recommed that you use string instead.
|
7,438,948 | 7,439,045 | Mutex in getter setter | I was wondering about how to use mutex for multithreaded application. Do my getters need to lock too? I found this post. The answer is yes, I need to guard getters functions
but that means I'll be able to perform one read at a time, and I wonder if it could be improved.
T.E.D's answer suggests that you can implement lo... | You need a special kind of locking mechanism called readers-writer lock. With this lock any number of readers can access the resource simultaneously, but for a writer to have access all reader threads must block.
Looks like Qt has a QReadWriteLock class that implements this mechanism.
|
7,439,028 | 7,439,229 | Windows, Mingw Qt Application Does Not Run On Deployed Computers | I have created a Qt application with Mingw. The application runs properly on the development computer after copying the required DLL's to the directory. However, when deploying on external computers, the application does not run at all.
Update:
In addition, the application uses Sqlite3 via QtSql.
| It's quite likely you're still missing some dll.
Check the Windows event log for any errors after running the application. (Administrative Tools->Event Viewer).
Try launching the application from a command prompt window.
Try Dependency Walker.
Another thought is some missing configuration file or registry settings.
D... |
7,439,167 | 7,439,275 | Returning an empty vector of strings if key is not found | I know it is a very bad idea, so other suggestions on how to do it efficiently will be well-received.
Here's the thing. I have map<string,vector<string> > , I want to search for a key and return its corresponding value (vector of strings in this case). Reason I insist on returning (rather than just iterating) is I need... | 1) Returning an iterator is a fine idea. When you do this, the natural way to indicate the "not found" case is to return the .end() iterator. This has the down-side that the abstraction is somewhat leaky: the caller has to be able to get at this .end() value in order to compare to it for error checking, and the returne... |
7,439,170 | 7,439,196 | Is there a way to find leaked memory using a core file? | I have a core dump from an application with a memory leak. I have used the strings command and xdd to examine the file and I've got a few ideas of which part of the program might be responsible for the leak. I'm able to run up the core file in gdb with the application but I can't do a lot of testing with it because it'... | Not very easily, no. The whole point of leaked memory is that it's memory that was allocated that no longer has a reference to it.
You would have to walk through the entire memory arena to get a list of all allocated blocks, then examine every possible variable/memory-location which may be pointing to it (with almost c... |
7,439,175 | 7,439,211 | how overload operator<< for an array in C++? | I'm trying to do it this way:
template <typename T>
ostream &operator<<(ostream &os, T &arr)
{ /*...*/ }
But can T represent an array? Is it correct to overload the << operator for an array?
EDIT:
According to Kerrek SB's advice, here is my implementation for <<:
template <typename T, unsigned int N>
ostream &operato... | You could do this:
template <typename T, unsigned int N>
std::ostream & operator<<(std::ostream & os, const T (&arr)[N])
{
// ..
return os;
}
This works only for compile-time arrays, of course. Note that you are not allowed to instantiate this template when T is a built-in type or a type in the std namespace!
Prob... |
7,439,306 | 7,439,328 | C++ removing leading zeros in a binary array | I am making a program that adds two binary numbers (up to 31 digits) together and outputs the sum in binary.
I have every thing working great but I need to remove the leading zeros off the solution.
This is what my output is:
char c[32];
int carry = 0;
if(carry == '1')
{
cout << carry;
}
for(i = 0; i < 32; i++)
{
... | You should not have that inner loop (inside if(flag)). It interferes with the i processing of the outer loop.
All you want to do at that point is to output the character if the flag is set.
And on top of that, the printing of the bits should be outside the detection of the first bit.
The following pseudo-code shows how... |
7,439,435 | 7,440,930 | opencv2 bluring images | I'm trying to blur an image , and gaussion blur an image but all that ends up happening when i run my code is the image opens up without bluring. Can anyone help me with this problem?
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
int main() {
//read th... | A couple things: You are processing image into the Mat called result but then displaying image. Also, there is no call to waitKey after the last two calls to imshow so you aren't seeing those at all. And a small point: return 0 from main to signal completion with no error. Try this instead:
//read the image
cv::Mat ima... |
7,439,475 | 7,439,572 | Why does std::vector::resize(n, src) pass by value? | Pretty much as per the title.
The spec for std::vector<T>::resize seems to require that the src object be passed by value:
void resize(size_type n, T src = T() );
Why isn't a reference to a constant object used here instead?
void resize(size_type n, T const& src = T() );
For instance, in this question, the pass-by-va... | It was a mistake in the Standard Library specification. It is fixed in C++11; std::vector now has two resize member functions declared as:
void resize(size_type sz);
void resize(size_type sz, const T& c);
The difference between the two is that if the size of the container is larger after the resize, the first overloa... |
7,439,499 | 7,439,516 | Passing Struct Array to Function by reference | I was wondering how to pass a struct array by reference into a function. I found how to do it with pointers but wanted to learn with references too. Here is my code thus far.
struct employeeType
{
string firstName;
...
double monthlyBonus;
};
void readEmpData(ifstream& infile, employeeType *emp, int length);
I though... | I assume you want readEmpData to read in an array of employees from a file. In this case, the caller wouldn't know how many employees there are and so the array and its length should be output parameters. An appropriate signature would be:
void readEmpData(ifstream & infile, employeeType *& emp, int & length);
or
empl... |
7,439,645 | 7,439,691 | C++ loop logic error? | I am having some trouble getting a C++ logic loop working. From testing, I believe it is a error in the Grades() function loop.
Basically the program is supposed to get the Names and Test Scores, which it appears to do, but the program exits right after that and I am not sure why. Just wanting to see if anyone else not... | What compiler/operating system are you using?
Sometimes it's necessary to add a system("pause"); call before you return from main. This is often true if you're compiling from an IDE than runs the program directly. You could avoid the problem by running it directly from the command line/bash/etc.
|
7,439,710 | 7,439,747 | C++ Segmentation Fault on For Loop | Everything works fine right up until the last value of index 19. In fact, all values are printed and what not. Once it prints the final value & index, it seg faults. I am assuming this is because it is trying to access the 20th value. How would I prevent this from occurring?
MAIN FILE CODE:
int index = 0;
while (index ... | Your current->info is outside null checking. When current is null, you can't access its pointer and cause seg fault
|
7,439,762 | 7,439,855 | Should I extend QT widgets or use my own classes containing the widget as a member? | Learning QT (with C++), I have been defining my own classes, which are not QObjects derivates. Even if QT tutorial teach you to extend their widgets in order to make your own I don’t because I was thinking that my code would be more “portable” and less QT inherent (if that makes sense) in case I switched to another gra... | Your clas is not a proper QWidget, but I don't think it would be a problem to Qt. Unless you need to gain acces to some protected elements of wigets (eg. interact with events) you could go without ever inheriting qt widgets - the choice of design is yours.
The only reason for inheriting might be to save some memory ta... |
7,439,939 | 7,440,125 | Deallocation of 3 dimensional array | I am creating a three dimensional array like this:
GLfloat ***tgrid;
//other code in between here
tgrid = new GLfloat**[nx];
for(int i = 0; i < nx; i++)
{
tgrid[i] = new GLfloat*[ny];
for(int j = 0; j < ny; j++)
{
tgrid[i][j] = new GLfloat[nz];
}
}
Does this mean i should deallocate the memory ... | Since my answer is also yes, I will follow up K-ballo's answer with a minimal example of how to use a flat array to store a set of multi-dimension data:
Store the GLfloat pointer and the dimensions as members of your class:
GLfloat *tgrid;
int nx, ny, nz;
In initlaization function:
void CreateGrid(int x, int y, int z)... |
7,440,098 | 7,440,311 | What is the deal with shared pointer? | My program fails due to addition of a pointer to a vector. After much reading and deleting I have changed it to an addition of a shared pointer into a set (using insert) which was fine at first but now fails as well. I tried two solutions; neither worked. One failed as well and the other, the make shared kind, did not... | It's all about ownership. An entity (a function or object) is said to "own" a pointer if it is that entity's job to ensure that the pointer is deleted. Any time you use new, someone, somewhere must take ownership of the pointer returned. If this is not the case, you have a memory leak.
The purpose of all kinds of smart... |
7,440,185 | 7,440,203 | Heap or Stack? When a constant string is referred in function call in C++ | Consider the function:
char *func()
{
return "Some thing";
}
Is the constant string (char array) "Some thing" stored in the stack as local to the function call or as global in the heap?
I'm guessing it's in the heap.
If the function is called multiple times, how many copies of "Some thing" are in the memory? (And ... | String literal "Some thing" is of type const char*. So, they are neither on heap nor on stack but on a read only location which is a implementation detail.
From Wikipedia
Data
The data area contains global and static variables used by the program
that are initialized. This segment can be further classified into
in... |
7,440,422 | 7,440,837 | VS2005: How to compile projects as if it was VS6? | I have a project that I'm building with Visual Studio 2005. The sources are also used in another project that gets built using Visual Studio 6.
This results in potential errors since the new _s-functions introduced by the Security Enhancements in the CRT are not present in VS6.
To ensure that my sources are also playin... | The answer given by Sergius inspired me to run a home made way:
implement the wrappers for the secure functions in a file secure.c
checking for availability of secure functions can be done with
#if (_MSC_VER >= 1400)
take the list of the Security Enhanced Versions of CRT Functions into a file
search each pattern in my... |
7,440,636 | 7,440,724 | How can I stop the function recursion in Objective C? | I have one text field.
Below function is attached to an UI event "editing changed" from txtfield's IB.
The function is recursive as obvious I am changing the textfield so it will call
again and again is there any thing , I can stop the function after calling it once.
So,I want to stop this looping function..
-(IBActio... | Rather than using that event callback, try implementing the UITextFieldDelegate method textFieldDidEndEditing:, like so:
- (void)textFieldDidEndEditing:(UITextField *)textField
{
textField.text = [textField.text substringToIndex:
[txtEditAmount.text length] - 1];
}
So it will cut off the last... |
7,440,727 | 7,440,767 | Lack of virtual destructor when doing "delete this" | Section 16.15 of the C++ FAQ Lite discusses delete this and then mentions:
Naturally the usual caveats apply in cases where your this pointer is
a pointer to a base class when you don't have a virtual destructor.
Why is this true? Consider this code:
class ISuicidal {
public:
virtual void suicide() = 0;
};
cla... | You are misunderstanding. Implement the suicide function (ie delete this) in ISuicidal and you will find that when the this pointer is a base class calling delete on it doesn't call the derived class's destructor.
|
7,440,746 | 7,440,790 | Address of each character of std::string | I tried to print the address of each character of std::string. But I amn't understanding what is happening internally with std::string that is resulting this output while for the array it is giving the address as I expected. Could someone please explain what is going on?
#include <iostream>
#include <string>
using nam... | When a std::ostream tries to print a char* it assumes it's a C-style string.
Cast it to a void* before printing and you will get what you expect:
cout << (void*) &str[i] << endl;
|
7,440,749 | 7,440,840 | Executable generated with clang++ goes crazy | #include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
using namespace std;
class Book{
public:
int a;
int b;
};
int main()
{
Book b1;
b1.a = 10;
b1.b = 20;
cout<< b1.a << " " <<b1.b;
}
when we compile the above code with
clang++ test.cc -o a.exe
and run a.exe wo... | By adding '-emit-llvm -S' you are not generating machine code, but LLVM bytecode. To run that, you need to use lli.
As ntvdm.exe is virtual machine for running real-mode DOS programs, it might mean that windows interprets executable in LLVM bytecode as 16-bit DOS program and tries to run it as one.
|
7,440,798 | 7,441,391 | Winsocks 2 Asynchronous Problem | I am trying to use winsock2 in asynchronous mode. I am able to send messages from client to server, but not from server to client. When I call recv on client side, nothing is received in the buffer.
Here is my client code
ClientSocket::ClientSocket (HWND& pHwnd)
{
WSADATA wsdata;
vSzIncoming = 0;
... | It's difficult to say where your problem is. The best solution is to systematically remove all possible roadblocks:
Check the return value of recv. If there is an error your buffer is untouched so an "empty" string is returned.
Check on your server side if the correct client socket is used. You use the "Socket"-variab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.