question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,127,115 | 5,127,136 | C++ Smallest common divisor rewrite | I made a function that returns the smallest common divisor of 2 numbers.
int check (int a, int b)
{
int i = 2; //every number is divisible by 1
begin:
if ((a % i == 0) && (b%i == 0)) //i must be divisible by both numbers
{
return i;
}
else
{
i++;
goto begin;
... | If a and b are co-prime (gcd=1) your algorithm will only terminate once i has overflowed and reached -1. i.e. after 4 billion iterations.
And even if this is not the case your algorithm is slow(linear in gcd(a,b)). You should look into the Euclidean algorithm which is much faster.
Your code in rewritten form(terminatio... |
5,127,249 | 5,127,276 | Open file with Windows' native program within C++ code | My C++ program creates .png file and I need to open (view) this file right after creation - is there a way to open it as so it was opened within Windows explorer - so file wiil be opened with user's preferred program and if there are no associated programs with file's format - Windows will show dialog window in which u... | On Windows, you can use the ShellExecute function.
|
5,127,421 | 5,134,372 | MySQL comparing CHAR(m) character by character | In my table one of my fields has a type CHAR(26). Instead of using STRCMP() to compare each character and stop when there isn't match, I want to compare all characters. In a C++ function with std::string or any kind of vector really, it would look like the following:
bool lesser(str1, str2) //str1 < str2
{
for (int ... | I don't know of a mysql function to do the same thing that your C++ code does, but you should be able to do it with your own function. I've not tested this code, but it will probably look something like this:
CREATE FUNCTION mylesser(s1 CHAR(26), s2 CHAR(26))
RETURNS BOOL
BEGIN
DECLARE ndx INT DEFAULT 0;
WHILE... |
5,127,483 | 5,127,564 | Summing Prime Numbers below two million | You may have heard of a website called Project Euler (projecteuler.net). I'm working through the first problems, which were quite trivial, and I'm on the problem described in the title.
This isn't about optimising or anything - it takes about 90 thousandths of a second to complete. It's giving me the wrong total.
Can s... | Here's a clue to at least one problem. Have a look at what happens when you replace:
for (int c=0;c<=np;c++){
atotal += pa[c];
}
with:
for (int c=0;c<=np;c++){
bignum oldatotal = atotal;
atotal += pa[c];
if (atotal < oldatotal)
cout << "Hmmm: " << oldatotal << " " << atotal << endl;
}
I get so... |
5,127,522 | 5,127,639 | How do I make a static library Release/Debug independent in VS2010 Express? | I am programming an application and linking against SDL and OpenGL. In my code I have the following lines:
#pragma comment(lib, "sdl.lib")
#pragma comment(lib, "sdlmain.lib")
#pragma comment(lib, "opengl.lib")
This works in Release mode only. In Debug mode, I receive the following linker error:
libcmt.lib(invarg.obj... | In vs2005 in project configuration, under linker options, I would set "ignore specific library" to libcmt.lib . vs2010 config might be similar. In any case, please try to ignore libcmt.lib and see what happens.
-- pete
|
5,127,660 | 5,128,722 | How can I tell QGraphicsItem::paint() is being called for printing? | I have a custom QGraphicsItem that display large (100s of MB compressed, mutli-channel) images. It's working pretty well right now.
The idea is only load scanlines that are needed for current view scale and graphics view port. And divide the display into tiles that are built in separate threads. The paint() function on... | Just an idea, don't have a printer right now to test it.
There is a device() method in QPainter class which returns the paint device on which this painter is currently painting, or 0 if the painter is not active. The paint device could be implemented by the QWidget, QImage, QPixmap, QGLPixelBuffer, QPicture, and QPri... |
5,127,795 | 5,127,806 | Short int - how to save to the file | I have unsigned short int (from 0 to 65535) and I must save it to the file, using stdio and consuming 2 bytes, but I don't know, how.
Any suggestions?
| http://www.cplusplus.com/doc/tutorial/files/ It's good to read the whole thing, but the information you need is in 'Binary files' in the bottom half of the article.
ofstream outputFile;
outputFile.open("yourfile.dat");
unsigned short int i;
i = 10;
outputFile.write(&i, sizeof(i));
outputFile.close();
|
5,127,805 | 5,127,938 | C++ error when using stream buffers directly with ?: operator | When I try to use a ternary conditional operator (?:) with stream buffer redirection, gcc produces 'synthesized method first required here' error. What is the problem, and how to correct the following program?
#include <fstream>
#include <iostream>
int main(int argc, char* argv[])
{
using namespace std;
cout <... | This compiled OK with my version of clang, I think that it may be a gcc bug.
From my reading of the standard, cout is an lvalue of type std::ostream and ofstream("tmp.txt") is an rvalue of type std::ofstream.
Neither has any cv-qualifiers and std::ostream is a base class of std::ofstream so the conditional operator is ... |
5,127,865 | 5,127,881 | Help with displaying list of contents C++ Linked lists! | void display()
{
list *newlist;
newlist = first;
cout << endl;
do
{
if (newlist == NULL)
cout << "List is empty" << endl;
else
{
cout << "Name is: " << newlist->name << " ";
cout << "Age is: " << newlist->age << " ";
cout << "... | Mahis, in your previous post I corrected your source code. Please read the comments in the code I provided. This will answer your question. See here.
You may have initialized your current to NULL, but when you add an element, you also need to set current to the correct value. For example, when you insert the first valu... |
5,127,981 | 5,129,533 | Portable C++ Component Design | I've been using COM and .NET assemblies in the past to develop component-based-systems. Now I'm going to work on a cross-plattform-C++-project and want to structure the code in components aswell…
Obviously COM and .NET are not an option, as COM is not available anywhere but Windows and Assemblies would add dependencies... | I have worked with such a system in the past - we basically re-invented COM. If you are interested in that approach, check out this great article: http://msdn.microsoft.com/en-us/library/ms809983.aspx
|
5,128,041 | 5,128,233 | How to apply a spline basis matrix? | 1) I have a bunch of spline control points ranging from P0 to PN.
2) I have a spline basis matrix.
How do I, given 2 control point indices and a t value, apply the basis matrix to get an interpolated position?
Now I keep seeing the following form:
[b00, b01, b02, b03] [p0]
[b04, b05, b06... | Yes, it's per component, so each p is a single number. They are the x-coordinates (say) of four consecutive control points.
Your matrix thing is simply the product of three matrices: ordinary matrix multiplication. So it's a sum: t^3.(b00.p0+b01.p1+...) + t^2.(b04.p0+b05.p1+...) + etc. And that's your coordinate value ... |
5,128,139 | 5,128,674 | Gotoline in Qt Creator | Well, I'm doing a Goto Line System. But it seems it doesn't work. It did before but I think I broke it.
void ScriptWindow::gotoLine()
{
int line = QInputDialog::getInteger(myEdit, "Line Number","To what line do you want to go?", 1, 1, myEdit->document()->lineCount());
QTextCursor cursor = myEdit->textCursor();
... | Set the cursor position to zero, move down by number of lines, and set myEdit's text cursor.
QTextCursor cursor = myEdit->textCursor();
cursor.setPosition(0);
cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, line-1);
myEdit->setTextCursor(cursor);
Alternatively, find the position via the QTextDocument a... |
5,128,358 | 5,129,654 | SDL_GL_SwapBuffers() in a loop = Freeze? | I read a few tutorials about OpenGL and now I'm trying to use it with SDL. The thing is that when I use SDL_GL_SwapBuffers() in a while loop the window just freezes. Here's some code:
#include "SDL.h"
#include "system.h"
#include "SDL_opengl.h"
System Sys(800, 600, 32);
SDL_Event kpress;
int main( int argc, char* args[... | My first advice: Get rid of that bogus System class: So far all the tasks it does are purely sequential/procedural and that should be reflected in the programs outline. People tend to put everything into classes just becase they're taught see everything in terms of object models. But this System class would have to fol... |
5,128,432 | 5,128,509 | Linked list - Almost done, but still minor problems somewhere. Help needed | void currentfor()
{
if(current == NULL)
{
cout << "You don't have any members yet!" << endl;
}
else
{
if (current->next == NULL)
cout << "This is the end of the list." << endl;
else
current = current->next;
}
}
void currentbac()
{
if (current == first)
co... | "I try to add a node at the "current"position when i move but its always adding at the end after all the nodes."
The problem is with you add node code, not your moving code.
You have not posted your add node code, so it is very hard to say what the problem is. You will have to unlink the nodes before and after the new... |
5,128,578 | 5,128,902 | Initialize a class members reference variable, as if it was a regular variable | Right now, I am writing a physics engine for a game I am developing. Often times, there is many repeated values when you combine a physics engine with a game engine. Such as variables denoting the position and rotation of an object. With most physics engines, you have to iterate through all the objects and update their... | Do what you're doing now, just keep an extra bool variable to indicate whether your memory was allocated or not. Then, in the destructor, you can call delete after checking that value, i.e.
struct object{
float & xPosition;
float & yPosition;
float & zPosition;
object(float & xPos, float& yPos, float& zPos)
... |
5,128,608 | 5,128,641 | overloaded member functions for a particular template specialisation | I have a class tPoint that would be implemented having different base types so
template<typename T>class tPoint{
T x;
T y;
public:
void Set(T ix, T iy){x=ix;y=iy;}
};
When the type T is int, tPoint<int>, I want a special Set(float, float) so I can round the values before assignation.
I thought that with speci... | You need to specialize the class, like this:
template<> class tPoint<int>{
int x;
int y;
public:
void Set(int ix, int iy){x=ix;y=iy;}
void Set(float ix, float iy){x = ix+0.5; y = iy+0.5;}
};
|
5,128,639 | 5,128,672 | Can C++ compiler assume a const bool & value will not change? | Can the C++ compiler assume a 'const bool &' value will not change?
For example, imagine that I have a class:
class test {
public:
test(const bool &state)
: _test(state) {
}
void doSomething() {
if (_test) {
doMore();
}
}
void doMore();
private:
const bool &_test;
};
And I use it as fol... | No. Just because your reference (or pointer) is a const does not stop someone else from having a non-const reference. Like this:
int main(void) {
bool myState = true;
test myTest(myState);
std::cout << myTest.getState() << std::endl;
myState = false;
std::cout << myTest.getState() << std::endl;
}
Or even mor... |
5,128,755 | 5,128,767 | Error when running g++ app. (encryption of string) | I'm trying to encrypt and decrypt files with C++, using this code:
#include <iostream>
void crypt(char* pData, unsigned int lenData, const char* pKey, unsigned int lenKey)
{
for (unsigned int i = 0; i < lenData; i++)
pData[i] = pData[i] ^ pKey[i % lenKey];
}
int main()
{
char* data = (char*)"any binar... | This line is wrong:
char* data = (char*)"any binary string here";
First, you should not use a cast. Next, a string literal is a constant. So it should be:
const char* data = "any binary string here";
But you're wanting to overwrite it. So you need a string that isn't a constant. Like this:
char data[] = "any bina... |
5,128,895 | 5,128,956 | Strange Way to Initialize std::string with C string | while I was reading nVidia CUDA source code, I stumbled upon these two lines:
std::string stdDevString;
stdDevString = std::string(device_string);
Note that device_string is a char[1024]. The question is: Why construct an empty std::string, then construct it again with a C string as an argument? Why didn't th... |
Why didn't they call std::string stdDevString = std::string(device_string); in just one line?
No good reason for what they did. Given the std::string::string(const char*) constructor, you can simply use any of:
std::string stdDevString = device_string;
std::string stdDevString(device_string);
std::string stdDevStrin... |
5,129,001 | 5,129,044 | Allowing a class function to easily be replaced | I often have a class where I want to allow a functionality to be selected. For example I have a class that has a GetNextNode() function which is used like MyClass::DoIteration(){GetNextNode(); } . I want to allow the user to select from one of many possible implementations of GetNextNode to determine how the next node ... | This looks like the Strategy Pattern Edit: And if you only need compile time variations, the Policy-based design you disovered yourself can be more appropriate.
class NextNodeStrategy {
public:
virtual int GetNextNode() = 0;
};
class MyClass {
private:
NextNodeStrategy &nextNode;
public:
void Se... |
5,129,017 | 5,129,055 | Multiple Version Resources | I am writing several C++ libraries inside of visual studio. I know I can use the Version Resource to assign DLL's a version, product name, and so on but is there a way that I can swap out different Resource scripts depending on my configuration settings. For instance, say I am compiling for x86 I want the product name ... | You can use #ifdefs in resource files. But using #ifdefs directly in he resource files, can sometimes screw with the IDE's resource editor (it has happened for me in Visual Studio 2008). I would therefore create two resource files (e.g. resource-x86.rc and resource-x64.rc) and include them in the main rc file like this... |
5,129,208 | 5,129,231 | C++ Help with pointers for a student | I am trying to create a vector and pass it to a function allowing the vector to be modified. Here is an abridged version of my code that doesn't work.
void addStudent(vector<Student*>*);
int main()
{
vector<Student*> students = new vector<Student*>;
addStudent(students);
return(0);
}
void addStudent(vector<St... | You've promised to give addStudent a pointer to a vector:
void addStudent(vector<Student*> *students)
so, use the address-of operator to get a pointer:
vector<Student*> students;
addStudent(&students);
There's nothing here that actually needs dynamic allocation, but if you did, note that new also returns a pointer:
v... |
5,129,312 | 5,129,337 | Are simple type variables objects in C++? | Are simple type variables objects in C++?
int x = 0;
Obviously, that depends on the definition of the object. So would x be object in this case? It may not be defined by the standard in any way, but please do claim so if you are sure that this is either object or it is not.
| Yes (object in the standard are simply a region of storage -- 1.8/1)
An object is a region of storage. [Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do. ] An object is created by a definition, by a new-expression_ or by the implementation when needed.
An... |
5,129,463 | 5,130,485 | Help with order of events in GUI | I'm making a game GUI and basically each Widget can have other widgets which listen to mouse or keyboard events. Anyone of these can consume the event too (and then any subsequent ones will not receive it.
The part I'm unsure for is if the order shoud be:
Send event to Target Widget
if(event is not consumed)
... | The best event model I've every used is from the Tk toolkit (and I've used perhaps a dozen toolkits professionally during my career). The naive description is that the event starts from the most specific (the actual widget in which the widget occured) up a chain to the least specific (a global binding).
It's a little ... |
5,129,690 | 5,129,770 | What's the best way to have a variable be accessible from anywhere in your program? | I'm making a game right now and pretty much everything has its own class. The main classes I feel that I have a problem with are my 'Level' and 'Object' class. The level class contains images to every image in the level, and the Object class contains the image for each object on the screen(an object is pretty much anyt... | You should usually avoid "making variables accessible from anywhere" - see here for why.
In your case, that means it's a bad idea to make the ResourceManager accessible from everywhere. I suggest you do as you say in the post - have every game object keep a pointer to the resource manager.
In the future it may turn out... |
5,129,731 | 5,129,793 | Regular Expression in C++ | I want to write C++ library for Regular Expression. I know there are many libraries available but I want to learn theory behind regular expression and implemented it by myself.
Can anybody please guide on what should I start with.
| http://swtch.com/~rsc/regexp/regexp1.html has a good explanation of the two major approaches to regular expressions, their trade-offs, and how to make the faster one (DFAs) usable in a lot of cases that most implementations fail to use them for.
|
5,129,790 | 5,129,824 | no matching function for call when trying to use get function from fstream library | I'm getting two errors in main that have me stumped:
"no matching function for call"
"invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'"
Could anyone lend a hand? thanks!
header
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <iomanip>
#inc... | Error 1 is because inData.get() does not take an int, you should do
grade = inData.get();
and the second is because list is actually an int* and not an int so the fourth parameter in input() should be an int* and not an int&
|
5,129,861 | 5,129,909 | How do I make a post using libcurl from a game written in c++ to a php page on my server more secure? | I wrote a game in c++ using SDL. The game currently updates a highscore to my game site by making a post with curl if the user has logged in. The problem that I am having is that the post provides the url to the php file that receives the post on my server, and the variables that the post uses. Last night someone fro... | You could add a small layer of security by passing not only the high score, but a hashed version that is validated on the PHP side.
e.g.
{hs:"2000";hash:'843ed7842a6bd864162022e48b84a668'}
Posted to your PHP script, that then checks,
if($hash==md5('secret'.$hs)){
//UPDATE HighScore
}else{
//Discard, flag spamme... |
5,129,883 | 5,129,960 | Best setup for c++ template/generic/metaprogramming | I am writing/maintaining some heavily templated code in c++. I am currently compiling it on windows but it is getting slower to compile and harder to write.
I want to know if there are any
Tools
Other Compilers
Compiler Switch
IDE
Practice
Dependency Management Technique
Libraries
on Windows/Linux that can help to w... | i use:
gcc 4.4/4.5 and/or icc 11.x
-O0 -Wall -g
emacs (TOO much to say)
boost mpl/type_traits/fusion/phoenix
boost::mpl::print is a god's gift
BOOST_MPL_ASSERT_MSG
boost preprocessor: http://www.boostpro.com/mplbook/preprocessor.html
tyeof/auto: http://www.boost.org/doc/libs/1_45_0/doc/html/typeof.html
result_of: http... |
5,129,943 | 5,130,049 | Tightly coupled parallel class hierarchies in C++ | For context, I'm working on a C++ artificial-life system involving agents controlled by recurrent neural networks, but the details aren't important.
I'm facing a need to keep two object hierarchies for the "brain" and "body" of my agents separate. I want a variety of different brain and body types that can be coupled t... | I think what you are doing is approximately correct. You would want the members such as reproduce to be pure virtual, though, so the base classes cannot be created. What is your issue with type-safety? You don't want the Brain subclass and the Body subclass to depend on each others' types.
|
5,130,015 | 5,130,024 | What is meant by a "x bit hash function" | What exactly is meant by a 64 bit hash function? Does it mean that it can map keys to atmost 2^64 locations?
| A 64 bit hash function is a hash function resulting in a 64 bit output - which are 2^64 different values.
|
5,130,020 | 5,130,159 | Is pointer arithmetic possible with C++ string class? | After programming a little in C I decided to jump right into C++. At first I was pleased with the presence of the string class and being able to treat strings as whole units instead of arrays of characters. But I soon found that the C-style strings had the advantage of letting the program move through it character by c... | string characters can be accessed by index, pointers, and through the use of iterators.
if you wanted to use iterators, you could make a function that checks whether a string has a space in it or not:
bool spacecheck(const string& s)
{
string::const_iterator iter = s.begin();
while(iter != s.end()){
if ... |
5,130,104 | 5,130,124 | How do I set GPU core and memory clock programmatically on Windows? | Is there some API/library for this? I have an ATI Radeon 9000 Series graphics card and I need to lower its core/memory clock on Windows startup (I thought of making a small service for this but I never did this before).
I know it's possible (because RivaTuner does it somehow) but I just haven't figured out how.
Can poi... | I don't think either AMD/ATI or nVidia publishes how to do things like this. It's clearly possible, but from what I've seen you'd probably have to sign a non-disclosure agreement before they'd tell you how to do it.
That said, there is quite a bit of info publicly available -- Linux drivers can be very informative. I'm... |
5,130,134 | 5,130,147 | Calling unmanaged code from a C# thread | I have an unmanaged C++ library for which I've created a managed C++ wrapper. I'm now trying to call this from C#. So far so good. However when I try to call the same code from within in a C# thread I get exceptions from within the unmanaged code:
Expression: vector subscript out of range
Is this even possible? I'm... | Managed types in .NET follow the same rules, no matter whether they're written in C# or C++/CLI.
While it's possible to create a new instance of the C++/CLI class for each thread, it's not going to happen automatically without you telling the compiler that's what you want.
EDIT: Looking at the code, I don't see any pro... |
5,130,142 | 5,130,155 | Terminating input after a ' ' (space) character | I just starting out in C++ and I've reached a problem in some practice questions that I can't quite figure out. I need to be able to read a line from the console in the form of:
N A B C... etc.
Where N is a number, and the following input will be of different types and different amounts based on what N is.
My approac... | You should read in the entire line at once (as requested) and then depending on N, your code should check the rest of the input to make sure it is properly formatted or print out an error.
|
5,130,210 | 5,130,252 | How does a scroll pane do scrolling | In windows, Java, etc, the scroll pane scrolls the widgets inside. What I'm wondering is, how exactly does it do its scrolling? Does it change the location of each nested widget, or does it have a content widget that it moves around? Or is it something else? Also, when both scrollbars are present, how does it mask that... | I think it just changes the location of the widget, button, or thing-a-ma-bober.
But my second guess would be it just draws the components "outside" of the scroll pane without being seen and when you scroll it just redraws dynamically.
|
5,130,292 | 5,130,303 | Am I missing the point of using arrays? | I just finished my first assignment using arrays and I feel like it is a little more complex than it has to be. The program reads a file with scores in it and counts the occurrences of a score within a certain range and then outputs the number of occurrences.
I am wondering if there is a more efficient way of completi... | You're right, because they're evenly spaced it could be a LOT shorter, e.g.
void calculate (int grade, int array[])
{
if (grade >= 0 && grade < 200) {
index = grade / 25;
array[index]++;
}
else if (grade == 200)
array[7]++;
}
output() could be turned into a loop, the calculation for... |
5,130,365 | 5,130,401 | Using abstract base to implement private parts of a template class? | When using templates to implement mix-ins (as an alternative to multiple inheritance) there is the problem that all code must be in the header file. I'm thinking of using an abstract base class to get around that problem. Here's a code sample:
class Widget
{
public:
virtual ~Widget() {}
};
// Abstract base class ... | It doesn't seem like this will work the way you want it to because you lose the ability to have the behavior of the mixin class depend on its template argument. That is, if you want to be mixing in functionality that uses static polymorphism or references the class in the template argument, you no longer can do so bec... |
5,130,461 | 5,130,713 | Implementing a function that "plugs" into a stream | I have implemented a function that prints the memory layout of a struct/class. I would like this function to "plug" into a stream this way:
BaseStruct1 struct1;
cout << "The struct1 object is:" << endl;
cout << OutputObjectLayout(&struct1, sizeof(struct1)) << endl;
How this could be done? Thanks for any input!
| I finally found the answer myself here: http://my.safaribooksonline.com/book/programming/cplusplus/0596007612/streams-and-files/cplusplusckbk-chp-10-sect-3.
Here is an example of how it could be done:
First, we need to define a temporary class to do the work. The temporary structure should look something like this:
cla... |
5,130,504 | 5,130,594 | user-defined operators in C++ | What do you think about an imaginary possibility to specify user-defined operators in C++.
Such user-defined operator could be defined by operator name (arbitrary sequence of allowed chars?), its precedence, associativity and arity (something else?).
They could be used for many purposes: to help to build "tiny" DSLs ov... | Well, Haskell has custom operators with settable precedence and left-right binding. So, it can work. But then, Haskell is cutting edge and barely readable as is, even though it's mostly used by some rather clever people. (Haskell scares off all newbies, I think..)
For C++, I think there are:
parsing issues (consider ... |
5,130,757 | 5,130,786 | C++ -- how to call user defined operator? | I saw the following code snippet:
class WindowHandle {
public:
WindowHandle(WINDOW_HANDLE handle) : w(handle) {}
~WindowHandle() { destoryWindow(w); }
operator WINDOW_HANDLE() { return w; }
...
private:
WINDOW_HANDLE w;
...
}
Here is the question: how do I use operator WINDOW_HANDLE() to get the raw poin... | Simply
WINDOW_HANDLE winPtr = win;
is sufficient. User-defined operators create implicit conversions.
|
5,130,790 | 5,130,800 | C++ class definition compile problems | Ive looked all over and I cant find anything relating to my problem. Im trying to write a class definition for a polygon class that basicly has a vector that holds pointers to a point. When I try to compile i keep geting the folllowing errors...
error C2143: syntax error : missing ';' before '<'
error C4430: missing ty... | You are using vector from the std namespace without qualifying it.
You either have to do using namespace std;, or using std::vector, or declaring all your vector objects with the std namespace like std::vector.
#include "Point.h"
#include <vector>
class Point; // Assuming Point.h has this declared,
// you... |
5,130,902 | 5,130,984 | cmake, boost::filesystem linking error (undefined directory_iterator.operator!=) | I'm using CMake (2.8.3), Boost::filesystem(1.42.0) in Ubuntu 10.10. The code compiles OK but I keep getting the following error when linking:
CMakeFiles/sample.dir/sample.cpp.o: In function `main':
sample.cpp:(.text+0x1af8d): undefined reference to `int operator!=<boost::filesystem::basic_directory_iterator<boost::file... | After adding the missing include files:
#include <string>
#include <iostream>
and namespaces (std), and defining a macro for this "fs" shortcut of your code:
#define fs boost::filesystem
Then I tried the first CMakeLists.txt approach that you mentioned, and it worked... I also have the same system as you.
What I woul... |
5,131,015 | 5,131,198 | Creating an application bundle on OSX with eclipse C++ | I have compiled a project using Eclipse with C/C++ plugin (using http://libcinder.org library, and it's working pretty good.
Sort of...
It is a windowed application, and opengl is correctly redrawing the screen, mouse events are correct, etc. However, I can only run the application from the terminal, otherwise when i ... | Hmmm. This is an architecture problem. I don't know how resources are bundled by Eclipse normally, but they don't use the application bundle architecture that OSX has built in.
Here's the Apple developer docs on NSBundle. Start your reading here!
|
5,131,059 | 5,131,072 | c++ what happens if callee deletes caller? | is the behaviour in a c++ app defined if a callee function deletes the object in which the caller (member) function is defined? will the rest of the caller function body still be executed? will it run correctly if it doesn't access any member variables?
I just ask because I found this case in my application (the resul... | Yes, that is the expected behavior. As long as the code does not access any non-static member objects or functions, there is no reason why it can't keep running.
|
5,131,061 | 5,131,093 | What directive can I give a stream to print leading zeros on a number in C++? | I know how to cause it to be in hex:
unsigned char myNum = 0xA7;
clog << "Output: " std::hex << int(myNum) << endl;
// Gives:
// Output: A7
Now I want it to always print a leading zero if myNum only requires one digit:
unsigned char myNum = 0x8;
// Pretend std::hex takes an argument to specify number of digits.
clog... | It's not as clean as I'd like, but you can change the "fill" character to a '0' to do the job:
your_stream << std::setw(2) << std::hex << std::setfill('0') << x;
Note, however, that the character you set for the fill is "sticky", so it'll stay '0' after doing this until you restore it to a space with something like y... |
5,131,085 | 5,131,136 | Grading Program - Compile/executing C++ code within C++ | I am writing a program to grade C++ code that students submit. Right now it uses a system call to compile every source file then redirects the input to a file and calls the new executables in processes and searches the output for certain strings. This also allows me to have a timeout on processes for programs that cras... | You may want to run the programs under an alternate account, e.g. ssh with key-based authentication is a good way to switch to a dummy account.
If any of the assignments require user interaction, then expect (which is Tcl-based) would be a good choice.
|
5,131,107 | 5,131,317 | WinAPI ShowWindow fails even though CreateWindowEx seemingly succeeds | I am having trouble using CreateWindowEx. If I set the final parameter (LPVOID lpParam) to NULL and use the returned window handle in a call to ShowWindow, the window displays everything fine. However, I need to pass in a pointer to the class that I will be modifying based off of some of the operating system messages t... | Put a breakpoint on CreateWindowEx. Write down the pointer you're passing in.
Put a breakpoint on your WindowProc function. Check that the pointer it extracts from your private window data (that's where you're storing the pointer, right?) is the same one passed in. You are using SetProp and GetProp (see topic Window... |
5,131,329 | 5,131,549 | How to pass a struct from C++ to C? | Updated:
main.h
typedef struct
{
float x;
float y;
float z;
}vec3;
const int sizeOfGrid = 20000;
vec3 *grid[sizeOfGrid];//assume initialized
main.cpp
#include "main.h"
extern "C" void cudaTranslate(vec3 *x);
void display()
{
cudaTranslate(grid);
}
lineCuda.cu
#include <stdio.h>
#include <assert.h>
#in... | Move grid to main.cpp. Pass it to lineCuda.cu. Problem solved.
Updated:
main.h
typedef struct
{
float x;
float y;
float z;
}vec3;
const int sizeOfGrid = 20000;
main.cpp
#include "main.h"
vec3 *grid[sizeOfGrid];//assume initialized
extern "C" void cudaTranslate(vec3 *x);
void display()
{
cudaTranslate(g... |
5,131,332 | 5,131,603 | Why am I not getting a display in my Qt Widget? | When I run it it will just finish right away and not show anything. I can't find anything wrong w/it and no one on #qt could either. I've got other apps working fine so I'm not sure. It's got something to do with the createForm call, if I omit that call in the constructor I do get a default QWidget displayed.
captchit... | You need to initialize your private class members, probably in your constructor, before you use them.
Widget::Widget(QWidget* parent) :
QWidget(parent)
{
captchaImage = new QPixmap;
imageLabel = new QLabel(this);
statusLabel = new QLabel(this);
captchaLineEdit = new QLineEdit(this);
submitButt... |
5,131,567 | 5,131,592 | Why can't we create an instance of an abstract class? | I found in many places that :
An Abstract Class is a class which is supposed to be used as a base class.
An Abstract Class is a class which has atleast one Pure Virtual Function.
But one thing that always strikes my mind is why can't we create an instance of an abstract class? Many places on the Internet say there is... | Your void bar()=0; is not valid -- the =0 notation can only be used with virtual functions.
The whole point of an abstract class is that it's abstract -- you've defined an interface but not an implementation. Without an implementation, instantiating the class wouldn't produce a meaningful or useful result. If it does/w... |
5,131,647 | 5,131,654 | Why would we call cin.clear() and cin.ignore() after reading input? | Google Code University's C++ tutorial used to have this code:
// Description: Illustrate the use of cin to get input
// and how to recover from errors.
#include <iostream>
using namespace std;
int main()
{
int input_var = 0;
// Enter the do while loop and stay there until either
// a non-numeric is entered, or ... | The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the cod... |
5,131,691 | 5,131,701 | What is an unnamed type in C++? | As part of my toilet reading on the C++ Standard ANSI ISO IEC 14882 2003, I came across the following:
14.3.1.2: A local type, a type with no linkage, an unnamed type or a type
compounded from any of these types
shall not be used as a
template-argument for a template
type-parameter.
While I get what a local t... | "Unnamed type" really means "unnamed enumeration or class type" [for more information, see the comments to this answer]. An enumeration or class type doesn't have to have a name. For example:
struct { int i; } x; // x is of a type with no name
You could try to use an unnamed type as a template argument through argum... |
5,131,694 | 5,131,748 | loop never end ??~ need help. C++ | Quesition:
Given input like this:
int myintsA[]={1,3,3,2,2,5,5,5,4};
int myintsB[]={0,9,8,6,7,3,3,4};
Find same elements, out put it. When they appear both 2 times. out put it as 2 times.
For example:
Output:
{3,3,4}
#include <iostream>
#include <vector>
#include <list>
#include <ext/hash_map>
using namespac... | Here's a working version of the code posted from earlier:
#include <iostream>
#include <vector>
#include <list>
#include <algorithm> //It's better to use the standard <algorithm> header here for sort.
//using <ext/hash_map> just for the sort functionality is not a great idea because it makes the co... |
5,131,807 | 5,131,859 | Is MAXIMUM_WAIT_OBJECTS really 64? | MSDN says that
The maximum number of object handles is MAXIMUM_WAIT_OBJECTS
for WaitForMultipleObjects... On my computer that was defined as 64. Is it really only 64?
thanks
| Yes, that's really the value of that macro.
Whether that's really the maximum number of objects that the function is capable of waiting on at once is an internal implementation detail. But if I were writing that function, I'd check the given array length to make sure it was within the documented bounds before proceedin... |
5,131,907 | 5,132,167 | Create a file that uses 4-bit encoding to represent integers 0 -9 | How can I create a file that uses 4-bit encoding to represent integers 0-9 separated by a comma ('1111')? for example:
2,34,99 = 0010 1111 0011 0100 1111 1001 1001 => actually becomes without spaces
0010111100110100111110011001 = binary.txt
Therefore 0010111100110100111110011001 is what I see when I view the file ('bi... | The basic idea of your format (4 bits per decimal digit) is well known and called BCD (Binary Coded Decimal). But I doubt the use of 0xF as an encoding for a coma is something well established and even more supported by notepad.
Writing a program in C++ to do the encoding and decoding would be quite easy. The only di... |
5,132,219 | 5,132,376 | createmutex questions | Let's say I call
h=CreateMutex(NULL,FALSE,"full");
y=WaitForSingleObject(h,INFINITE);
//Read from a queue (critical section)
ReleaseMutex(h);
What issues can arise that can lead to an access violation reading a location?
For example is it possible for multiple threads to enter that critical section as the same time... | Although you're storing the results of those functions in variables, you're not reading them to determine whether the functions succeeded. Perhaps you didn't create or open the given mutex, so h is 0. Or perhaps instead of acquiring ownership of the mutex, the the wait failed. In either case, you should call GetLastErr... |
5,132,343 | 5,132,379 | How does behave linux buffer cache when an application is crashing down? | Let's say I am using c++ files stream asynchronously. I mean never using std::flush nor std::endl. My application writes a lot of data to a file and abruptly crashes down.
Is the data remaining in the cache system flushed to the disk, or discarded (and lost)?
| Complicating this problem is that there are multiple 'caches' in play.
C++ streams have their own internal buffering mechanism. Streams don't ask the OS to write to disk until either (a) you've sent enough data into the buffer that the streams library thinks the write wouldn't be wasted (b) you ask for a flush specific... |
5,132,496 | 5,136,021 | ActiveMQCPP connection.start() hangs up | I'm using ActiveMQ CPP 5.2.3 if it matters.
I have JMS producer that connects using failover transport to JMS network of brokers.
When I call connection->start() it hangs up (see AMQ-2114).
If I skip connection start() and call connection->createSession(), than this call is blocked too.
The requirement is that my appli... | This is normal when the connection is awaiting a transport to connect to the broker. The start method must send the client's id info to the broker before any other operation, so if no connection is present it must block. You can set some options on the failover transport like the startupMaxReconnectAttempts option to... |
5,132,579 | 5,132,595 | Why am I getting an access violation exception in a pointer operation? | I'm using C++ Visual Studio .Net 4.0 on Windows 7.0 x64. This happens just on the first loop of the while statement.
int main()
{
char *string = new char[11];
string = "characters\0";
toUppercase(string);
return 0;
}
void toUppercase(char *stringPtr)
{
while(*stringPtr != '\0')
{
if(*stringPtr >= 'a... | I suspect you're doing something like this:
toUppercase("test");
The problem is "test" is an array of const char, not char, so cannot be modified. However, due to a terribly stupid deprecated special conversion, a string literal can be treated as char* anyway.
(Your function also fails to test for toUppercase(0).)
|
5,132,683 | 5,133,054 | C++ compile time checker using templates | I am having following code which is taken from modern C++ design. While i am using it i am getting compiation error i think invalid sizeof opearand. Can any one point out what is the problem. Thanks!
template<bool>
struct CompileTimeChecker {
CompileTimeChecker(...);
};
template<>
struct CompileTimeChecker<false> ... | Like AProgrammer pointed out, the (void)sizeof isn't getting swallowed by the compiler. I suggest removing the parentheses from the sizeof, like this:
(void)sizeof CompileTimeChecker<(expr) != 0>((ERROR_##msg()));\
That seems to make g++ accept it, and interpret it the way it was probably meant to.
If that (void)sizeo... |
5,132,924 | 5,133,110 | Trying to create a vector of COORD, causes linking error | my code is:
#pragma once
#include "stdafx.h"
#include <vector>
#include "field.h"
class output
{
void putAtLocation(COORD, char chIcon); //currently this outputs to console
static std::vector<COORD> m_vsOutputBuffer;
public:
output(void);
static void addToken(COORD);
void drawTokens();
~outp... | you need this line in your .cpp file:
std::vector<COORD> output::m_vsOutputBuffer;
(Note the absence of static and the scope output::)
This is the actual definition of the member variable. What you have in the class (.h) is only the declaration.
Without this the static variable output:m_vsOutputBuffer does not exist ... |
5,132,939 | 5,133,069 | How to do AES decryption using OpenSSL | I'd like to use the OpenSSL library to decrypt some AES data. The code has access to the key. This project already uses libopenssl for something else, so I'd like to stick to this library.
I went looking directly into /usr/include/openssl/aes.h since the OpenSSL site is light on documentation. The only decrypt funct... | There's no size given because the block sizes for AES are fixed based on the key size; you've found the ECB mode implementation, which isn't suitable for direct use (except as a teaching tool).
ECB, CBC, CFB128, etc, are all short names for the modes of operation that are in common use. They have different properties, ... |
5,132,993 | 5,133,175 | Using C++ Macro with arguments into a linked piece of code | i have a macro that i use to speed up the implementation of Factory classes.
For example, to build a Factory for a CameraGenerator i use the macro this way:
GENERATOR_BUILD_FACTORY_START(CameraGenerator)
... do some stuff ...
GENERATOR_BUILD_FACTORY_END(CameraGenerator)
This bu... | Instead of GEN_NAMEFactory you need to use GEN_NAME##Factory inside of macro. Otherwise your code violates ODR rule (you define GEN_NAMEFactory in a different ways in two compilation units). This is causing a trouble only in debug, as only in debug the functions are not inlined, and only one of the two conflicting impl... |
5,133,034 | 5,133,045 | Why do i get linebreaks? | How can i make it in the same line?
It looks like:
You see a closed door.
It belongs to house 'Magician's Alley
5a'.
Nobody owns this house.
But I want it to look like:
You see a closed door. It belongs to house 'Magician's Alley 5a'. Nobody owns this house.
the code:
void House::updateDoorDescription()
{
std::stri... | Because you are doing
<< std::endl
This is endline and puts a linebreak. Remove these and it will be what you want to have.
|
5,133,050 | 5,133,404 | Dynamic programming approach to calculating Stirling's Number | int s_dynamic(int n,int k) {
int maxj = n-k;
int *arr = new int[maxj+1];
for (int i = 0; i <= maxj; ++i)
arr[i] = 1;
for (int i = 1; i <= k; ++i)
for(int j = 1; j <= maxj; ++j)
arr[j] += i*arr[j-1];
return arr[maxj];
}
Here's my attempt at determining Stirling number... | Found the bug.
You already computed your dynamic array of Stirlings numbers for k=1 (S(n,1)=1 for all n).
You should start computing S(n,2) - that is:
for (int i = 2; i <= k; ++i) //i=2, not 1
for(int j = 1; j <= maxj; ++j)
arr[j] += i*arr[j-1];
|
5,133,114 | 5,133,164 | Overloading logical operators considered bad practice? | Is it a bad idea to overload &&, || or comma operator and Why?
| I wouldn't overload operator&& or operator||. Even if you define a class that gives rise to a Boolean algebra (finite sets, for example), it would probably be a better choice to overload operator& and operator|.
The reason is that C++ programmers expect special semantics for operator&& and operator||: they are short-ci... |
5,133,265 | 5,133,315 | boost::format() output operator | I need to write the class which will accept boost::format() through the operator like cout does:
cout << boost::format("some string; some param = %d\n") % someValue;
Which type of operator's parameter must be?
So that the class will be declared like this:
class Output
{
Output& operator<<(... format);
}
int main()... | boost::format is the type you want. It has a str() member to get a std::string.
|
5,133,320 | 5,133,381 | How to use files in another Project in Visual Studio 2005? | I have a solution with two project in Visual Studio 2005. I want to use Project2's files in Project1. I included the head file and compiled it successfully. There comes the error LNK2019 when linking. However it runs well in project2 using the same file.
It is not about the obj path, cause I have tried move them to the... | If Project2 is a library, then all you have to do is link Project1 against Project2 by right-clicking Project1 -> Project dependencies and select Project2. If Project2 is not a library, then you must include the sources to Project1 as well, that is by clicking Project1->Add existing Items, and selecting the relevant cp... |
5,133,329 | 5,133,357 | what happen to my code? | I am new to C++. I am really confused between C and C++. I am familair with C and java, but not C++. Today I am going to write a linked list program using C++. But to what happened to my code ???
Thanks.
Raymond
the result:
Unhandled exception at 0x00412656 in 09550978d.exe: 0xC0000005: Access violation writi... | You should be using the new operator instead of malloc. See the difference here. Also why use structs and typedefs when c++ allows you to make a class
Here is my version of your code, its not bug free yet but it should illustrate how to use new and classes. I will try to fix it fully and update you.
Also note that with... |
5,133,378 | 5,133,477 | Template metaprogramming rules of thumb | What are the rules of thumb that should be considered whenever someone might use template metaprogramming to accomplish a goal? And what would be a good example where using template metaprogramming is much more efficient than plain old code other than libraries like boost?
| One very helpful rule I can think of is to have the a compilation error be thrown as close to the "true" problem as possible. That ways it's easier not only to deduce the issue but also easier for others who would use your library to deduce the issue.
Here's a contrived version of what I mean:
template<typename Type> ... |
5,133,675 | 5,133,796 | C++: Structs slower to access than basic variables? | I found some code that had "optimization" like this:
void somefunc(SomeStruct param){
float x = param.x; // param.x and x are both floats. supposedly this makes it faster access
float y = param.y;
float z = param.z;
}
And the comments said that it will make the variable access faster, but i've always thoug... | The usual rules for optimization (Michael A. Jackson) apply:
1. Don't do it.
2. (For experts only:) Don't do it yet.
That being said, let's assume it's the innermost loop that takes 80% of the time of a performance-critical application. Even then, I doubt you will ever see any difference. Let's use this piece of code ... |
5,133,732 | 5,133,737 | Cannot access base class' enum when inherit from a template parameter in C++ | I have a problem with the following code:
class SymmetryTypes
{
public:
enum Type { REAL, COMPLEX, INTEGER, PATTERN, UNINITIALIZED };
void f() { cout << "SymmetryTypes::f() invoked" << endl; };
};
template <class T>
class EnumBase : public T
{
public:
EnumBase() /* : t_(T::UNINITIALIZE... | T::Type is intended to refer to a type, so you need typename
typename T::Type t_;
If you omit typename, it thinks when it parses the template you are declaring a member whose name is T::Type (and then it errors out at t_ because there cannot be a second name afterwards). Remember it doesn't know at that point what T i... |
5,134,025 | 5,134,042 | boost::shared_ptr and assigning derived classes | Assume DerivedClass is derived from BaseClass
Would the following work?
boost::shared_ptr<BaseClass> a(new BaseClass());
boost::shared_ptr<DerivedClass> b(new DerivedClass());
a=b;
Following this question, I understand that now a points to the derived and b points to the base (right?)
Also, now if I call a function vi... | ...
a=b;
You are reassigning to a and therefore a and b would now both point to the DerivedClass object. The BaseClass object would be destroyed, since its reference count would be zero at this point (by virtue of a being reasigned to point to a different object).
Since a now points to a DerivedClass object, virtual ... |
5,134,077 | 5,134,111 | Is the C part of the C++ library automatically C99? | Are all the functions in a conformant C++98/03/0x implementation completely C99 conformant?
I thought C++0x added some C99 (language) features, but never heard or read anything definitive about the C library functions.
Just to avoid any confusion, I'm talking about a C++ program using functions declared in the <c*> hea... | Most of the C99 standard library has been imported in C++0X but not all. From memory, in what wasn't imported there are
<ctgmath> simply includes <ccomplex> and <cmath>,
<ccomplex> behaves as if it included <complex>
<cmath> has quite a few adjustment (providing overload and template functions completing the C99 pro... |
5,134,217 | 5,134,913 | Aligning data on the stack (C++) | This question is specific to the MSVC compiler (specifically 2008), but I'm interested in non-compiler specific answers too.
I'm trying to figure out how to align a char buffer on the stack, based on the alignment of some arbitrary type. Ideally the code would read:
__declspec( align( __alignof(MyType) ) ) char buffer[... | Update
Check Robert Knight's answer! Uses C++11 but is much cleaner than this...
Original Answer
How about this nasty hack:
namespace priv {
#define PRIVATE_STATICMEM(_A_) \
template <size_t size> \
struct StaticMem<size,_A_> { \
__declspec(align(_A_)) char data[size]; \
void *operator new(size_t ... |
5,134,278 | 5,134,330 | LINKED LIST question C++ ...Can we make TWO different node types in one program? | I have another project to finish off regarding linked lists.
I wanted to know if it was possible to write in TWO struct nodetype codes to create two nodes.
If so how and where should I place them?
My code is going to contain of one node type with "Videos" in a list.
And another node type with "Customer" details in a li... | Because an instantiation of a class template yields a new type, you can make your list node a template:
template<class Tag>
struct ListNode
{
ListNode *prev, *next;
};
And then derive multiple times from the same template instantiating it with a different tag type:
struct VideoTag;
struct CustomerTag;
struct Item... |
5,134,287 | 5,139,128 | Embedded Lua - timing out rogue scripts (e.g. infinite loop) - an example anyone? | I have embedded Lua in a C++ application. I need to be able to kill rogue (i.e. badly written scripts) from hogging resources.
I know I will not be able to cater for EVERY type of condition that causes a script to run indefinitely, so for now, I am only looking at the straightforward Lua side (i.e. scripting side probl... | You need to address this with a combination of techniques. First, you need to establish a suitable sandbox for the untrusted scripts, with an environment that provides only those global variables and functions that are safe and needed. Second, you need to provide for limitations on memory and CPU usage. Third, you need... |
5,134,297 | 5,186,291 | Xlib How Does This (Removing Window Decoration) Work? | How does the following code remove window borders?
//note the struct is declared elsewhere, is here just for clarity.
//code is from [http://tonyobryan.com/index.php?article=9][1]
typedef struct Hints
{
unsigned long flags;
unsigned long functions;
unsigned long decorations;
long inputM... | It's hard to come by any sort of "official"-looking standard or such, but the
_MOTIF_WM_HINTS property does seem to come from the... Motif toolkit (ok, you
guessed that :-) ).
See the MotifZone site.
Warning: what follows is incomplete, but should shed some light I hope.
Documentation for the XmNmwmDecorations, XmNmwmF... |
5,134,357 | 5,134,373 | how to include header files in other src folder | I have a c++ project having two src folders. Source file in folder 1 may need to include header file in src folder 2. Is it possible? or how should I write my Makefiles? thanks
| Depending on how closely the two folders are related (eg, if they're the same project), then it can be as easy as:
#include "../otherfolder/header.h"
If they're separate projects, then it's customary to simply add the other project's header directory to your project's header search path, and include the header like th... |
5,134,454 | 5,346,715 | Use VirtualProtect to mark pages as copy-on-write (poor-man's fork on windows) | I use VirtualAlloc(Ex) to allocate and commit a large range of pages.
Later in the execution I wish to "fork" that memory, launch a new process that can read it in it's current state, while the parent process treats it as copy-on-write memory.
Can this be done with VirtualAlloc(Ex) and VirtualProtect(Ex)?
This is trivi... | I don't believe any of these quite answer the question posed by the original poster. Perhaps I might venture the following example. Suppose one has some data in "bufferA" and one copies it to "bufferB" and then modifies both buffers. Now one examines both buffers, and decides to copy either "bufferA" or "bufferB" to... |
5,134,479 | 5,134,532 | Is it possible to set pre-processor conditions within a macro? | I'm in a position where this design would greatly improve the clarity and maintenance-needs for my code.
What I'm looking for is something like this:
#define MY_MACRO(arg) #if (arg)>0 cout<<((arg)*5.0)<<endl; #else cout<<((arg)/5.0)<<endl; #endif
The idea here:
The pre-processor substitutes different lines of code dep... | As far as I know, you cannot have #if (or anything similar) inside your macro.
However, if the condition is known at compile-time, you can safetly use a normal if statement. The compiler will optimise it (assuming you have optimisions turned on).
It's called "Dead code elimination"
|
5,134,599 | 5,134,646 | Subclasses as arguments? | I am attempting to create something like this:
class food
{
public:
void EAT(); //Whatever happens...
int bitesLeft //This is decreased by one each time you eat the food
};
class cheese: public food
{
public:
void EAT(); //Some overloaded form of the "eat" command...
};
Is there a way to create one of each ... | Yes, there is:
void myfunc(food* f)
{
f->EAT();
}
int main()
{
food f;
cheese c;
myfunc(&f);
myfunc(&c);
return 0;
}
However, for this to work, you need to declare EAT() as virtual in the food class, as in virtual void EAT();. Also, you probably want to declare bitesLeft as protected, so that ... |
5,134,614 | 5,134,691 | Const map element access | I tried to use the operator[] access the element in a const map, but this method failed. I also tried to use at() to do the same thing. It worked this time. However, I could not find any reference about using at() to access element in a const map. Is at() a newly added function in map? Where can I find more info about ... | at() is a new method for std::map in C++11.
Rather than insert a new default constructed element as operator[] does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)
Because of this behaviour it makes sense for ther... |
5,134,641 | 5,134,705 | expected nested-name-specifier error in C++ | I've written classes to implement a tree ADT that stores two sets one of edges and one of nodes. it stores them is SSet classes, which are an interface to use the set library.
The outlines of the classes as well as SSet.H were given to us by the staff and I wrote the functions.
line number 103 (function GenGraphTemp::R... | // Removes an edge from edges set
bool RemoveEdge (const typename NodeEdge& e1) {return _edges.Remove(e1);}
// Check if two nodes are connected
bool RConnected const (const Node& n1, const Node& n2) {
make
// Removes an edge from edges set
bool RemoveEdge (const NodeEdge& e1) {return _edges.Remove(e1);}
// Check if ... |
5,134,717 | 5,136,735 | "Empty" rendering with openGL | specs: Radeon 3870HD w/ openGL 3.3 & GLSL 1.5
I am rendering data through computational shader. Because of dependencies I had to put all my data to uniform textures and nothing left for attributes. Only value that change per primitve is index and I can get this one from gl_VertexID. But I'm having problem with setting ... | I had the same issue with ATI. In order to bypass it I'm using any accessible buffer for a dummy 1-byte per vertex input array (not used by the shader).
|
5,134,871 | 5,134,926 | Type traits doesn't work | This:
cout << std::is_const<const int*>::value;
prints out false and I'd think that it should print true. Why does it print false?
| As others have mentioned, what you have is a non-const pointer to a const int. You are asking if the pointer is const, and it isn't, it can be changed. It just points to something which is const. If you want to know if the pointed-to type is const, something like this should work:
std::is_const<std::iterator_traits<con... |
5,135,100 | 5,135,459 | Segmentation fault in overloaded operator>> | I'm trying to write code for an orthogonal linked sparse matrix.
Here's the question:
An alternative linked representation for sparse matrices uses nodes that have the fields down, right, row, col, and value. Each non-zero entry of the sparse matrix is represented
by a node. The zero terms are not explicitly stored. ... | I think your issue is with currentNode. You shouldn't need it as a class variable, and instead you should create a new one each time you read input from the stream. For example,
istream& operator>>(istream& in, OrthogonalLinkedSparseMatrix& x)
{
in >> x.numRows >> x.numCols >> x.numTerms;
int inRow, inCol, i... |
5,135,108 | 5,135,126 | to compile a library from multiple sources | I want to build a library from multiple source files, like a1.cpp a2.cpp. I used the following command, 'g++ -o libcode -c a1.cpp a2.cpp'. However, error pop up "cannot specify -o with -c or -S with multiple files".
In general, how should I build such lib from multiple sources? thanks...
| You first compile your source files to objects files (*.o), and then invoke the ar command to build the library. In your example:
g++ -c a1.cpp a2.cpp
ar rcs libcode.a a1.o a2.o
This would build a static library, you can also create a dynamic one.
http://www.network-theory.co.uk/docs/gccintro/gccintro_79.html
ht... |
5,135,123 | 5,135,258 | no suitable constructor exists to convert from "uint8_t *" to "std::vector<uint8_t, std::allocator<uint8_t>>" | no suitable constructor exists to convert from "uint8_t *" to "std::vector<uint8_t, std::allocator<uint8_t>>"
and the cast not working
Edit:
const std::vector<uint8_t> Test (const std::vector<uint8_t> buffer) const;
uint8_t* buffer="...";
//so i can use Test() function
Test(buffer);
Error
no suitable constructor e... | You cannot convert an array to a std::vector, you need to construct one explicitly.
One way to do it would be to use the vector's range constructor like this:
uint8_t* buffer="...";
// +1 for the terminating \0
std::vector<uint8_t> vector( buffer, buffer + strlen( buffer ) + 1 );
Test( vector );
As a side note if yo... |
5,135,198 | 5,135,215 | Why can't I call an function in an anonymous namespace from within another function? | I have written this piece of code:
namespace {
void SkipWhiteSpace(const char *&s) {
if (IsWhiteSpace(*s)) {
s++;
}
}
bool IsWhiteSpace(char c) {
return c == ' ' || c == '\t' || c == '\n';
}
} // namespace
The problem is that the compiler complains that IsWhiteSpace() was not declared in this scope. But w... | Perhaps it's because you're defining IsWhiteSpace after SkipWhiteSpace.
Edit:
I successfully compiled the following code:
#include <iostream>
using namespace std;
namespace
{
void Function2()
{
cout << "Hello, world!" << endl;
}
void Function1()
{
Function2();
}
}
int main()
... |
5,135,216 | 5,135,238 | <algorithm> sort custom condition | Okay, so I've tried to use sort to vector of items so the size of two adjecant items is <= 2d.
So here's my attempt:
struct item{
long number;
long size;
};
// d is global variable.
bool check(const item& x, const item& y)
{
return ((x.size + y.size) <= (2 * d));
}
// Items is a vector of item.
sort(items... |
it's even impossible to sort using condition like that ?
No. The comparer in sort must satisfy the criteria of a strict weak ordering which yours clearly doesn’t (for instance it’s not irreflexive).
|
5,135,291 | 5,135,322 | Is using string.length() in loop efficient? | For example, assuming a string s is this:
for(int x = 0; x < s.length(); x++)
better than this?:
int length = s.length();
for(int x = 0; x < length; x++)
Thanks,
Joel
| In general, you should avoid function calls in the condition part of a loop, if the result does not change during the iteration.
The canonical form is therefore:
for (std::size_t x = 0, length = s.length(); x != length; ++x);
Note 3 things here:
The initialization can initialize more than one variable
The condition i... |
5,135,373 | 5,135,714 | How should I extracted this url get string | How should I extract a URL for example "action=add&var1=5&var2=6" into
QString action;
QVector<QStringList> vars;
efficiently?
I am using apache, c++ cgi and the QT libary. Ask for more detail if needed.
| Use the QUrl class that comes with Qt. Set it to the url and then use allEncodedQueryItemValues to get the pairs.
|
5,135,423 | 5,135,436 | Any ways to improve this implementation (significantly)? | This is a piece of code I've written for a homework. It seems to work but I wonder if I missed something.
The task was to implement a function (here: Countwords) which counts all words in a char *. No library functions should be used.
namespace {
bool IsPrintable(char c) {
return c >= '!' && c <= '~';
}
void SkipPr... | You solve this in linear complexity. One cannot do the same in less complexity. So you cannot significantly improve your algorithm.
|
5,135,651 | 5,135,737 | type signature of an enable_if'ed templated template constructor? | I usually declare my classes and templates, and then define their methods after (in the same header file, of course). I just find it easier to read that way. Well, I've come across a case where I can't figure out a working type signature to use in an out-of-class definition. Here's a simplified example of what I'm doin... | I wouldn't do it that way. Here's the changes I would make:
template <class T>
struct Foo
{
Foo(T a, T b);
template
< class Iterator
>
Foo
( Iterator first
, Iterator last
, typename enable_if<is_iterator<Iterator> >::type* = 0
);
};
template <class T>
Foo<T>::Foo... |
5,135,707 | 5,135,833 | Interrupting a method but continue executing the remainer of the code | I want to run a section of my code but with the option to interrupt it (ctrl-c) before it is completely done and resume executing the rest of my code. (I am working on a Linux platform.)
My guess is to create fork, call the method, and then use signal handling. What steps are needed for the signal handling?
void Mana... | Depending on the function you wish to interrupt, this might be implemented without forking.
If the function doing its processing in a loop, the signal handler can set a boolean indicating you want processing to stop. The loop can just check this boolean and the function can exit safely and in a consistent sate once it'... |
5,135,734 | 5,136,535 | What's the difference in GCC between -std=gnu++0x and -std=c++0x and which one should be used? | I'm having troubles with <stdint.h> when using -std=c++0x in GCC 4.4.3 (for Android):
// using -std=c++0x
#include <stdint.h>
uint64_t value; // error: 'uint64_t' does not name a type
But using -std=gnu++0x works:
// using -std=gnu++0x
#include <stdint.h>
uint64_t value; // OK
Is <stdint.h> incompatible with C++0x?... | So far as I can tell, I think this could be argued an implementation bug (or actually, since C++0x isn't published, not a bug per se but an incomplete implementation of the current state of the upcoming standard).
Here's why, referring to n3225 for the expected behavior of -std=c++0x:
D.7 says
Every C header, each of... |
5,135,779 | 5,135,808 | Reading from and Writing to a processes I/O? | Suppose we have two programs, A and B. B prints something continuously and reads input too. (probably there are two processes in B using same I/O, I don't know if it is possible or not...)
A have to read B's output and decide about what to say to B, then sends a string to B's input. (just like that someone inputs text ... | You can use the unofficial boost Process library, which has an excellent tutorial of exactly what you want to do and is bound to be an official part of boost any time now. It's also naturally cross-platform. HTH
|
5,135,854 | 5,135,920 | Make a file pointer read/write to an in-memory location | I can make a file pointer write to a file with fopen(). But can I make a file pointer that will make it so calling functions such as fputc or fprintf will write to a pointer in memory? An example of this is ByteArrayOutputStream in java. Also: could I run it in reverse, where a library needs a file pointer to read from... | If your operating system provides fmemopen,
probably it will meet your purpose.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.