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,886,292 | 7,886,510 | Variadic templates - incomplete type | Having this code:
template<class ...Args>
struct Are_Same
{
enum {value = Are_Same<Args...>::value};
};
template<class A,class... C>
struct Are_Same<A,C...>
{
enum {value = Are_Same<A,C...>::value};//HERE is THE ERROREOUS LINE
};
template<class A,class B>
struct Are_Same<A,B>
{
enum {value = std::is_sam... | I think that the definitions of the templates are wrong, in both cases you are triggering exact recursion. I would have expected the compiler to die with some stackoverflow inside the compiler but a different error is produced...
An implementation of the are_same variadic template could be:
template <class... Args> ... |
7,886,504 | 7,886,588 | Sign extension on literal vs. variable | I'm working with gcc 4.4.5, and have some difficulties in understanding the right shift operator on plain simple unsigned values...
This test
ASSERT_EQ( 0u, (unsigned long)(0xffffffff) >> (4*8) );
passes.
This test
unsigned long address = 0xffffffff;
ASSERT_EQ( 0u, address >> (4*8) );
fails:
Value of: add... | It is undefined behaviour to shift a value greater than or equal the size in bits of the left operand (§5.8¶1). (I assume unsigned long is 32 bits from your comments about 0xfffffff being the expected result if you consider sign extension.)
Still, there's probably something that ASSERT_EQ does that causes the differenc... |
7,886,719 | 7,886,779 | Merging interfaces, without merging | I was thinking, does C++ or Java have a way to do something like this
Interface IF1{
....
};
Interface IF2{
....
};
function f(Object o : Implements IF1, IF2){
...
}
meaning a typesystem that allows you to require implementation of interfaces.
| You can do this in Java:
public <I extends IF1 & IF2> void methodName(I i){
....
}
This way you force I to implement your two interfaces, otherwise it won't even compile.
|
7,887,314 | 7,887,480 | std::getline input not working properly in C++ |
Possible Duplicate:
Need help with getline()
getline not asking for input?
I am working on the following code:
int main()
{
int num;
string str;
cin>>num;
int points[num][2];
for(int i=0;i<num;i++)
{
cout<<"\nPoint"<<i<<":";
getline (cin,str);
points[i][0]=atoi(&str[0]... | Following on from Prince John Wesley's reply, try
cin >> num >> endl;
to flush the stream buffer before using it again.
|
7,887,494 | 7,905,016 | How to close a dialog box using do modal | Okay basically I have an MFC application with lots of dialogs that need to be cycled through. Basically when you click one button to go to another dialog, I want the previous dialog to close. Right now the dialogs are just displayed over the top of each other. How do I get the dialog to close once the new dialog has op... | What you can do is hide the parent dialog when you DoModal() the new dialog and destroy it after the new dialog ends. I have not tested the ShowWindow() below but you get the idea, if it doesn't hide the dialog look for another similar function.
void CMachine2Dlg::OnBnClickedNewmc()
{
ShowWindow( SW_HIDE);
NameD... |
7,887,582 | 7,887,752 | TR1 function multicast | How would you implement multicast for TR1 functors? I have my callback slots implemented like
void setCallback(std::tr1::function<void (std::string)> cb)
{
this->callback = cb;
}
but need to pass more than one callback in one of them. I don't want to go into more complex solutions like observer, as this is the on... | You most likely want:
void registerCallback(std::tr1::function<void (std::string)> cb)
{
this->callbacks.push_back(cb);
}
with callbacks a container (whichever you like) of std::tr1::function objects instead of a single one. When dispatching, iterate over the callbacks.
Also, if you want to be able to remove callb... |
7,887,652 | 7,887,792 | boost::scoped_ptr documentation inconsistency? | boost::scoped_ptr documentation contains an example of a technique referred as Handle/Body Idiom. It is described there in the following words:
The scoped_ptr_example_test.cpp sample program includes a header file,
scoped_ptr_example.hpp, which uses a scoped_ptr<> to an incomplete type
to hide the implementation... | They don't contradict each other. Because scoped_ptr is a template, and because there is no explicit instantiation in the code, each method is instantiated on demand. That means that the type must be complete by the time that ~scoped_ptr<> is instantiated, which in this case is in the .cpp file after the held type is c... |
7,887,941 | 7,887,947 | random number from -9 to 9 in C++ | just wondering, if I have the following code:
int randomNum = rand() % 18 + (-9);
will this create a random number from -9 to 9?
| No, it won't. You're looking for:
int randomNum = rand() % 19 + (-9);
There are 19 distinct integers between -9 and +9 (including both), but rand() % 18 only gives 18 possibilities. This is why you need to use rand() % 19.
|
7,888,211 | 7,924,705 | How do I detect typo with Boost.program_options? | I use boost.program_options library. Consider this simplified case.
po::options_description desc("Usage");
desc.add_options()
("uninstall,u", "uninstall program")
("custom,c", po::wvalue<std::wstring>(), "specify custom action");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify... |
I want to produce error on such command-line:
testprog.exe -u c- action1
Note, user made a typo "c-" instead of "-c". But the parser
understands this as a single -u option. How do I handle such cases?
Instruct the program_options library to accept no positional arguments and you get the desired behavior
code & com... |
7,888,245 | 7,888,455 | HowTo exclude signature from XML signed file? | I used DSign methods from MSXML 5.0 dll (IDE - MSVC) to be able sign() and verify() XML documents, but just for now I need to find methods, to exclude signature fields from signed XML file.
I have tried to find the solution on the Internet, but no luck.
Have any one faced with this problem and solved it?
Thanks!
| Just remove the signature elements? They have their own namespace URI, even: http://www.w3.org/2000/09/xmldsig
|
7,888,322 | 7,888,792 | Relationship between IDL and c++ source file | To lean about interfaces, I'm trying to write a test project to implement the IDispatch interface.
So far I've:
created an MFC dll project in visual studio 2010
written the following IDL
[ uuid(68B0FAE7-3828-415D-94B0-720A007311FF), version(1.0) ]
library Test
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
[ ... | You can you the
midl compiler
It is capable of generating header/sources in c (or C++? don't remember), but most importantly it will get you a typelibrary (tlb) file
#import directive
Will generate c++ definitions for the typelibrary contents.
|
7,888,559 | 7,888,781 | How to get started writing Perl bindings for a C++ library? | I want to write Perl bindings for a C++ library, so that the library can be used from Perl. How would I get started doing this? I've written pure-Perl modules for CPAN before.
| There is SWIG and there XS. I used XS for Net::Sharktools which was the first time I wrote any XS code. I point to it because it was a particularly trivial case, and might be a good way to get an idea of what is involved.
perldoc perlxs includes a section on C++ specific aspects as well.
|
7,888,939 | 7,889,008 | c++ makefile destructor undefined reference | This is a puzzle to me:
c++ undefined reference to destructor
That's the issue, the code is the same as the link, full makefile and errors here. The linked answers did help but only to highlight that I had some headers in a place I did not expect.
makefile
CXX = g++
BIN = .
LIBS = -L.
INCLUDE = -I . -I
CXXFLAGS = ... | Your executable output file and your object file geomTest.o have the same name! That's bound to get you into trouble when the linker overwrites the object file.
Change it to $(CXX) -o geomTest ..., or better even to $(CXX) $@ ... to avoid such problems in the future.
In fact, you are misusing the linker command altoget... |
7,889,032 | 7,889,116 | UTF-8-compliant IOstreams | Does GCC's standard library or Boost or any other library implement iostream-compliant versions of ifstream or ofstream that supports conversion between UTF-8-encoded (file-) streams and a std::vector<wchar_t> or std::wstring?
| Your question doesn't quite work. UTF-8 is a specific encoding, while wchar_t is a data type. Moreover, wchar_t is intended by the standard to represent the system's character set, but this is entirely left to platform, and the standard makes no requirements.
Therefore, the correct thing to ask for is first of all conv... |
7,889,053 | 7,893,059 | clang - symbol(variable, function, type, etc..) definition or declaration or reference | Please do anyone know if clang has option to return symbol definition or declaration(or reference)?
I mean: there is option for clang executable called -code-completion-at=path_to_file:line:coloumn
the clang will look into code and returns you completion strings(ie if there is for example
std::string_type_variable. ..... | Clang provides such functionality by libclang shared library, but there is a simple example on how to use it. If you built clang from source, take a look at c-index-test executable. It's source located in tools/c-index-test.
|
7,889,087 | 7,889,192 | lambda returning bool | I want to find point, which has the less Y coordinate (if more of such points, find the one with smallest X).
When writing it with lambda:
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
if (p1.first->y() < p2.first->y())
return true;
else if (p1.first->y() > p2.f... | The return type of lambdas can be implicitly inferred, but you need to have a single return statement to achieve this; that's why your "working" lambda works (return type inferred to be bool).
sehe's solution explicitly declares the return type, so it works fine as well.
Update:
The C++11 standard, §5.1.2/4 states:
If... |
7,889,136 | 7,889,919 | std::chrono and cout | I have a stupid problem. I try to switch to the c++11 headers and one of those is chrono. But my problem is that I cant cout the result of time operations. For example:
auto t=std::chrono::high_resolution_clock::now();
cout<<t.time_since_epoch();
gives:
initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>... | As others have noted, you can call the count() member function to get the internal count.
I wanted to add that I am attempting to add a new header: <chrono_io> to this library. It is documented here. The main advantage of <chrono_io> over just using count() is that the compile-time units are printed out for you. Thi... |
7,889,219 | 7,889,290 | Microsoft's CopyFileEx error | I am using Microsoft's CopyFileEx method to copy files.
I am coping from one server to another and the file located in share folder and i am using UNC.
i get an error 999. I was able to find the ‘999’ error on Microsoft’s Technet site. The copies are failing because of an “Error performing inpage operation.”
Accordi... | It says in the beginning of that kb article that if it's a small file, it can be an I/O error that causes it to give error 999 due to the way it's copying the file.
I'd suggest trying to copy the file manually using CreateFile and ReadFile (as mentioned in that article) and hopefully that would give you the real erro... |
7,889,700 | 7,889,735 | Why doesn't the locale change on OSX? | I'm trying to use strftime on a mac to output the time in a locale-dependent way.
I'm setting the locale and getting the time :
// sets the program's locale to the native locale
// without this line the locale is 'C'
log.debug(setlocale(LC_ALL,""));
struct tm* date = localtime(&time);
strftime(result.buf, size, "%X %... | You need to restart the terminal or whatever you're starting your program from for changes to take effect.
|
7,889,836 | 7,889,935 | Are iterator::difference_types system independent | I have some serialization logic in which I also serialize stl datastructures. Currently I just write the size field and then each element of the structure by iterating over it. In the deserialization I read the size field and then I know when I am done reading the data structure.
No the question is how to write the siz... |
Is this guaranteed by the standard to be portable, or should I use some fixed type for all data structures here to encode the length?
No, it is not portable, and yes, you should use some fixed-size type. For most applications, a 32-bit integer should be fine. Please note that, depending on your serialization code a... |
7,889,956 | 7,890,136 | Is std::bitset bit-order portable? | Does C++ say anything on bit-ordering? I'm especially working on protocol packet layouts, and I'm doubting whether there is a portable way to specify that a certain number be written into bits 5,6,7, where bit 5 is the 'most significant'.
My questions:
is 0x01 always represented as a byte with bit 7 set?
is bitset<... | From 20.5/3 (ISO/IEC 14882:2011)
When converting between an object
of class bitset and a value of some integral type, bit position pos corresponds to the bit value 1 << pos.
That is, bitset<8>().set(7).to_ulong() is guaranteed to be (1 << 7) == 128.
|
7,890,007 | 7,890,086 | C++ input and output files | So im writing c++ program, that takes a integer from input file, multiply it with 2 and outputs it on output file. So the code is -
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
int n;
FILE * inFile;
FILE * outFile;
inFile = fopen ("reiz.in","r");
outFile = fopen ("reiz.... | This a C-program (apart from the using namespace std;). In C++ you should use streams and formatted I/O, like this:
#include <fstream>
int main() {
std::ifstream input_file("reiz.in");
int n;
input_file >> n; // read one integer
std::ostream output_file("reis.out");
output_file << n * 2 << std::end... |
7,890,204 | 7,891,906 | Deducing knowledge of original types, whilst simultaneously forwarding | Summary: I want to end up with a function that deduces the exact types it was called with and takes (e.g.) a tuple that forwards them (the types of which will be different from the exact types the function was called with).
I'm stuck trying to "know" via deduction the types of the arguments to a given function, whilst ... | Answer to first question:
Arguments to functions are expressions, not types. The difference between these two is expressed in chapter 5 [expr], p5:
If an expression initially has the type “reference to T” (8.3.2,
8.5.3), the type is adjusted to T prior to any further analysis.
Thus, there is no difference what-so-... |
7,890,240 | 7,890,266 | In C++, how do I declare a function pointer to a method in a class? | In C++, I'm trying to define a type suitable for a pointer to one of several member functions of my class cBar (all functions have the same interface, say accept an int and return void).
For now, I'm making a global type tHandler suitable for a pointer to one of several global functions accepting an additional paramete... | A pointer to a member can be declared like
typedef void(Trustee::*tHandler)(int);
Here's how to use it (adaptation of your own code):
class Trustee {
typedef void(Trustee::*handler_t)(int);
handler_t pfCurrentHandler;
void handlerOne(int i) { cout << "HandlerOne: " << i << endl; }
void handlerTwo(int ... |
7,890,335 | 7,890,358 | In C, how do I constantly get user input while doing another function? | This problem really perturbs me on how to do it in C way:
Display series of numbers (1,2,3,4, 5....etc) in an infinite loop. The program should quit if someone hits a specific key (Say Backspace key).
My try was to make a loop and then get the user input every time.
int main()
{
char userInput;
int i = 0;
... | You can call _kbhit to check if input is waiting. If there is, then you can read it with _getch.
|
7,890,452 | 7,890,552 | C++ parameter is a pointer to a constant object but the updated object is not returned? | I have native C++ class SrcClass containing the following:
std::vector<shotEntry> objectsQueue;
bool getRelatedEntry(const entryToProcess *entriesDeets, int &i) const {
if (i >= (int)objectsQueue.size()) {
i = 0;
return false;}
if (!objectsQueue.size()) return false;
entriesDeets = &(object... | This is because you are setting the value of the function's parameter. You want:
bool getRelatedEntry(const entryToProcess **entriesDeets, int &i) const {
...
*entriesDeets = &(objectsQueue[i++]);
...
and
srcObj->getRelatedEntry(&entriesDeets, i)
|
7,890,585 | 7,890,811 | Is state checking always an efficient thing to do? |
Suppose that it is only necessary to bind a value to a certain
datamember of a certain object when bState is true. When bState
is false, it is not necessary, but it does not hinder either.
Which of the following pieces of code would be more efficient, and why?
(EDIT: updated, state is now a member of the object)
cons... | I would say the latter is definitely quicker. The first version has bidirectional memory access, the latter has unidirectional memory access.
In this version:
for (; i < x; ++i) {
if (pObject[x].bState) {
pObject[x].somedatamember = iToBind;
}
}
there is a stall during the if statement as the CPU must wait for... |
7,890,793 | 7,893,065 | Read gzipped files by using a STL vector of pointers to igzstreams | As input, I have a list of gzipped files. As shown here, I use gzstream to handle them. For practical reasons, I want to open each file and record each stream into a vector. It seems pretty straightforward but I don't manage to make it work. Here is the minimal code:
#include <cstdlib>
#include <iostream>
#include <ve... | As mentioned in the comments, I would prefer not to use Boost and I only have gcc 4.1.2. Thus, here is the solution using the free store, thanks to the suggestion of Cat Plus Plus:
// open each input file
for (i = 0; i < vInFiles.size(); ++i)
{
igzstream * pt_inStream = new igzstream;
pt_inStream->open (v... |
7,891,203 | 7,891,481 | using only certain functions from a library? | i would like to use only certain functions from math.h (WITHOUT including the entire library)
for example, i need to use "sqrt" and "exp", but i have variables named "y1" (and possibly others) which conflict with definitions in math.h
how can i use only certain functions from a library like that?
i tried
#define sqrt ... | Yes, you can just use the parts you want.
Simply create your own partial mini_cmath.h header for those functions / globals you need access to (assuming those don't conflict!).
As several have noted, there's no way to only #include a given chunk (unless the included header has preprocessor macros to enable such a thing,... |
7,891,210 | 7,891,489 | write a buffer in memory from C/C++ and read from it in java without JNI | I have a question, is this possible and how? Reading bytes from a buffer in the memory that has been created from C/C++ with Java? My idea is to use JNI for starting a cycle in C++ that writes bytes in a buffer and only send the direction of the buffer to Java, then Java reads the bytes from it in another cycle. The go... | You can use a ByteBuffer. The simplest approach is to use a ByteBuffer.allocateDirect() using the address allocated by Java. If you have to use the address provided by C, you can change the address and limit (for the size) to point to anywhere you like.
If you would rather use something more low level, on the Oracle J... |
7,891,306 | 7,891,385 | gcc error: invalid conversion from double* to const double | I'm using gcc version 4.5.0. Using the following simple example I would assume to get an error invalid conversion from double* to const double*
#include <iostream>
using namespace std;
void foo(const double *a)
{
cout<<a[0]*2.<<endl;
}
int main()
{
double *a=new double[2];
a[0]=1.;
a[1]=2.;
foo(a)... | Generally, you are allowed to implicitly make things "more constant" but not "less constant" in C and C++. Therefore, you are allowed to pass a non-const object to a function that takes a const object.
Basically the const parameter in the method declaration is the function's way of promising not to modify the paramete... |
7,891,436 | 7,893,906 | Socket connect timeouts differ between networks | I have a rather interesting problem. We have 2 networks at work that are physical duplicates of each other (network A and network B). They just run on different subnets.
I am working on some fault tolerance improvements for our devices that cluster with each other on the network. One of the test cases that I am exercis... | Maybe you should give more addresses? It's not clear exactly what the IPs are.
My guess is that:
In the slow case you're getting ARP failures (no response because target has incorrect netmask)
In the fast case you're getting a routing failure. If the host has an incorrect smaller netmask it won't even attempt ARPs.
... |
7,891,504 | 7,892,104 | Precision long double worse than double | When I use long double I get worse precision than using double.
3.14159265358979323846264L is this good to write long double const in source code or I should add something other than L?
EDIT
I solved the problem. I change algorithm to be more precisely.
| Your are not getting a worse precision.
What is happening is that when you print the number out the stream library is truncating the displayed value. Use std::setprecision to get a specific precision.
double x = 1.0/3;
long double y = 1.0/6;
// Prints out the precision
std::cout << "Limit: " << std::numeric_l... |
7,891,526 | 7,891,606 | Should function declarations include parameter names? | What would you actually consider a better coding style: declaring the parameter names of functions/methods inside the header, or only in the source file, as it is possible to do both? If you actually consider declaring parameter names of functions/methods only in the source file, how would you then declare default valu... | While both are a-okay and used quite a lot, there is a distinct advantage to using parameter names in the declarations in your header files.
Most documentation systems (say, doxygen) will parse your header files and generate docs.
As an example, look here: http://libface.sourceforge.net/doc/html/classlibface_1_1_face.... |
7,891,609 | 7,891,658 | How to read C++ crash info | Hi I am faced with something along the lines of
*** glibc detected *** /usr/lib/R/bin/exec/R: double free or corruption (out): 0xb1f64430 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x6ebc2)[0xb73f3bc2]
/lib/i386-linux-gnu/libc.so.6(+0x6f862)[0xb73f4862]
/lib/i386-linux-gnu/libc.so.6(cfree+0x6d)[0xb... | _XXXDXEv is a mangled function name - use c++filt to demangle it.
(_XXXDXEv+0x30) means that level of the backtrace was 48 bytes into the code for that function.
Try re-running under gdb, or run gdb over a core file if you have it, for more detail.
|
7,891,797 | 7,891,834 | C++ Reading in wrong values from a file | My data file contains the following numbers to be read in
/*
111
100.00
200.00
50.00
222
200.00
300.00
100
*/
but after the while loop reads in customerNumber as 100 when it should be 111, it get's the values for everything else wrong also. Such as beginningBalance reading as
//-9255963134931783000000000000000000000... | Try removing the semicolon from after your while loop condition and see if that fixes it.
So change
while (inputFile >> customerNumber);
to
while (inputFile >> customerNumber)
The way it is now, it does nothing until it eats up all the data from the file, then does the stuff inside the { ... }, and the file reads you... |
7,892,328 | 7,892,396 | Abstract class with minor differences in implementers | In a current project, I have classes named BlahManager and class named BlahController, defined like this:
class BlahController
{
public:
void doSomething(int x, float y){
// do the work
}
void doOtherThing(char a, char* b, int c){
// do the work
}
}
class BlahManager
{
public:
BlahCont... | No and you shouldn't.
BlahController::doSomething takes 2 parameters, while BlahManager::doSomething takes 3. So you cannot have an abstract parent class forcing the two classes to implement the same function, because they are not the same function.
Also, you shouldn't even want to do this. These functions don't do sim... |
7,892,382 | 7,892,817 | How to handle objective-c delegation from C++? | Short version: I have a Qt/C++ to which I am having to add a limited amount of Cocoa/Objective-C code. I have changed the .cpp file to a .mm file and added the objective-c code/objects to said file, and it compiles and works. I now need a delegate for one of the objects I created- a NSPopUpButton (or, rather, the menu ... | Ok to answer your question:
reportwindow.h is additionally included in a .cpp file, if that makes
a difference.
It does make a difference. Any compilation unit (cpp file in this case) that is touching Objective-C code has to be renamed to .mm or .m. Including the header that in turn is including Objective-C stuff i... |
7,892,441 | 7,892,674 | Floating Point Arithmetic, C/C++ the way to go? | I'm creating a web application that does some very heavy floating point arithmetic calculations, and lots of them! I've been reading a lot and have read you can make C(and C++) functions and call them from within PHP, I was wondering if I'd notice a speed increase by doing so?
I would like to do it this way even if it'... | It all depends on the actual number of calculations you are doing. If you have thousands of calculations to do then certainly it will be worthwhile to write an extension to handle it for you. In particular, if you have a lot of data this is where PHP really fails: it's memory manager can't handle a lot of objects, or l... |
7,892,632 | 7,893,068 | inserting a std::string to an arbitrary location within a std::fstream | I have a Visual Studio 2008 C++ application where I would like to insert a string to an arbitrary point in a file using std::fstream. The file may be as large as 100MB in size, so I don't want to read it entirely in to memory, modify it, and the re-write a new file.
/// Insert some data in to a file at a given offset
/... | You've just stated one of the basic motivations for database formats, and a need they fulfill.
Based on that, the solution seems pretty obvious, at least to me: you need to use a database format of some sort, probably along with code that directly supports that format. Nearly any decent db format will support what you'... |
7,892,769 | 7,892,856 | How does this program work | This is my first C++ program. It prints the number of words in the input.
My first question, how does it go into the loop and add to the count? is it every time i type the space character? if so, how does it know I'm trying to count words?
using namespace std;
int main() {
int count;
string s;
count = 0;
... |
Cin will capture input until a space, yes. The specific style of loop you have will go until an End-Of-File (EOF) is found or until bad input is provided. That loop doesn't look like common C++ practice to me, but it's described here.
2.namespace std is how you tell the compiler where to look to find the objects you'... |
7,892,776 | 7,892,882 | Using C++ native dll in .Net External component has thrown an exception | I'm trying to use a native C++ dll in C# and am getting the "External component has thrown an exception" with an error code of -2147467259.
C#:
[DllImport(@"MyDLL.dll", CharSet = CharSet.Auto)]
public static extern string MyFunction([MarshalAs(UnmanagedType.LPStr)] StringBuilder input);
C++:
__declspec(dllexport) char... | try the technique from http://blog.rednael.com/2008/08/29/MarshallingUsingNativeDLLsInNET.aspx - this has saved the day several times :-)
|
7,892,810 | 7,892,887 | C++ logging wrapper design | I would like to add a log to my application. I've picked a logging library but I'd like to be able to switch to a different library without having to alter any code that uses logging.
Therefore, I need some sort of logging wrapper that is flexible enough to utilize pretty much any underlying logging library's functiona... | Your best bet is to make the interface as simple as possible. Completely separate the logging user's interface from how the logging actually gets implemented.
Cross-cutting concerns always are expensive to maintain, so making things any more complicated will make you hate life.
Some library only wants something simple... |
7,892,908 | 7,892,975 | C++ Classes formatting | Is this generally accepted as proper formatting for C++ classes? I've seen so many different formats for how to code classes while trying to learn them. I'm just wondering what the standard or 'normal' way of doing it is.
class Circle
{
private:
double radius;
public:
Circle()
{
radius = 0.0;
}... | It's a matter of taste and consistency. There are many ways in which you can format not just classes, but all parts of the code in general. What's important is that the code is readable to anyone involved on your project, and follows basic guidelines in your group/workplace/whatever.
|
7,893,217 | 7,893,686 | C++ memset() for long (64bit) types |
Possible Duplicate:
Is there memset() that accepts integers larger than char?
As it can be seen in memset's declaration:
void * memset ( void * ptr, int value, size_t num );
Is there any way to use this memset function (or another function included in STL library) so that you can set memory to a long long type valu... | memset only uses one byte of the value passed in and does bytewise initialization. If you want to initialize a long long array with a particular value, just use std::fill or std::fill_n and let your library and compiler optimize it as they can (partial loop unrolling etc).
Another canonical C++ way is to just use vecto... |
7,893,220 | 7,893,270 | How is "const" implemented? | How does a compiler, C or C++, (for example, gcc) honors the const declaration?
For example, in the following code, how does the compiler keeps track that the variable ci is const and cannot be modified?
int
get_foo() {
return 42;
}
void
test()
{
int i = get_foo();
i += 5;
const int ci = get_foo();
... | Much like any other bit of symbol information for variables (address, type etc.). Usually there is a symbol table which stores information about declared identifiers, and this is consulted whenever it encounters another reference to the identifier.
(A more interesting question is whether this knowledge is only present ... |
7,893,222 | 8,143,937 | How do I render "Video" in Qt / X11 on an embedded device | I am currently trying to write an application that displays live "video" from a specialized USB device. The USB device provides approx. 10 frames/sec of 320x240 video in an array of gray levels. The application is written in Qt on an iMx51 (800Mhz arm) platform running linux and X11. My application needs to display t... | After downloading and reading through the VLC source code I settled on using the Xvideo extension for X11. The VLC source code contains an xvideo output "engine" using xcb to communicated with the xserver. I used this as an example to code my own solution.
On our platform the scaling and display features of the xvide... |
7,893,380 | 7,895,395 | Time differences between Release and Debug builds | My program is supposed to trigger an event every 180 seconds.
mFoodSpawnTime += dt;
if (mFoodSpawnTime > mFoodSpawnCycleLength)
{
..... etc;
}
mFoodSpawnCycleLength = 180.0f, and mFoodSpawnTime is another float that accrues time every loop.
My problem is that if mFoodSpawnCycleLength is around 180.0f, then on ... | You might want to try using double rather than float here. The performance difference in this case will be minimal, and I suspect you may be hitting a problem where you are adding a very small number to a big number - leaving the floating point value of the big number unchanged.
Floats only give you around six digits o... |
7,893,381 | 7,893,553 | Why is C# much slower than Java and C++ in my prime number testing | (bear with me, there's a lot of explanation before my question)
As a few of you may be aware over the last few days I have posted a fair few questions relating to performance of C++. Being a Java programmer I wanted to know was C++ worth the extra effort to specialise in, or is Java good enough for performance programm... | About C#:
First of all, instead of datetime you should use stopwatch.
Datetime is not reliable for code timing.
Second, are you sure you are executing it in release mode with visual studio closed?
If visual studio is open or you are launching with F5 the JIT will not optimize the code!
So... use stopwatch and close all... |
7,893,525 | 7,893,801 | What's the difference between boost::signals2::mutex and boost::thread::mutex? | I'm using scoped_lock and mutex to implement a version of a BlockingQueue posted in a different SO question, but there are multiple different precompiled headers for both of them in boost.
scoped_lock is available through "boost/interprocessor/sync/scoped_lock.hpp" and "boost/thread/mutex.hpp"
mutex is available throug... | The signals2::mutex is part of the signals2 library, thus presumably a special purpose mutex just for that library.
The generic mutex is the "boost/thread/mutex.hpp" one and should be the one you use. The "win32" version will be included automatically by the generic file and includes the code for mutexes on windows. T... |
7,893,531 | 7,893,598 | What is the best way to indicate that a double value has not been initialized? | I have a class CS which is to represent the co-ordinate system in 3D i.e.(x, y, z)
class CS
{
private:
double x;
double y;
double z;
}
CS::CS()
{
x = NULL;//this causes x = 0//i want the address of x to be 0x000000 & not x = 0
y = NULL;
z = NULL:
}
I want that the user can create a ... | You can't change the positions of x,y,and z to be NULL, since there positions will always be offsets from the CS object. They will always exist. It's not that CS has an x like you have a car, it's like CS has an x like you have a head. You can't not have a head. If they were integers, you would have to make them po... |
7,893,640 | 7,893,699 | How to extract directory properties in Windows? | Does any function return how many files are in a directory?
Is the only way to iterate through all files?
(For example, when you right click the directory in windows, it lists: 7 files in directory. Is there a way to extract that information?, how is "it" getting that info?)
Thanks.
| I don't know if there's a better way, but I use FindFirstFile/FindNextFile to do this (some error checking removed for clarity):
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
_TCHAR szDir[] = _T("somedir\\*");
hFind = FindFirstFile(szDir, &ffd);
do
{
if((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY... |
7,893,666 | 7,893,705 | function sleep could not be resolved | I'm using eclipse and I'm building a simple program, but I get an error saying function sleep could not be resolved
#include <time.h>
#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
printf("ciao");
... | If you are using MinGW as stated, then you may need to include windows.h. The sleep implementation I think uses the Win API Sleep().
For example:
#include <windows.h>
#include <iostream>
int main() {
std::cout << "!!!Hello World!!!" << std::endl;
Sleep(20000);
std::cout << "Text Will Appear After 2 Sec.."... |
7,893,698 | 7,894,148 | Optimization makes function return immediately instead of executing | I'm working on VS 2010 express and trying to do some file reading and parsing work
my function goes something like this... (I dropped the boring parts)
void SomeClass::SomeFunc(char *ALName, std::map<...> *chromList, std::map<...> *chromLine)
{
ifstream file;
char tmpBuff[500];
char tmpBuff2[500];
char ... | Are you sure that the function is actually being skipped and that the debugger isn't simply making it look skipped?
If it really isn't being executed then it's almost certain you have undefined behavior that happens to work how you want it when not optimized and the compiler (probably rightfully) optimizes it into non-... |
7,893,768 | 7,903,731 | Using boost::bind with boost::function: retrieve binded variable type | Is there any way to retrieve information on what paramaters were bounded by boost::bind or does this need to be stored manually?
i.e.:
in .h
class MyClass
{
void foo(int a);
void foo2(double b);
void bar();
void execute();
int _myint;
double _mydouble;
}
in .cpp
MyClass::bar()
{
vector<boos... | As far as I know, you can't do what you want, as std::function throws away (nearly) all type information of the passed function pointer, function object or lambda. It employs a technique called type erasure and on the surface completely forgets what was passed into it, as long as it is callable with the provided argume... |
7,893,850 | 7,895,745 | Long compile times in Visual C++ 2010 with large static arrays | We have a C++ project in which there are several large static data tables (arrays of structs) generated by an preprocessing tool and compiled into our project. We've been using VC++ 2008 up to now, but are preparing to move to 2010, and these data tables are suddenly taking a very long time to compile.
As an example, ... | Might be worth turning off all optimisation on this file (it's not going to buy you anything anyway) in case it's the optimiser that is going N^2.
|
7,893,949 | 7,894,149 | C++ stream get unget not a nop? | I have the following C++ program and ran it using Visual Studio 2008 on Windows 7. I get and then unget a character. After doing so, the file position is different. Why? How do I get around this problem?
test.txt (download link below if you want)
/* Comment 1 */
/* Comment 2 */
#include <fstream>
int main (int arg... | Ok using your input file I see the same behavior you do. After some experimentation, it looks like the file was in Unix format, then had the ^M characters edited out (at least that's how I was able to reproduce it).
To fix it, I edited the file in Vim, executed ":set ff=dos", then added and deleted a character to dirt... |
7,894,527 | 7,915,833 | Boost.Spirit Overlapping actions / reusing terminal tokens | Using Boost.Spirit, is it possible to deliver a terminal token to multiple actions and if so, what would the syntax be?
For example, suppose I have two rules:
rule 1 that consumes "A B" and has an associated action "void f( <attribute type of A>, <attribute type of B>)" and rule 2 that consumes "B C" and has an associ... | Use local variables:
qi::rule<Iterator, qi::locals<B> > r =
(a >> b)[lf(_1, _2), _a = _2] >> c[lg(_a, _1)];
I'm assuming here that lf() and lg() are lazy function (i.e. wrappers for your underlying f() and g()). See here for more information about locals. The disadvantage is that you make a copy of b's attribute... |
7,894,544 | 7,895,037 | video capture from firewire c++ windows | I'm using eclipse and c++ on windows and I have to capture a video from a firewire camera but I have no ideas of which libraries should I use.
I prefer to not install anything, but using some libraries if it's possible.
if you can also post a code example of how to capture the video it would be very helpfull.
thank you... | Video capture API in Windows is DirectShow or Media Foundation. With DirectShow you can capture video in a way similar to other video sources (frame grabbers, web cameras etc). See Capture firewire video: does this require DirectShow?.
|
7,894,865 | 7,894,883 | Equivalent of const(C++) in Java | I was wondering if there was an equivalent to c++'s const in Java. I understand the final keyword, but unfortunately I cannot use that to declare a functions return value final. Instead, it always ensures the function cannot be overridden, correct?
Basically, I want to make sure a given returned class cannot be modif... |
Basically, I want to make sure a given returned class cannot be
modified and is read only. Is that possible in Java?
Not directly, but one workaround is an immutable object.
Example -
public final Foo{
private final String s;
public Foo(String s){
this.s = s;
}
// Only provide an accessor... |
7,894,930 | 7,894,960 | Online C++ compiler with input stream? | I kinda like codepad online editor (supports C++), but I'd like to use some scanfs which is not possible with codepad.
Is there some online C++ compiler that supports input streams? Is that even possible?
| IDEOne supports passing in the input; you can specify it in a <textarea>.
|
7,894,957 | 7,895,162 | Windows lowest level socket programming? | I'm having a little bit of confusion regarding how low-level winsock is? I am wanting to write a VERY basic client-server program on windows. I don't really wish to use a bloated TCP or even UDP, just something extremely basic and low latency. Would winsock be ideal for this? Or is winsock the same as the windows netwo... | Winsock, TCP, UDP, and any well received networking library built on top of these are all going to be comparable performance wise.
Use whichever one is easiest to get your work done.
|
7,894,967 | 7,894,989 | Does a method local structure require executing the default constructor | When a you declare a struct in a class method, how is the memory for that struct allocated? For example:
void Foo::Bar(void)
{
struct timeval a;
a.tv_sec = 1;
a.tv_usec = 0;
...
}
Is a allocated on the stack like any other local data (int, double, etc.), or is a default constructor called and the mem... |
Is a allocated on the stack like any other local data (int, double, etc.), or is a default constructor called and the memory allocated on the heap?
It is allocated on local storage(stack).
An object will be created on Freestore(heap) only when any of the new versions of the operators(except maybe placement new) ar... |
7,894,973 | 7,895,043 | Problems with linking .cpp files in Code::Blocks | I'm having a headerfile called cnVector.h whose implementation is written in cnVector.cpp.
Those two files are located in the same directory.
cNormalCBP/
+ src/
+ cNormal/
+ cnUtils/
- cnVector.h
- cnVector.cpp
- main.cpp
The header contains a simple class defi... | Move your inline functions to your header file. Inline functions need their entire definitions in the header files because of how they integrate with the rest of your code. The compiler will (maybe) attempt to insert the code at all locations where the function is called, so it needs to be visible in the header file si... |
7,895,186 | 7,895,244 | Trouble initializing a variable | below is a code I am writing to learn about using files in C++. I have everything reading and writing correctly but I can not get my display to show the correct values because it is ignoring when I try to initialize the Total variables in the while loop.
#include <iostream>
#include <iomanip>
#include <fstream>
using ... | You do not have your variables initialized in the first place, so they don't have any initial values. Then you add something to those variables, and the result is undefined (read garbage).
Consider declaring them like this:
double beginningTotal = 0, purchaseTotal = 0, paymentsTotal = 0, financeChargeTotal = 0, endingT... |
7,895,279 | 7,895,474 | How to prevent pcre(C library) to continue matching when it failed in one string? | If I have a string and a pattern:
char src[]="\"http://www.aaa.cn\"</tab><tab>\"www.bbb.com\"";
char pattern[] = "\"http:\/\/.*\.com\"";
Then it returns "http://www.aaa.cn\"</tab><tab>\"www.bbb.com" to me (it failed but continue matching next characters).
I just want some like "http://www.aaa.com", "http://www.bb... | Try this.
char pattern[] = "\"http://[^\"]*\"";
Better yet, don't parse HTML (or fragments thereof or XML) with regexen.
|
7,895,295 | 7,895,396 | std::map<string, class> print the value of the key | My program is written in C++.
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Details
{
int x;
int y;
};
typedef std::map<string, Details> Det;
Det det;
Details::Details(int p, int c) {
x = p;
y = c;
}
int main(){
... | My best guess is that you have no default or copy constructor in your Obj (you don't have any in the code you posted, but I assume you have one that takes two integers). You've also got a typo in the catalog.insert() line. Here is what worked for me, using your code:
class Obj {
public:
Obj() {}
Obj(int x, in... |
7,895,364 | 7,895,481 | Move element in array in order | How to move element in array in order or remove from array?
Example: arr[3,3,2,1]
move(arr[0],arr[sizeof(arr)]);
arr[3,2,1,3];
I wrote function, but is correctly it ?
void remove(int index, char *arr)
{
arr[index]=NULL;
for(int i=index;i<sizeof(arr)-1;i++)
swap(arr[i],arr[i+1]);
}
| This already exists in the C++ standard library (std::rotate), and the C standard library (memmove)
If you're using C++, (since it comes with a std::swap function, and C can't swap with parameters like that):
void remove(int index, char *arr, int len)
{
if (len<=0)
len = strlen(arr);
std::rotate(arr+ind... |
7,895,383 | 7,895,458 | Script that replace each repeated letter in a string with one letter | I have a script which takes a word from input file and outputs customizated word in output file.
For example, in input file I have word ccccccaaaaaannnnndlllllleeeeeand I need to edit the word it to look like candle and output in other file. So could you please give me a example of it?
So far I have:
#include <iostrea... | Assuming you mean consecutive repeated letters, std::unique does exactly that.
vards.erase(std::unique(vards.begin(), vards.end()), vards.end());
|
7,895,420 | 7,895,547 | C++11: intptr_t/int_ptr_t, intmax_t/int_max_t? | I'm doing a bit of reading on c++11 and I've noticed a couple things about int type names. Right now, apparently the spec is only available by paying for it but there is an early draft from February available at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
However I noticed on a website which is ci... | Yes, it's just a typo on the website. From the FDIS, §18.4.1 (Header <cstdint> synopsis):
namespace std {
...
typedef signed integer type intmax_t;
typedef signed integer type intptr_t; //optional
...
typedef unsigned integer type uintmax_t;
typedef unsigned integer type uintptr_t; //... |
7,895,426 | 7,895,456 | using c++ const on user-entered data? | Suppose that I wanted to read an integer from cin and then make it immutable. I can do:
int a;
cin >> a;
const int b = a;
Then, I would have a variable (b) which is initialized to user data, but cannot be changed. However, I think I'm abusing the const keyword here. Is this an acceptable thing to do? The compiler seem... | It's completely fine. You're free to create const variables from non-const data, even user-entered data.
You might even write a function so you don't have the stray a variable sitting around afterward. For example:
int read_int(std::istream& in) {
int a;
in >> a;
return a;
}
int const b = read_int(std::cin);
|
7,895,652 | 7,909,820 | Is there a way to compare obj files from Visual Studio? | I've got a C++ project that builds in several configurations (not just Debug/Release), and it's a rather massive project. Let's call it KitchenSink.vcproj
I suspect that many pieces of this project build identically, regardless of the configuration. E.g. Building with/without Unicode support will not matter for a sou... | To see if a project is building the same file in different configurations, but pointlessly, it is best to compare the output of the preprocessor. Comparing object files is simply too prone to failure, and not necessary.
The basic idea is: Run the preprocessor on a file in multiple configurations, and compare the outp... |
7,895,700 | 7,895,872 | Forward declarations that involve std::vector, etc | I have used forward declarations a lot; they help avoid many #includes, improve compilation time and what not. But what if i want to forward-declare a class in the standard library?
// Prototype of my function - i don't want to include <vector> to declare it!
int DoStuff(const std::vector<int>& thingies);
I have heard... | The reason I wouldn't do this:
const std::vector<int>& a = a_3rd_party_lib::get_data(); // this type is out of your control
DoStuff(a); // you cannot pass it to this function!
|
7,895,704 | 7,896,002 | Retrieving ActiveX classID from the system registry with C++ | I am working on a windows application that has a shockwave flash player embedded in it.The C++ part should be able to call Flash movie methods and vice versa.Initial experiment was done using MFC.It works.But now I want to port it to Qt as it allows easier UI development.Qt has got QAxObject which holds the ActiveX co... | It would be better to query from the registry by mime type. You can find details on where that is stored here:
http://msdn.microsoft.com/en-us/library/aa751976%28v=vs.85%29.aspx
You can look up the mimetype in the registry and get the CLSID from that. You can look it up by name as well; the locations of both registry k... |
7,895,809 | 7,895,873 | how to stop listening to a port | I have a linux application written in c++.
The application listens to a socket on a certain port. I implemented this using ACE Acceptor.
In addition the application starts postgresql database using the init script /etc/init.d/postgresql start by calling the ACE_OS::system function.
The problem I am having is: When the ... |
Is there a way to close the port?
Yes. Close the socket, or set FD_CLOEXEC on the underlying file descriptor.
Or ... wrap your call to the child process (...postgresql start) with something that will close fds higher than stderr:
ACE_OS::system("perl -MPOSIX -e 'POSIX::close($_) for 3 .. sysconf(_SC_OPEN_MAX); exec... |
7,895,817 | 7,897,210 | Is there a raycasting library in C++ that is simple and open source? | I'm looking for a library that will let me cast a ray into a scene model (it happens to be a terrain model in our case) and return the point of intersection in the scene. It does not have to be super-efficient (although I'd rather it not be super-inefficient). Ideally it would not have dependencies on other libraries... | Unless there are other requirements you haven't revealed, use CGAL's AABB tree's support for ray intersections (example).
(Please, don't even think about using this if you're actually trying to do terrain rendering though... there are far more efficient algorithms for ray-casting height fields for the purpose of produc... |
7,895,868 | 7,896,001 | A little rusty on C++ class inheritance | What are the rules for a subclass accessing protected member objects? I thought I understood them but my code disagrees.
I have a base class, defined as
class Datum {
public:
Datum(Datum *r, Datum *l) : right(r), left(l) {}
protected:
Datum *right, *left;
};
I subclass Datum as follows:
class Column: public Dat... | The problem is Datum::Datum *right is protected. Pointer right is accessible / assignable because the base class is inherited publicly. But the object pointed by right has no access previliges the way you are trying to in the member function Column::cover() because the object pointed by right has no direct relation in ... |
7,895,879 | 7,896,206 | Using member variable in lambda capture list inside a member function | The following code compiles with gcc 4.5.1 but not with VS2010 SP1:
#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <set>
#include <algorithm>
using namespace std;
class puzzle
{
vector<vector<int>> grid;
map<int,set<int>> groups;
public:
int member_function();
... | I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.
Now, it's exactly like the error message says: You can't capture stuff outside of the enclosing scope of the lambda.† grid is not in the enclosing scope, but this is (every access to grid actually happens as this->... |
7,895,888 | 7,895,965 | GetAsyncKeyState's return values don't seem to correspond with the description | I investigated GetAsyncKeyState after seeing it in a code example on how to make a fictional character move on the screen through the WASD keys.
I read this on its MSDN page:
Return value
Type: SHORT
If the function succeeds, the return value specifies whether the key
was pressed since the last call to GetAsyncKeyStat... | GetAsyncKeyState(chr) == 0x8000
This is incorrect check. Use:
!!(GetAsyncKeyState(chr) & 0x8000)
to see if the most-significant bit is set.
The value 0xFFFFFFFFFFFF8001 doesn't correspond to the actual returned value from GetAsyncKeyState. Windows calculator doesn't know the size of the value returned from GetAsyncKe... |
7,895,894 | 7,943,024 | How do I append read_some buffer? | I have some client asio code that uses read_some() until the number of bytes has been read. But from looking at all the examples, I can't figure out how to assemble the read buffer into a larger one that contains the entire message. How do I do this?
boost::array<char, 4096> buf;
while (lnTotalBytesRead < BigMessageS... |
I can't figure out how to assemble the read buffer into a larger one
that contains the entire message. How do I do this?
Use a streambuf instead of a boost::array for your buffer. Though, as Andy said you really should be using read(). As the documentation states, it is a composed operation and handles invoking rea... |
7,895,994 | 7,896,147 | Are there any open source, hardware-accelerated crossplatform physics libraries with C++ bindings? | I'm working on a game using OpenGL and C++. I would really like hardware accelerated physics, but cross-platform. Is there anything out there, maybe implemented in OpenCL?
| The Bullet physics library is an excellent choice. It's a C++ library, with comprehensive OpenGL demos, and supports OpenCL acceleration.
|
7,896,035 | 7,896,096 | C++ Make a file of a specific size | Here is my current problem: I am trying to create a file of x MB in C++. The user will enter in the file name then enter in a number between 5 and 10 for the size of the file they want created. Later on in this project i'm gonna do other things with it but I'm stuck on the first step of creating the darn thing.
My prob... | Potentially sparse file
This creates output.img of size 300 MB:
#include <fstream>
int main()
{
std::ofstream ofs("ouput.img", std::ios::binary | std::ios::out);
ofs.seekp((300<<20) - 1);
ofs.write("", 1);
}
Note that technically, this will be a good way to trigger your filesystem's support for sparse fil... |
7,896,223 | 7,929,203 | How to schedule member function for execution in boost::threadpoool | I found a threadpool which doesn't seem to be in boost yet, but I may be able to use it for now (unless there is a better solution).
I have several million small tasks that I want to execute concurrently and I wanted to use a threadpool to schedule the execution of the tasks. The documentation of the threadpool provide... | I think I found out what I need to do: I have to make a runnable which will take any parameters that would be necessary (including a reference to the object that has a function which will be called), then I use the static schedule function to schedule the runnable on the given threadpool:
class Runnable
{
private:
... |
7,896,265 | 7,896,341 | two consecutive newline characters as a delimiter - C/C++ | I'm writing a getline function below but I want the delimiting character to be two consecutive newline characters such the function stops reading once it reaches a blank line.
in.getline(temp, 127, delimiter);
Is it possible to do this with getline?
| Delimiter must be a single character for istream::getline. However, you could always buffer the result yourself, checking the next character (peek) to see if its a newline.
|
7,896,314 | 7,896,335 | itoa creates an infinite loop in C++ | This is very strange. itoa(); seems to create an infinite loop.
for(int i = 0; i < 10; i++)
{
char buffer[1];
itoa(i, buffer, 10);
std::cout << buffer;
}
Why on earth does it do that? I've tried using different variables than i, numerical values without variables (i.e. itoa(1, buffer, 10);), it... | itoa null-terminates the string it produces, but you haven't made buffer large enough to hold the terminating NUL character. Try:
for (int i = 0; i < 10; i++)
{
char buffer[2];
itoa(i, buffer, 10);
std::cout << buffer;
}
|
7,896,340 | 7,896,363 | Accessing values in a 2D array incorrectly | I have a 2D array such as:
// construct initial **array
int **arr;
arr = new int* [SIZE];
for (int i = 0; i < SIZE; i++) {
arr[i] = new int[SIZE];
}
I am then filling the array with input from cin, and that is working fine. Yet when I go to access the values in the a... | It looks like you are storing the ASCII values of the numbers rather than their numeric values, for example the character 1 has ASCII value 49. Check that the variable you are using to read input is a numeric type and not char.
|
7,896,422 | 7,896,504 | Threaded Chat Session between 2 users using C++ | I want to build a simple chat session between two users, not more. I know that this should be done using socket programming, but to be honest i haven't worked in this domain yet so this will be my first.
I need to know where to start from and was wondering if there are any samples that you suggest i start from.
Than... | If you are using Windows, then I would suggest looking at this site to learn the WinSock API.
http://tangentsoft.net/wskfaq/
Section 6.1 contains some example code which I found very helpful when first learning socket programming.
|
7,896,426 | 7,896,443 | How can I debug a program that starts but appears to do nothing? | I currently have 2 virtual machines running, one is a server and one is a client. They are both running Ubuntu. I created a C++ program to connect to a MYSQL server. When i open up a terminal in the server VM, the c++ program compiles and runs PERFECTLY!
BUT, when I try to run it on the client, it wont work at all. The... | Either add logging to your program or run it under strace to figure out where it's getting stuck or what it's waiting for.
At the most basic level, you add logging by adding log statements. Say your code looks like this:
a();
b();
c();
output_stuff();
Temporarily change it to:
cout << "about to do a" << endl;
a();
cou... |
7,896,581 | 7,950,509 | intel pin RTN_InsertCall multiple function arguments | I'm trying to obtain the values of the arguments to a function using intel pin. Single argument functions are simple enough using the example ManualExamples/malloctrace.cpp . However, when I try to get the argument values with multiple arguments I run into trouble.
Eg. Trying to capture the argument values of the foll... | I think it's actually a pretty easy one to fix, since you've basically got everything right to begin with.
The only problem is that when calling RTN_InsertCall, you only extract the first argument (which is why Pin and Actual are the same for the first argument but not the others). You simply need to give a few more a... |
7,896,746 | 7,896,796 | How do I cancel CFtpConnection::PutFile? | ftp server and client (C windows) using a UDP socket.
The server puts files on the client using CFtpConnection::PutFile
A large file takes several minutes, so the client needs to be able to cancel PutFile().
How do I check for a cancel udp message if PutFile() is busy transferring data? Create another thread....?
Any a... | Since you need some level of control for the transfer process, you can't go with the high-level approach of PutFile and you 'll have to take a more direct role.
Open the remote file with CFtpConnection::OpenFile for writing, which will give you a CInternetFile*. You would then write data using CInternetFile::Write by y... |
7,896,937 | 7,897,054 | Ordering using stl sort in Visual Studio and GCC | Writing a program that should be portable in Linux and Windows enviroments I have found a issue with the STL sort function, when compiling with Visual studio and gcc.
In order to sort a vector of complex data structures I have written an int conversion operator for the structures in that form:
struct result
{
public :... | The only meaningful difference I see between the two comparison methods is that the second will work when the element is const. The first should probably be:
// vvvvv
operator int() const
Even though you're modifying the container, your comparison still has the requirement that it work on const objects. In... |
7,897,050 | 7,897,057 | Adding to a vector of pair | I have a vector of pair like such:
vector<pair<string,double>> revenue;
I want to add a string and a double from a map like this:
revenue[i].first = "string";
revenue[i].second = map[i].second;
But since revenue isn't initialized, it comes up with an out of bounds error. So I tried using vector::push_back like this:
... | Use std::make_pair:
revenue.push_back(std::make_pair("string",map[i].second));
|
7,897,107 | 7,897,187 | Using gluPerspective() | I'm learning OpenGL; I managed to make my first 2D program but I am stuck on using gluPerspective.
I'm trying a little test to try to grasp how I can go about making a 3D project but I can't seem to figure out what I am missing and what is needed to make this small test work:
void init_perspective()
{
SDL_Init(SDL_... |
gluPerspective(45, 1.333, 0, 100);
Never set zNear to zero. It messes up the math:
Because r = zFar / zNear approaches infinity as zNear approaches 0, zNear must never be set to 0.
Choose some small positive number like 0.01 or 12.
EDIT: Also, put your camera somewhere such that it can see your geometry:
int main(... |
7,897,163 | 7,897,179 | std::cout to print character N times | How can I print a character N number of times using std::cout without looping?
Is there a way to move the text cursor back to nullify the effect of std::cout << std::endl;? i.e. to move up a line (say we never printed anything after doing the std::cout << std::endl; operation).
| std::cout << std::string(100, '*') << std::endl;
To move a line up, you have to resort to terminal escapes (assuming that isatty() indicates that you are running on one).
|
7,897,195 | 7,897,275 | How to write efficient Genetic Algorithms in C++ | I am trying to write a C++ program for the canonical genetic algorithm, where you have a population of individuals (chromosomes) of length N, where each element is a O or 1.
I have started writing my program using STL vectors, but before I go more deeply into it I would like to ask your opinions about how to write the ... | The crossover code seems at max efficiency for what you are trying to do with the vectors. From my experience with genetic algorithms, the fitness function and selection operator are the most time intensive. Since you will be using crossover and mutation on a sample of the population you don't have to worry too much ab... |
7,897,373 | 7,897,407 | What is the c++ equivalent of Javascript's "in"? | I'm trying to check whether a string exists in an array in as little lines as possible example:
string foo[] = {blah,blahhh,blahhhh}
string bar = "blah";
if (bar in foo){
cout << "true";
}else {
cout << "false";
}
| There is not this keyword nor this construct in C++.
You have to do a loop or use the find function.
http://www.cplusplus.com/reference/algorithm/find/
For other people that try to do the same thing (since is a question a lot of people asked to me in the past) : char arrays and string literals (that are const char arra... |
7,897,612 | 7,897,635 | Check Palindrome using recursion | I am trying to implement a function that will check to see if a word is a palindrome Below is the code that i have tried to use. the code works for one letter words obviously and words that don't start and end with the same letter. It fails on anything else. Please help
bool is_palindrome(int start, int end, const stri... | start++ increments the [local] variable start, and evaluates to the old value. You want to evaluate to the new value, and you don't need to alter the local variable at all.
So write start+1, end-1 instead, and then consider the case where your string has an even number of characters because there is another issue there... |
7,897,677 | 7,897,774 | Casting error with GetModuleFileNameW | I'm trying to get the version information for a module in some C++ code (basically this) and I'm getting compile time errors. Here's the code:
WCHAR fileName[MAX_PATH];
HMODULE module = GetModuleHandle(L"some-module");
DWORD size = GetModuleFileName(module, fileName, MAX_PATH);
And the compiler is returning:
erro... | There must be something funky going on with your includes or your libraries, because this compiles and runs fine here:
// Scratch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR fileName[MAX_PATH];
HMODULE modu... |
7,897,802 | 7,897,906 | Long array performance issue | I have an array of char pointers of length 175,000. Each pointer points to a c-string array of length 100, each character is either 1 or 0. I need to compare the difference between the strings.
char* arr[175000];
So far, I have two for loops where I compare every string with every other string. The comparison function... | One simple optimization is to compare the strings only once. If the difference between A and B is 12, the difference between B and A is also 12. Your running time is going to drop almost half.
In code:
int compr(const char* a, const char* b) {
int d = 0, i;
for (i=0; i < 100; ++i)
if (a[i] != b[i]) ++d;
retur... |
7,898,395 | 7,901,118 | Which function structure is better? | Look at the following code:
class MyClass{
public:
MyClass(){}
MyClass(MyClass &&){}
MyClass(const MyClass &){}
};
MyClass f1(){
MyClass &&o=MyClass();
/*...*/
return std::move(o);//or return static_cast<MyClass &&>(o);
}
MyClass f2(){
MyClass o=MyClass();
/*...*/
return o;
}
int m... | This is how current compilers (MSVC10 / gcc trunk) works :
Assuming MyClass is moveable
f1 : move
f2 :
worst case : move
best case : NRVO
Assuming MyClass is not moveable :
f1 : copy
f2 :
worst case : copy
best case : NRVO
So even if compilers get better and start doing NRVO for functions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.