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 |
|---|---|---|---|---|
3,820,908 | 3,822,075 | Count how many times each distinct word appears in input | I'm working on an exercise from Accelerated C++:
Write a program to count how many times each distinct word appears in its input.
Here's my code:
#include <iostream>
#include <string>
#include <vector>
int main()
{
// Ask for
// and read the input words
std::cout << "Please input your words: " << std::... | Assuming that std::vector is the only container you're acquainted with at this point, and that you haven't gotten to std::pair yet, I suggest the following:
you add a std::vector<int> word_count
in your std::cin while-loop, you check if the current word is present in word_input. If it is not, you push_back the word an... |
3,821,064 | 3,821,091 | Call a base class constructor later (not in the initializer list) in C++ | I'm inheriting a class and I would like to call one of its constructors. However, I have to process some stuff (that doesn't require anything of the base class) before calling it. Is there any way I can just call it later instead of calling it on the initializer list? I believe this can be done in Java and C# but I'm n... |
Is there any way I can just call it later instead of calling it on the initializer list?
No, you cannot. The base class constructor must be called in the initializer list, and it must be called first.
In fact, if you omit it there, the compiler will just add the call implicitly.
I believe this can be done in Java an... |
3,821,072 | 3,821,101 | Is there a C++ equivalent of Objective-C's autorelease? | I can write a function this way in Objective-C. This can be used to churn out many UIButtons.
+(UIButton*)getButton:(CGRect)frame{
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Some title" forState:UIControlStateNormal];
button.frame=frame;
return button;
}
Can the same be... | In C++ you can do
CString* getCString(some parameters)
{
CString* string = new CString(L"Hi sample string.");
return string;
}
and delete (by calling delete on the pointer) the string in the caller after he is done with it if you want to have the string on the heap. However in the first version you posted, ... |
3,821,107 | 3,824,129 | What's the cleanest way to defeat C++ access qualification? | I decided to work around a bug in GNU libstdc++ by accessing an internal variable. Recalling that Johannes solved the problem on his blog, I checked that out… but couldn't comprehend the code, aside from the basic concept of getting a static initializer to do the dirty work. So, I boiled it down to this, which is prett... | Bah, it was too late when I posted this… I should've slept on it.
I can avoid both the static initialization order fiasco and the duplication problem by making the variables truly global, and merely initializing them multiple times. Since the initialization value is the same each time, it doesn't matter when they happe... |
3,821,261 | 3,821,277 | NULL check before deleting an object with an overloaded delete | This came up as one of the code review comments.
Is it a good idea to check for NULL before calling delete for any object?
I do understand delete operator checks for NULL internally and is redundant but the argument put forth was delete as an operator can be overloaded and if the overloaded version doesn't check for t... | No, don't check for null. The standard says that delete (T*)0; is valid. It will just complicate your code for no benefits. If operator delete is overloaded it's better to check for null in the implementation of the operator. Just saves code lines and bugs.
EDIT: This answer was accepted and upvoted, yet, in my opinion... |
3,821,327 | 3,821,364 | How to break with GDB at object destruction if there is no destructor? | How to break with GDB at object destruction if there is no destructor?
| If there's no destructor, you cannot break on the destructor, as there is no op-code for the destructor. You have two choices on where to break:
If the object is allocated on the stack, break on the closing brace of the scope defining the variable.
If the object is allocated on the heap, break on the delete statement.... |
3,821,367 | 3,846,175 | Boost Intrusive List hook | What is the difference in a base hook and a member hook in Boost::Intrusive library and when is one better to use then the other?
I've read the boost documentation, but its not that explanatory.
| As far as I can tell it is a matter of style and object-oriented design. Base hooks intrude upon the inheritance hierarchy, necessitating an extra public parent class and possibly forcing multiple inheritance upon the design. Using member hooks allows the programmer to treat an object as having a has-a relation with a ... |
3,821,497 | 3,821,599 | is there a browser object/class for g++? | I am looking for a browser class that can be created in a terminal program in g++ that will create a page in memory and execute client JavaScript.
environment is Linux, server is h ubuntu 10.04 there is no GUI installed, program would be an occasional cron script.
is there such an animal?
edit: removed vbscript
| I particularly like Google V8 for this.
|
3,821,618 | 3,821,679 | What is wrong with using a static member object with a class? | I have heard that using static member objects is not a very good practice.
Say for example, I have this code:
class Foo {
...
static MyString str;
};
I define and initialize this variable in the implementation file of this class as:
MyString Foo::str = "Some String"; // This is fine as my string API handles this.
Whe... | Most of the arguments against them are the same as for global variables:
Initialization order between different compilation units is undefined.
Initialization order inside one compilation unit may affect the behavior — thus non trivial ordering may be required.
If a constructor throws an exception you can't catch it, ... |
3,821,852 | 3,822,007 | Why is "operator delete" invoked when I call "delete" on a null pointer? | While reading answers to this question I noticed that answers (this for example) imply that operator delete can be called even when delete statement is executed on a null pointer.
So I wrote a small snippet:
class Test {
public:
void* operator new( size_t ) { /*doesn't matter*/ return 0; }
void operator delete(... | The language in the upcoming C++0x standard (section 5.3.5 [expr.delete]) is as follows:
If the value of the operand of
the delete-expression is not a null
pointer value, the delete-expression
will call a deallocation function
(3.7.4.2). Otherwise, it is
unspecified whether the deallocation
function will ... |
3,822,612 | 3,822,630 | Should I use boost::ptr_vector<T> or vector<boost::shared_ptr<T> >? | I need a container of pointers. Would you recommend boost::ptr_vector<T> or std::vector<boost::shared_ptr<T> >? (Or something else?)
If that's of interest, my actual data structure is relatively complicated (see here) and currently stores objects, not pointers, but i'd like to change that (using pointer containers), in... | Who owns the object? If the container owns the objects (meaning the objects should not live longer than the container), use a ptr_vector. Otherwise, use a vector of shared_ptrs. Standard library containers (such as std::vector or std::list) own the objects they contain, so the semantics of a ptr_vector is closer to tha... |
3,822,640 | 3,822,749 | How to resize a window using WM_* messages | When a window handle is given, how can i exactly resize a window sending windows messages towards it? I've tried many things such as sendig a WM_SIZING Message to the window, but nothing worked(the way i did it).
I don't like to use SetWindowPosition.
Thanks in advance,
David
| WM_SIZE and WM_SIZING are not commands, they are notifications sent by SetWindowPlacement. You can use that or any of the conveniece API available, including SetWindowPos and MoveWindow.
|
3,822,999 | 3,823,031 | GetFileSizeEx corrupts file handle | Currently I'm using GetFileSizeEx to track how large a log files gets before I write to it. We have limited space and anything if we try to create a file larger than 100 megabytes we stop logging data. The problem is for some reason GetFileSizeEx will corrupt the file handle that I am using.
if( hFileHandle != INVALID_... | Try using LARGE_INTEGER instead of PLARGE_INTEGER. Normally PLARGE_INTEGER is a pointer, not a value.
|
3,823,049 | 3,823,570 | Templated method with overloaded name | To be consistent with other classes in a library, my array class below has two read() methods. The first reads the entire array to an output iterator and returns an error code, the second reads a single value and returns that (using exceptions for errors).
The problem I have is that if I call the second read(size_t id... | Furthermore, I don't think size_t is guaranteed to be a synonym for unsigned, so even with the "u" suffix the code might not be portable.
std::string has a similar problem that it has to distinguish between:
string s(10, 97); //size_t, char
string t(s.begin(), s.end()); //iter
That would internally forward the call t... |
3,823,050 | 3,823,304 | DLLImport c++ function with default parameters | I am trying to import a function from an unmanaged code c++ dll into my c# application. The c++ prototype is
int somefunction (int param1, int *param2 = NULL);
How do I declare this in c# to take advantage of the default nature of param2? The following code does not work. param2 gets initialized with garbage.
DllIm... | If you are using C# 4.0 then dtb`s answer is the right approach. C# 4.0 added optional parameter support and they work just as well with PInvoke functions.
Prior to C# 4.0 there is no way to take advantage of the optional parameter. The closest equivalent is to define one function that forwards into the other.
[Dll... |
3,823,058 | 3,823,124 | Is string::c_str() allowed to allocate anything on the heap? | If I need to get a NUL-terminated char array out of a std::string in a situation where I need to be sure nothing will be allocated, is it safe to use c_str to do so? For example, if I'm inside a destructor and I want to copy some data from a string into a pre-allocated, fixed-size buffer, can I use c_str and be sure it... | The standard says that calling c_str() may invalidate references, pointers, and interators referring to the elements of the string, which implies that reallaocation is permitted (21.3/5 "Class template basic_string").
You might want to just call string::copy() to get your copy (you'll need to add the null terminator yo... |
3,823,091 | 3,823,520 | Files reading differently in linux? C++ | I'm a fairly new programmer, but I consider my google-fu quite competent and I've spent several hours searching.
I've got a simple SDL application that reads from a binary file (2 bytes as a magic number, then 5 bytes per "tile")
it then displays each tile in the buffer, the bytes decide the x,y,id,passability and such... | Your array handling is incorrect.
Array indexing in C/C++ begins from 0.
You have defined 'tile_buffer' to be an array sized 'BYTES_PER_TILE'.
If BYTES_PER_TILE was 5, your array would have elements tile_buffer[0] to tile_buffer[4].
In your inner for-loop you loop from 1 to 5 so a buffer overflow will occur.
I don't kn... |
3,823,136 | 3,823,242 | How and when to properly use *this pointer and argument matching? | When I go thru the code written by collegue, in certain place, they use:
this->doSomething(); //-->case A
doSomething(); //-->case B
In fact I'm not sure about the great usage of *this pointer...:(
Another question with argument matching:
obj.doOperation(); //-->case C
(&obj)->doOperation(); //-->case D
In fact both... | This is not an answer to your question, but a note that both fragments may do different things:
namespace B { void doSomething() {} }
struct A {
void f()
{
using B::doSomething;
this->doSomething(); // call A::doSomething
doSomething(); // calls B::doSomething
}
int a;
... |
3,823,287 | 3,823,324 | C++ inheritance, base methods hidden | I have a simple C++ base class, derived class example.
// Base.hpp
#pragma once
class Base
{
public:
virtual float getData();
virtual void setData(float a, float b);
virtual void setData(float d);
protected:
float data;
};
//Base.cpp
#include "stdafx.h"
#include "Base.hpp"
float Base::getData()
{
... | This is an artifact of C++ name lookup. The basic algorithm is the compiler will start at the type of the current value and proceed up the hierarchy until it finds a member on the type which has the target name. It will then do overload resolution on only the members of that type with the given name. It does not con... |
3,823,359 | 3,832,849 | Using QStyle to set global default minimum QPushButton height | Is it possible to define a default minimum height for a QPushButton through a custom application wide QStyle?
I know this can be achieved using stylesheets, but I rather not use them because of performance reasons.
| You might consider looking at the QApplication::globalStrut property, which is designed to provide a minimum size for any user-interactive UI element. Ideally, it would do what you want (and possibly more). However, I have seen times when this was ignored, either by the widget or the style drawing the widget, so in p... |
3,823,408 | 3,823,464 | forward declaration generates incompatible type error | I've been reading some on forward declarations, including in this forum. They all say that it saves us from including the header file, However the following code generates an error:
#ifndef CLASSA_H_
#define CLASSA_H_
class B;
class A {
public:
A();
~A();
int getCount();
private:
static int _count;
... | The compiler has to know the exact definition of class B to determine at least what size to give to class A. If you use a pointer, it knows its size.
Note that circular dependencies are not possible. If you want
class A { B b; };
class B { A a; };
then A and B must have infinite size...
|
3,823,625 | 3,823,904 | Why BOOST_AUTO_TEST_CASE is not working? | I'm doing something wrong but I do not know what. Here are my files:
//main
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
//MyFoo.h
#pragma once
#include "stdafx.h"
class MyFoo
{
public:
MyFoo(void){};
int multiplyByTwo(int value);
~MyFoo(void){};
};
//MyFoo.cpp
#include... | Remove _tmain - it's not needed, and the test never executes if you have this there.
Verified on Win32 Visual Studio 2008, output is:
Running 1 test case...
c:/temp/test/test.cpp(25): fatal error
in "my_test": critical check
a.multiplyByTwo(2) == 5 failed
|
3,823,711 | 3,824,920 | C++ Detecting an implicit cast of 0 to a class | I am calling a function in a API that returns a Answer object. Under some conditions, the API will return EMPTY_answer, which is defined as such:
#define EMPTY_answer ((Answer)0)
of course, attempting to access a Answer variable or function from an EMPTY_answer object crashes the application.
Trying to test for it us... | If Answer is a class type, as the text of your questions suggest, then (Answer) 0 will construct a temporary Answer object using the constructor that accepts 0 as an argument (apparently such constructor exists). In this case attempting to access the members of that object will not crash anything, unless Answer class i... |
3,823,878 | 3,823,976 | Mapping a string to a unique number? | Is there a nice bash one liner to map strings inside a file to a unique number?
For instance,
a
a
b
b
c
c
should be converted into
1
1
2
2
3
3
I am currently implementing it in C++ but a bash one-liner would be great.
| awk '{if (!($0 in ids)) ids[$0] = ++i; print ids[$0]}'
This maintains an associative array called ids. Each time it finds a new string it assigns it a monotically increasing id ++i.
Example:
jkugelman$ echo $'a\nb\nc\na\nb\nc' | awk '{if (!($0 in ids)) ids[$0] = ++i; print ids[$0]}'
1
2
3
1
2
3
|
3,823,906 | 3,824,252 | Why does this dialog box close immediately after opening? | My issue is that I am trying to create a Opengl/Win32 application and I am unable to keep my dialog box open. It literally flashes as if someone pressed cancel on it RIGHT when it opened.
I've looked around google and found a few others with this issue, but none of the solutions they posted have helped me, so I turn to... |
DialogBox does not return a hwnd, the function does not return until the dialog is closed, if you want a modeless dialog and a handle, use CreateDialog
The DLGPROC DialogBox parameter should not require a cast, change LoginDlgProc' LRESULT to INT_PTR
MessageBox(NULL, NULL, NULL, MB_OK); will not display anything, it n... |
3,823,913 | 3,823,943 | why C# and C++ use _<variableName> coding convention? | I have seen too much C# and C++ code where the variable naming convention seems to ask programmers to write variable names using underscore before the text of the variable. e.gr.
int? _countMoney;
What's the rationale supporting that convention?
| In C# I usually prefix with _ private fields but never local variables. The rationale behind this is that when I need a private variable I type _ and the Intellisense filters the list and it is easier to find. This way I am also able to distinguish between private from local variables and I no longer need to type this.... |
3,823,921 | 3,823,994 | Convert big endian to little endian when reading from a binary file | I've been looking around how to convert big-endian to little-endians. But I didn't find any good that could solve my problem. It seem to be there's many way you can do this conversion. Anyway this following code works ok in a big-endian system. But how should I write a conversion function so it will work on little-endi... | Assuming you're going to be going on, it's handy to keep a little library file of helper functions. 2 of those functions should be endian swaps for 4 byte values, and 2 byte values. For some solid examples (including code) check out this article.
Once you've got your swap functions, any time you read in a value in the ... |
3,824,058 | 3,824,103 | istream parse EVENT_TYPE(param1;param2; ...) | I'm trying to find an elegant way to parse a string like:
EVENT_TYPE(param1;param2; ...)
EVENT_TYPE is one of many string constants, each has zero or more parameters.
So far I thought that given the sting "s" contains EVENT_TYPE(param1;param2) I'd write:
if (boost::istarts_with(s, "EVENT_TYPE")) {
std::istringstream... | This looks complicated enough to warrant a "real" parser. Since you're already using Boost, try this first: http://boost-spirit.com/home/
|
3,824,078 | 3,824,195 | Why does calling std::stringstream's good() through a pointer lead to crashes? | I am having problems with a stringstream object. My class has an input stream as a member.
I am checking if obj->istream and after thatn if obj->istream->good().
The stream exists but the call to good() crashes. I am in Visual Studio 2005. Any clue?
How do I reset an istream?
if (soap->is) {
if (soap->is->good())
... | This probably indicates that your is member does not point to a stringstream. It might just be initialized to some garbage value when enclosing object is instantiated.
If you are testing for pointer being zero, make sure it's set to zero in the constructor (and reset to zero if you ever detach the stream).
|
3,824,198 | 3,824,293 | Using DYLD interposing to interpose class functions | I have succesfully using dyld -macosx- to interpose standard C functions to a third party application, getting important information about the workarounds it does. But what I really need is to replace a certain function of a certain class.
The function I want to override is QString::append(..., ..., ...), so each time ... | C++ does name mangling. This means member function QString::mid() looks something like __ZNK7QString3midEii to the linker. Run the nm(1) command on the library you are interposing on to see the symbols.
|
3,824,213 | 3,824,241 | does order of members of objects of a class have any impact on performance? | May order of members in binary architecture of objects of a class somehow have an impact on performance of applications which use that class? and I'm wondering about how to decide order of members of PODs in case the answer is yes since programmer defines order of members via order of their declaraions
| Absolutely. C++ guarantees that the order of objects in memory is the same as the order of declaration, unless an access qualifier intervenes.
Objects which are directly adjacent are more likely to be on the same cacheline, so one memory access will fetch them both (or flush both from the cache). Cache effectiveness ma... |
3,824,221 | 3,824,398 | Volume to physical drive | QueryDosDevice(L"E:", DeviceName, MAX_PATH);
(E: is a SD card)
DeviceName is "\Device\HarddiskVolume3"
How do I "convert" it to something like "\\.\PHYSICALDRIVE1"
| Volumes are made up of one or more partitions, which reside on disks. So, E: doesn't necessarily map to a single disk in the system (think software RAID).
The way you map volumes to the PhysicalDrive names in Win32 is to first open the volume and then send IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS. This will give you a stru... |
3,824,571 | 3,824,708 | Array to Hex Representation | I am writing a program that needs to take an array of size n and convert that into it's hex value as follows:
int a[] = { 0, 1, 1, 0 };
I would like to take each value of the array to represent it as binary and convert it to a hex value. In this case:
0x6000000000000000; // 0110...0
it also has to be packed to the r... | The following assumes that your a[] will only ever use 0 and 1 to represent bits. You'll also need to specify the array length, sizeof(a)/sizeof(int) can be used in this case, but not for heap allocated arrays. Also, result will need to be a 64bit integer type.
for (int c=0; c<array_len; c++)
result |= a[c] << (63-c)... |
3,824,696 | 3,824,747 | Aligning text to the right in the C++ console | How do I format my console output so that it's aligned to the right in C++?
| Use the manipulator flag std::right
Example
or
This works...
#include<iostream>
using std::cout;
using std::endl;
#include<iomanip>
using std::setw;
int main(){
int x = 12345;
cout << "Blah Blah Blah" << endl << setw(80) << x << endl;
system("pause");
return 0;
}
|
3,824,703 | 3,824,764 | Performance issues when reading a file from HD that dosen't follow computer byte alignments | I have a file format (.STL, stereo lithography, the structure is standard and can not be changed. Not to be confused with standard template library) that uses a 50 byte data structure. Reading from the HD directly leads to wrong data being read as 50 bytes is not a multiple of 4.
Out of the entire 50 byte structure, I ... | Instead of doing a bunch of small seeks & reads, allocate a large buffer (say, enough for 1000 structures) and read a bunch of records at once. (Then iterate through that buffer copying out the 36-byte chunks you need).
|
3,824,822 | 3,824,893 | How to create pool allocator for abstract base class in C++? | Have run into a bug with glibc's malloc(): http://sourceware.org/bugzilla/show_bug.cgi?id=4349 and am thinking a work around for now until updating to later version of glibc is to do pooled allocation for small objects that have many instances coming and going.
The small objects are all derived from an abstract base cl... | One obvious starting point would be the Boost Pool library. Unfortunately, the model you want is one it doesn't provide yet, although it is listed as the sole item under "future directions". OTOH, this library hasn't been updated in a while now. The chances of it being updated to include that model really soon seems so... |
3,824,874 | 3,825,020 | cublas link in visual studio | I am trying to use cublas.h in visual studio. The program doesn't compile because it can't find some of the external link. Can some one tell me how to link the .dll file, I believe it is in ../C/common/bin.
| You need to link to the lib file, not the DLL.
|
3,824,886 | 4,635,278 | CUDA Linking Error Visual Studio 2008 | Hi I am getting the following Linking error while compiling ConvolutionFFT2D from CUDA src
1>------ Rebuild All started: Project: FinalTest, Configuration: Release Win32 ------
1>Deleting intermediate and output files for project 'FinalTest', configuration
'Release|Win32'
1>Compiling with CUDA Build Rule...
... | Add cufft.lib in Linker->Input->Additional Dependencies ..... And it will work fine
|
3,824,890 | 3,825,323 | C++ library to discover sql database schema for multiple vendors? | Just wondering if anyone knows of a C++ library that provides a single interface for querying database schema (tables, fields, field types), and for a variety of vendors? I know DTL does this to some degree, although I haven't dug into the details of how it does it, or if it makes that info available external to itsel... | That can be done with ODBC.
|
3,824,921 | 3,825,010 | Error handling in C++ | How do I make it so that the cin statement only accepts integers?
| I don't think you can force std::cin to refuse to accept non-integral input in all cases. You can always write:
std::string s;
std::cin >> s;
since the string doesn't care about the format of the input. However, if you want to test whether reading an integer succeeded you can use the fail() method:
int i;
std::cin >... |
3,824,950 | 3,825,063 | Are there any static analysis tools that can help detect shared_ptr<> circular references? | Are there any static analysis tools that can help detect shared_ptr<> circular references?
Even if such a tool couldn't detect complicated cases, it would still be useful for eliminating the simple cases.
| Don't know about existing of such tools, but here are nice thoughts about the problem:
The key to effective object life time management
is to have an acyclic object ownership graph.
Then you use shared pointers when going down,
weak pointers when going sideways,
and weak pointers (or sometimes plain pointers) ... |
3,825,008 | 3,825,456 | error: boost.fusion::for_each() and struct derived from boost.tuple | on compilation this code:
struct any_type: boost::tuple<std::string, std::string, std::string> {
...
};
struct functor {
void operator()(const std::string& v) {
std::cout << v << std::endl;
}
};
int main() {
any_type type;
boost::fusion::for_each(type, functor());
}
get error: no type named 'cat... | Inherit from boost::fusion::tuple instead of boost::tuple.
Note: Consider making void operator()(const std::string& v) const
|
3,825,321 | 3,841,063 | Network Not Available Error when trying to map network drive | I'm calling WNetAddConnection2 during the login process for a 2008R2 box. The action happens right after userinit is run. I'm receiving a 1222 error or Network Not Available. Right after doing this I'm also connecting a couple printers using the AddPrinterConnection function. Both the printers and the network drives ar... | Could be a timing issue (network startup still in progress while first call is made). Have you tried reversing the order of the calls?
It's also possible that AddPrinterConnection (which blocks) waits for resources to be available whereas the other does not. have you tried connecting all resources using WNetAddConnec... |
3,825,350 | 3,826,116 | VS2008 not linking to all functions in a library | Our project is a VS2008 based project using Boost and Qt heavily. However, today we have a new linking problem that doesn't make any sense.
What is happening is that during the link
For program A, our static library Foobar is finding links to 5 of the 8 member functions.
For program FoobarUnitTest, everything from Fo... | Hard to give any meaningful advice for such a nebulous question but here are a couple things to check out. The linker reports "unresolved externals" when the header says there's a function named "x::y()" but it can't find that function in the lib file. Keep in mind that this assumes you have in fact implemented the f... |
3,825,392 | 3,825,435 | string to float conversion? | I'm wondering what sort of algorithm could be used to take something like "4.72" into a float data type, equal to
float x = 4.72;
| scanf, operator>> for istreams, and strtof would be the obvious choices.
There is also atof, but, like atoi, it lacks a way to tell you there was an error in the input, so it's generally best to avoid both.
|
3,825,553 | 3,825,769 | Convert Hex String to Hex Value | I have a large hex string
abcdef...
and I want to convert it to
0xab 0xcd 0xef
Are there any functions that do that?
Also could you tell me what I means when people ask are those inputs in ASCII or not?
abcdef are represented as a string. Not sure if that is ASCII or not. not sure what they mean. I am very new to ... | You can do this using string streams.
#include <iostream>
#include <sstream>
#include <vector>
int main( int , char ** )
{
const char *str = "AFAB2591CFB70E77C7C417D8C389507A5";
const char *p1 = str;
const char *p2 = p1;
std::vector<unsigned short> output;
while( *p2 != NULL ) {
unsigned short byte;
... |
3,825,632 | 3,825,708 | Does std::map<key, data> in C++ support native data types like Structures? | How do I map a key to a native data type like structure?
I wrote this snipped but I couldn't compile it. Do you have any ideas on how to fix it?
#include <map>
#include <iostream>
typedef struct _list
{
int a,b;
}list;
map<int,list> test_map;
int main(void)
{
cout <<"Testing"<< endl;
}
| A number of problems here:
You're missing either a using::std or std::map, so the compiler doesn't know what map<int,list> means.
Assuming you have a using namespace std declaration, your typedef list might collide with the STL collection of the same name. Change the name.
Your typedef struct _tag {...} tag; construc... |
3,825,647 | 3,825,674 | C# interface C++ DLL? | How do I call functions from a C++ DLL?
The C++ DLL contains functions like this:
__declspec(dllexport) bool Setup () { return simulation.Setup (); }
The C# program does this:
[DllImport("mydll.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Setup();
The C# program crashes with the follow... | This error occurs when you try to load a 32-bit DLL into a 64-bit process. (Or vice-versa)
Until VS2010, C# projects are target any CPU by default and will run as 64-bit on a 64-bit OS.
You need to go to the Build tab in Project Properties and set the C# project to x86 only.
|
3,825,668 | 3,825,704 | Checking for NULL pointer in C/C++ | In a recent code review, a contributor is trying to enforce that all NULL checks on pointers be performed in the following manner:
int * some_ptr;
// ...
if (some_ptr == NULL)
{
// Handle null-pointer error
}
else
{
// Proceed
}
instead of
int * some_ptr;
// ...
if (some_ptr)
{
// Proceed
}
else
{
// H... | In my experience, tests of the form if (ptr) or if (!ptr) are preferred. They do not depend on the definition of the symbol NULL. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.
Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as aut... |
3,825,711 | 3,825,735 | const correctness problem with copy constructor? | I am trying to wrap a C structure in a C++ class to take advantage of memory management and such. I have mad the structure a private member and provided a public function to provide access. The return type is constant, since all functions that take the object as an argument have const in their signature.
#include <gsl/... | Make rng() const function: const gsl_rng* rng() const {.
|
3,825,727 | 3,825,886 | COM Interop: indexed property signature issues | I'm working on a project that's a .NET extension to a rather large classic ASP project, using a lot of C++ COM objects that have been around in our code base forever. Unfortunately, there's a lot of hack-ish code on the C++ side, and I fear that I'm not experienced enough to work out the problem I've encountered.
In a... | Hmm, your code suggest that you do in fact use C# 4.0 since you're using named parameters. That version does support indexed properties in COM interop scenarios. Indexer syntax however requires [square brackets]. No idea if it still works with more than one argument, the examples all have just one. Try this first:
... |
3,826,082 | 3,830,454 | BOOST_PP_ITERATE() result in "no such file or directory" | I'm learning the boost preprocessor library (because i need to use it), and I wanted to try the file iteration mechanism. I've set up a minimal project with a.cpp and b.hpp. What I'm trying to do is including many time b.hpp via the boost pp :
#include <boost/preprocessor/iteration/iterate.hpp>
#define BOOST_PP_ITERAT... | Yep, you need to add -I. to the command line in order to make it work. This adds the directory you started gcc in to the include search path, allowing the compiler to find the file b.hpp.
|
3,826,090 | 3,826,208 | Why does the F# Bitwise Operator pad with 1's for signed types? | I was looking at F# doc on bitwise ops:
Bitwise right-shift operator. The
result is the first operand with bits
shifted right by the number of bits in
the second operand. Bits shifted off
the least significant position are not
rotated into the most significant
position. For unsigned types, the most
signi... | To answer the reformed question (in the comments):
The C and C++ standards do not define the result of right-shifting a negative value (it's either implementation-defined, or undefined, I can't remember which).
This is because the standard was defined to reflect the lowest common denominator in terms of underlying inst... |
3,826,108 | 3,826,343 | Has anyone an example for wrapping a function in C++? | I have searched online a lot but I couldn't find an example that works with g+, all examples work with GCC.
The error I keep getting is:
wrap_malloc.o: In function `__wrap_malloc(unsigned int)':
wrap_malloc.cc:(.text+0x20): undefined reference to `__real_malloc(unsigned int)'
wrap_malloc.o: In function `main':
wrap_mal... | When you use a C++ compiler, all names are mangled. What this means becomes clear when you run nm wrap_malloc.o, which should give you something like this:
00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
U __Z13__real_mallocj
00000000 T __Z13__wrap_mallocj
U _printf
This means tha... |
3,826,197 | 3,826,218 | Implicit cast through constructor with multiple arguments | If I have these 2 constructors for MyClass:
MyClass(int n1);
MyClass(int n1, int n2);
and an overloaded (non-member) operator+:
MyClass operator+(MyClass m1, const MyClass& m2);
This enables me to write code like this:
MyClass m;
5 + m:
which I guess uses an implicit cast through the defined constructor, correct?
Is... | In a word, no. The most succinct option is MyClass(15,8) + m;.
|
3,826,281 | 3,826,335 | How do I make a C++ program that filter out non-integers? | Something like this
cout << "Enter the number of columns: " ;
cin >> input ;
while( input != int ){
cout << endl <<"Column size must be an integer"<< endl << endl;
cout << "Enter the number of columns: " ;
cin >> input ;
}
| cin will do this for you, kind of. cin will fail if it receives something that is not of the same type as input. What you can do is this:
int input;
while(!(cin >> input))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl <<"Column size must be an integer"<< endl << endl;
... |
3,826,481 | 3,826,513 | Accessing a Pointer to a pointer in C++ | Hi I am using a 3rd party library in my iPhone application that uses C++ one of the methods i need to use returns a pointer to a pointer of a class. like follows.
DLL classAttributes** getAttributes();
I can successfully call the method and return the value into a pointer to a pointer like so;
classAttributes **attrib... | 'invalid uses of incomplete type 'struct attributes' indicates that you need to #include the header file for it. It's only forward-declared at this point in your code.
|
3,826,524 | 3,826,625 | Using kbhit() to pause terminal output? | I took my first 'fundamentals of programming' lab session at uni today. One thing struck me as odd, though: the use of while(! _kbhit()) from conio.h (which I'm sure is a C unit?) to 'pause' the console output.
Is this the best way to do this? What do I need to watch out for when using it? Is my tutor absolutely bonker... | A very quick (and easy to remember) way of doing this is to use getchar:
getchar();
You may have to press Return after entering your char, depending on stdin's buffering mode. You can probably use setvbuf to fix that, but personally I just always press Return.
You may also be using C++ iostreams. In that case, you'll ... |
3,826,602 | 3,826,614 | What is the normal convention for naming and using iterators in C++? | I feel like I'm unprofessional in the way I name and use iterators. What I mean by that is that I "feel" like I should be calling them something else, but I always name them based on the "it_" prefix, and after a while, in a long function, the names start to all look alike.
Additionally, I always wonder if I'm doing th... | I try to declare the iterators inside the for loop as much as possible, so that the scope of the iterator identifier is minimized.
First, I typedef the "long" type names to "shorter" and re-usable ones:
typedef std::map< int, int > IntMap;
typedef IntMap::const_iterator IntMapConstIter;
Then, I do
for( IntMapConstIter... |
3,827,246 | 3,827,274 | Is it possible to read dos files in linux using an ifstream | When I use the std::ifstream to open a file that has been written in dos format, the ifstream does not seem to be able to open the file correctly since when I call good() on the stream afterwards it fails (returns false). I tried opening the file in binary mode as well as the default "in" mode and neither worked. If ... | The file format will NOT affect your ability to open it.
It is more likely that your path is not correct.
|
3,827,320 | 3,827,355 | Simple class concepts in C++ (cards in a deck) | Classes confuse me! For this particular assignment, we are to do the classic 'Cards in a Deck' program. We are to make two classes, one called 'Card' and the other 'Deck'. Now I've gotten a large chunk of this done so far but a concept seems to be escaping me.
When we call a default constructor for the Card class, all ... | There are always a hundred ways to do something. For me, when creating classes and the structure of my program, I always think how things are related to each other.
In your problem, Cards in a Deck, the relationship is stated. Each Card object belongs to a Deck. I would start by creating the Card class as it has nothin... |
3,827,352 | 3,827,385 | Global variables in C++ | I am working with some C++ code that has a timer and the timer runs this:
char buf[1024];
ZeroMemory(&buf, sizeof(buf));
somefunction(buf); // this put stuff into buf
otherfunction(buf); // this do stuff with buf
somefunction() does a web request and InternetReadFile() puts the data in "buf"
But I need to be able to r... | If you don't have to deal with multiple threads accessing the timer action function simultaneously, you can make buf into either a static variable within the scope of the function, or a file variable in the anonymous namespace (or, if you are an unreformed C programmer like me, into a file static variable). You then m... |
3,827,374 | 3,827,386 | C++ Virtual Const Function | Given the following snippet,
class Base
{
public:
virtual void eval() const
{
std::cout<<"Base Const Eval\n";
}
};
class Derived:public Base
{
public:
void eval()
{
std::cout<<"Derived Non-Const Eval\n";
}
};
int main()
{
Derived d;
Base* pB=&d;
pB->eval(); //Thi... | This is because one is declared const and the other isn't. One function is being hidden by the other. The function in Derived is hiding the one in Base because they have the same name while they aren't the same function.
My compiler gives a warning here, does yours?
|
3,827,463 | 3,827,727 | Having a constant to be used across entire application. Use #define or variable |
Possible Duplicate:
static const vs #define
Hello all, in C++, to define a constant to be used across the entire application, what is your guys usual practice?
#define WINDOWS_HEIGHT 1024
or
const int WINDOWS_HEIGHT = 1024;
Thanks.
| Pros and cons to everything, depending on usage:
enums
only possible for integer values
properly scoped / identifier clash issues handled nicely
strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control (in C++03)
can't take the address
stronger usage restraints (e.g. incrementing... |
3,827,668 | 3,827,745 | Programming language suggestion for Windows app to connect to Sybase database | I am writing a Windows application that will connect to a Sybase database through an ODBC connection.
It will dynamically create a SQL statement based off of selections by the user in the GUI.
It needs to be fast (1M+ records sometimes) and have the ability to export to Excel, or some other reporting tool (graphs, etc... | All of the .Net languages (C#, Managed C++ and VB) have access to the same runtime library. C# and VB are both simpler than Managed C++, and personally I prefer C# to VB (but that's a matter of taste).
You might also want to consider Java as it's also used extensively in enterprise applications that for database trans... |
3,827,926 | 3,827,946 | What does string::npos mean in this code? | What does the phrase std::string::npos mean in the following snippet of code?
found = str.find(str2);
if (found != std::string::npos)
std::cout << "first 'needle' found at: " << int(found) << std::endl;
| It means not found.
It is usually defined like so:
static const size_t npos = -1;
It is better to compare to npos instead of -1 because the code is more legible.
|
3,827,929 | 3,828,037 | Operator error in template | I am trying to create a "value" template class, where additional properties can be assign to it easily.
Properties are stored in std::map<std::string, std::string>, and operator[] has been overloaded to provide quick access to them.
#if ! defined __VALUE_H__
#define __VALUE_H__
#include <string>
#include <map>
namespa... | obj["AA"]... have you seen a similar construct before? There is an old C obfuscation trick where you take the array and the index and reverse them in the expression as a[b] is the same as *(a + b) which is the same as b[a]. In the cast overload in this case, you are returning a integer. The other element of the call is... |
3,827,955 | 3,828,057 | Constructor help with const C-string array | I have a simple class Name:
class Name
{ private:
char nameStr[30];
public:
Name(const char * = "");
char * getName() const;
void print() const;
};
I am having two problems, which are just a bit difficult for me wrap my head around. The constructor is supposed to take an argument of const char * a... | I would recommend you use an std::string, but first you need to know how pointers work.
Let's take your first problem: &nameStr = setName;
Here, nameStr is an array of chars, for storing your name. &nameStr refers to the address of this array. You cannot set the address of a variable of any sort, it is illegal. For exa... |
3,828,004 | 51,070,651 | Is there a portable equivalent of gcc's __attribute__ (pure)? | I'm writing some code where there are a bunch of simple pure functions that get called a lot. It's perfectly safe if these functions get get optimized to be called less often.
Currently I am using gcc as my compiler and I'm wondering if there is a portable way of doing:
int foo(int) __attribute__ ((pure))
Info about t... | Since C++11, you can use the standardized attribute syntax with GCC specific attributes:
[[gnu::pure]]
int foo(int)
Since C++17, this is guaranteed to be fine on any compiler, since if they don't recognize [[gnu::pure]], they must ignore it without error.
|
3,828,022 | 3,828,045 | Generating Vector of Random Number (of Size M) from -K to K in C++ | Is there a fast way to do that?
| I suppose you could do this with rand:
for (int i = 0; i < M; i++)
{
v.push_back(rand()%(2*K)-K;
}
But I need to know more about your question. Is the interval [-K,K] or (-K,K)? Do you include -K and K or not?
|
3,828,069 | 3,829,070 | c++ string in C struct, is it illegal? | struct run_male_walker_struct {
string male_user_name;
string show_name;
};
typedef struct run_male_walker_struct run_male_walker_struct_t;
in another function:
run_male_walker_struct_t *p = malloc(sizeof(struct run_male_walker_struct));
question, is it illegal? As the string is a class, it's size can... | This is illegal, but not for the reasons you're thinking.
The difference between std::malloc()/std::free() and new/delete is that the latter will call constructors/destructors, while the former won't. The expression
void* p = std::malloc(sizeof(run_male_walker_struct))
will return a blob of uninitialized memory on wh... |
3,828,085 | 3,828,124 | Getting to know the caller is from which DLLs | Currently, I have a C++ exe project, which dynamic load N DLLs.
Those DLLs will perform calling to the functions which is re-inside exe project.
Now, within my exe project, I wish to know the callers are coming from which DLLs.
Is it possible to do so using any available Windows API?
| It depends on what your actual goal is. You cannot do it if you're expecting the DLLs to be possibly malicious (that is, if you're expecting them to try to trick you). But if it's just for debugging or logging or something relaitvely harmless like that, you can look at the stack and get the address that the ret instruc... |
3,828,192 | 3,828,537 | Checking if a directory exists in Unix (system call) | I am not able to find a solution to my problem online.
I would like to call a function in Unix, pass in the path of a directory, and know if it exists. opendir() returns an error if a directory does not exist, but my goal is not to actually open, check the error, close it if no error, but rather just check if a file is... | There are two relevant functions on POSIX systems: stat() and lstat(). These are used to find out whether a pathname refers to an actual object that you have permission to access, and if so, the data returned tells you what type of object it is. The difference between stat() and lstat() is that if the name you give i... |
3,828,307 | 3,828,361 | Defining a string with no null terminating char(\0) at the end | What are various ways in C/C++ to define a string with no null terminating char(\0) at the end?
EDIT: I am interested in character arrays only and not in STL string.
| Typically as another poster wrote:
char s[6] = {'s', 't', 'r', 'i', 'n', 'g'};
or if your current C charset is ASCII, which is usually true (not much EBCDIC around today)
char s[6] = {115, 116, 114, 105, 110, 107};
There is also a largely ignored way that works only in C (not C++)
char s[6] = "string";
If the array ... |
3,828,394 | 3,828,413 | Why does my function pointer code run with no errors? | I have this:
typedef void (*funcptr) (void);
int main(){
funcptr(); //this can compile and run with no error . WHAT DOES IT MEAN? WHY NO ERRORS?
}
| The statement creates a funcptr instance by its default constructor* and discard it.
It is just similar to the code
int main () {
double();
}
(Note: * Technically it performs default-initialization as not all types have constructors. Those types will return the default value (zero-initialized), e.g. 0. See C++98... |
3,828,497 | 3,828,531 | Do boost::shared_ptr<T> and boost::shared_ptr<const T> share the reference count? | There are several interesting questions on pitfalls with boost::shared_ptrs. In one of them, there is the useful tip to avoid pointing boost::shared_ptr<Base> and boost::shared_ptr<Derived> to the same object of type Derived since they use different reference counts and might destroy the object prematurely.
My question... | It is perfectly safe.
The following code sample:
#include <iostream>
#include <boost/shared_ptr.hpp>
int main(int, char**)
{
boost::shared_ptr<int> a(new int(5));
boost::shared_ptr<const int> b = a;
std::cout << "a: " << a.use_count() << std::endl;
std::cout << "b: " << b.use_count() << std::endl;
return E... |
3,828,506 | 3,837,749 | How to differentiate Whether a Drive or NetWork Drive, on RightClick | When I Rightclick on a Shell Drive I want to differentiate whether the Drive is a Normal Drive or a Network Drive.
I hope we can do this using Initialize(LPCITEMIDLIST, LPDATAOBJECT, HKEY) method but unsure which parameter to use.
| Initialize is now documented to take a PCIDLIST_ABSOLUTE (not LPCITEMIDLIST), so you know it's rooted in My Desktop. My Computer is the second ItemID on that list, and the drive is the third ItemID. As Luke indicated, once you have the drive, GetDriveType will tell you whether the drive is remote.
|
3,828,676 | 3,830,794 | Asterisk cross platform compilation | I am trying to compile asterisk from windows using netbeans c/c++ IDE. As i want to add some functionality into the existing code.
when i am running the configure file i got the following errors
cygwin warning:
MS-DOS style path detected: .\configure
Preferred POSIX equivalent is: ./configure
CYGWIN environment v... | The first part seems just to say, that you should call configure not as .\configure but as ./configure. The last line is the real error. As it says it can't run /bin/sh ./config.sub you should check that both files are correct and existent.
Do ls -l ./config.sub to see if the file exists and is readable by your user a... |
3,828,748 | 3,828,811 | Question about Exceptions | I was just playing around with exceptions in the visual studio and with the above code I was expecting that since my exception specification doesn't mention anything the bad_exception should have been thrown. But what actually happens is the exception gets caught by the appropriate handler. Why so? Am i missing some se... | Regarding exception specification, Visual Studio is not standard-conforming.
While the empty exception specification is somewhat useful (but, as said, not properly implemented by VS), in general exception specifications are seen as an experiment that failed.
|
3,828,846 | 3,832,280 | QGridlayout changes height of row | I have a problem with a QGridLayout. One row of my layout contains an element (QProgressbar) that is normaly hidden. When there is some progress to report i call show on it. The problem is that when i call show on the QProgressbar the row above the row containing it will be slightly resized in height (1-3 px). So the w... | This is likely caused by the vertical spacing and/or margins of the layout. You should try playing with those properties.
|
3,828,877 | 3,828,933 | How to pack the required bits of a structure in a char*? | Language : C++
I am working on Bit Packing (Extracting the required bits from the given data and packing them in a char*) . My code currently supports :
- Integers
- Characters
- Strings
Now if I have to store the required bits of a structure, how should I go about it ? I mean what should I expect as input parameter... | Have a look at this for a very packed format or use an standard marshalling format such as json, xml, boost serialization,... and save yourself the grey hair.
|
3,828,907 | 3,829,092 | is there any way to inline just some selective calls to a function not all of them? | Is there any way to inline just some selective calls to a particular function not all of them? cause only form I know is declaring function as such at beginning and that's supposed to effect all calls to that function.
| First, some background on inlining.
There are multiple phases where inlining might occur (for example):
at compile time, the compiler may decide (or not) to inline the call.
at link time, if LTO are enabled, the linker might decide to inline some calls.
at load time, for the languages that support it.
All of them sha... |
3,829,040 | 3,829,128 | Scope problems in template C++ | Is there any scope problem in this program?
#include<iostream>
using namespace std;
template<class Type>
class Base
{
public:
Type member;
Base(Type param): member(param){
}
};
template<class Type>
class Derived: public Base<Type>
{
public:
Derived(Type param):Base<Type>(param){
... | Your question is somewhat confusing. At first I thought you were asking about base<Type> in the member initialization list, then I thought you were asking about accessing member, then back to the first... Now I'm thinking you're asking both, so I'll answer both.
Not writing Type here gives error, why?
When you use ... |
3,829,106 | 3,829,185 | Can dereferencing of pointer throw? | I'm teaching myself techniques of programming with exception safety mode of ;) and I wonder if dereferencing a pointer could ever throw an exception? I think it would be helpful for all C++ programmers to know all operations that are guarantied to not throw so I would be very grateful if someone could compose such list... | Dereferencing a simple pointer (T*) can lead to Undefined Behavior if there is no valid object of the specified type where the pointer points to. It's the nature of UB that the result might be anything, including, but not limited to, a C++ exception. One could indeed imagine an implementation that would check pointers ... |
3,829,107 | 3,841,693 | Loading JPEG file from resources in MFC C++ application | The following code works correctly under Windows XP:
CImage image;
RECT destRect;
int nResource = 10;
CResourceStream stream(0, MAKEINTRESOURCE(nResource), _T("JPEG"));
HRESULT hr = image.Load(&stream);
image.Draw(hDC, destRect);
But on Windows 7 image.Load returns E_FAIL though creating CResourceStream reads JP... | At the end I used this solution from codeproject:
http://www.codeproject.com/KB/GDI-plus/cgdiplusbitmap.aspx
It is a thin wrapper for GDI+ which is able to load JPEG files (and others) under Windows 7 perfectly.
|
3,829,220 | 3,829,252 | Is there no way to upcast into an abstract class and not modify it each time a class is derived from it? | #include<iostream>
using namespace std;
class Abs
{
public:
virtual void hi()=0;
};
class B:public Abs
{
public:
void hi() {cout<<"B Hi"<<endl;}
void bye() {cout<<"B Bye"<<endl;}
};
class C:public Abs
{
public:
void hi() {cout<<"C Hi"<<endl;}
void sayona... | Well, i'm not sure to understand exactly what you want (and why you want it that way) but:
int main()
{
Abs *bb=new B;
static_cast<B*>(bb)->bye();
Abs *cc=new C;
static_cast<C*>(cc)->sayonara();
}//main
Will work.
You just have to be sure that bb is really a B* before you static_cast.
Y... |
3,829,330 | 3,829,549 | Boost Shared_Ptr assignment | Why can I not do this?
boost::shared_ptr<QueuList> next;
void QueuList::SetNextPtr(QueuList* Next)
{
boost::mutex mtx;
boost::mutex::scoped_lock lock(mtx);
{// scope of lock
//if (next == NULL) // is this needed on a shared_ptr??
next = Next; // Why can I not assign a raw ptr to a shared... | Putting a pointer inside a shared_ptr transfers ownership of the pointer to the shared_ptr, so the shared_ptr is responsible for deleting it. This is conceptually an important operation, so the designers of shared_ptr didn't want it to just happen as part of a normal-looking assignment. For example, they wanted to prev... |
3,829,421 | 3,834,889 | Installing latest 1.44 boost library under ubuntu 10.04 | I have ubuntu 10.04 and want to install the latest boost library 1.44_0
I downloaded the tar.gz file and unpacked it into /usr/local/boost_1_44_0
I already have the boost 1.40 version install from synaptic.
So I want to compile and link against 1.44 because I'm wanting to use some new libraries that
are not in the olde... | What you miss here is bz2 library that Boost Python library in particular depends on. Install this library first using the following command - sudo apt-get install libbz2-dev.
|
3,829,771 | 3,830,216 | Lack of orthogonality in templates between class and function | // InternalTemplate.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
template<class T>
struct LeftSide
{
static void insert(T*& newLink, T*& parent)
{
parent->getLeft() = newLink;
newLink->parent = newLink;
}
};
template<class T>
struct Link
{
T* parent_;
T* left_;
T* right... | $14/2 -
A template-declaration can appear only as a namespace scope or class scope declaration. In a function template declaration, the last component of the declarator-id shall be a template-name or operator-functionid (i.e., not a template-id). [ Note: in a class template declaration, if the class name is a simple... |
3,829,788 | 3,830,224 | Using operator[] on empty std::vector | I was advised a while ago that is was common place to use std::vector as exception safe dynamic array in c++ rather than allocating raw arrays... for example
{
std::vector<char> scoped_array (size);
char* pointer = &scoped_array[0];
//do work
} // exception safe deallocation
I have used this convention m... | See LWG issue 464. This is a known issue.
C++0x (which is partially implemented by MSVC 2010) solves it by adding a .data() member.
|
3,829,885 | 3,830,008 | How to copy a certain number of chars from a file to a vector the STL-way? | If I want to copy the contents of a file to a vector, I can do it like that:
std::ifstream file("path_to_file");
std::vector<char> buffer(std::istream_iterator<char>(file),
std::istream_iterator<char>());
My question is, how would I do this if I want to copy only the first n chars?
Edit I cou... | As was noted by Steve, this would need copy_n(), which, due to an oversight, isn't in the current standard library, but will be in C++1x. You can implement one yourself easily, here's one I believe to be correct:
template<class InIt, class OutIt>
OutIt copy_n(InIt src, OutIt dest, size_t n)
{
if (!n) return dest;
... |
3,829,955 | 3,830,116 | How to use STL unsorted key-value as pair in map | I need to use STL C++ map to store key value pairs.
I need to store more than one data information in stl map.
e.g
Need to store DataType,Data and its behavior as(in param/outparam) all in string format.
But map always use key value pair
so if I
store it like
std::map<map<"int","50",>"behavior">.
But always it so... | If you don't want ordering, don't use ordered containers like map or set. You could achieve what you're looking for using a class and a vector. The sorted nature of std::map is what makes it efficient to lookup by key. If you want/need unsorted and more hash like behavior for lookups, look at Boost unordered contain... |
3,829,990 | 3,830,024 | Same code using floats on two computers gives two different results | I've got some image processing code in C++ which calculates gradients and finds straight lines in them with the hough transformation algorithm. The program does most of the calculations with floats.
When I run this code on the same image on two different computers, one Pentium IV running latest Fedora, the other a Cor... | This is not uncommon and it will depend on your compiler, optimisation settings, math libraries, CPU, and of course the numerical stability of the algorithms that you are using.
You need to have a good idea of your accuracy requirements and if you are not meeting these then you may need to look at your algorithms and e... |
3,830,106 | 3,830,194 | buffering in iostream | can somebody please explain, what exactly does it mean? I'm trying to understand what is the difference between clog and cerr, difference is only in buffering
thanks in advance
| When you write to clog then you actually write to an in-memory store of characters. When this store becomes full, it then writes to the actual stream. When the stream is closed, (which would happen on the program ending) then any remaining data is written to the stream (manual flushing can also happen).
With cerr, this... |
3,830,117 | 3,830,373 | Intrusive list threadsafe - best way | How do you create an intrusive slist (boost) that is threadsafe so that multiple threads can remove items or add items?
I'd want fairly fine grained locking; so I can lock only the necessary nodes and not the whole list each time.
Do I just write a wrapper class around boost slist or is it better to just implement it m... | You can have a look at the approach here that uses C++0x atomic operations (if you have access to C++0x). It adresses the multi-producer/consumer approach.
http://www.drdobbs.com/high-performance-computing/210604448
|
3,830,367 | 3,831,260 | difference between logical and physical const-ness | What is the difference between these two terms, and why do I need mutable?
| Scott Meyers, Effective C++, Item 3:
Use const whenever possible
has an excellent discussion (with examples) on this topic. Its hard to write better than Scott!
Note also that physical-constness is also known as bitwise-constness.
|
3,830,491 | 3,830,652 | How to deduce class type from method type in C++ templates? | In templates as shown below, I would like the call Run(&Base::foo) succeed without the need to name the Base type twice (as is done in the compiling Run<Base>(&Base::foo) call). Can I have that? Possibly without adding a ton of Boost headers?
With the provided code, I get an error of:
prog.cpp:26: error: no matching fu... | The T in Traits<T>::BoolMethodPtr is in a non-deduced context, so the compiler will not deduce automatically from the call what type T should be.
This is because there could be code like this:
template<typename T>
struct Traits {
typedef bool (T::*BoolMethodPtr)();
};
template<>
struct Traits<int> {
typedef bool (... |
3,830,644 | 3,830,661 | Comparing a variable to a range of values | In mathematics, the notation 18 < age < 30 denotes that age must lie between the values 18 and 30. Is it possible to use this kind of notation in the if statement? For example, I've tried executing
if(18 < age < 30)
and I get weird output, so it's not quite right. Is there a way to do this or so I simply have to writ... | You can do:
if (18 < age && age < 30) /*blah*/;
|
3,830,663 | 3,830,674 | Random and negative numbers | I have to generate numbers in range [-100; +2000] in c++. How can I do this with rand if there is only positive numbers available? Are there any fast ways?
| generate a random number between 0 and 2100 then subtract 100.
A quick google search turned up a decent looking article on using Rand(). It includes code examples for working with a specific range at the end of the article.
|
3,830,853 | 3,831,136 | C++ Program quits unexpectedly, how do I debug this with gdb? | I am writing a program that runs some unit tests on code that that been written by my colleagues. I am using the Google C++ testing framework. I run a function that spawns 3 threads, and then runs for 30 seconds. After it runs, the program exits with status 0. This is not the expected behavior, obviously. I know it doe... | Besides break exit, there are a couple other places you might need to set breakpoints. Take a look at this question and answers.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.