spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » C++ » Page 22
Make tree from mathematical expression by std::regex
As stated by n.m., regular expressions can't deal with nested parentheses. However there are simple alternatives that can parse nested parenthesis, such as recursive descent parsers. Example: enum TokenType { TTId, TTNumber, TTPlus, TTMinus, TTTimes, TTDivide, TTLParen, TTRParen, TTEndOfInput }; TokenType token = TTEndOfInput; string tokenValue; int peekChar(

Categories : C++

Unable to Fix a Linker Error in C++
Those linker errors mean that you have not provided the definition of those three functions. i.e constructor, destructor and Load function... CPictureCtrl(void); ~CPictureCtrl(void); BOOL Load(CString &szFilePath);

Categories : C++

Given the coordinates how to find if they make a rectangle using C++ programms?
check this clever solution from this link find the center of mass of corner points: cx=(x1+x2+x3+x4)/4, cy=(y1+y2+y3+y4)/4 test if square of distances from center of mass to all 4 corners are equal bool isRectangle(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { double cx,cy;

Categories : C++

Qt TabWidget Tab rename in runtime
If you want to capture the event when you double click on tab bar, you should install the event filter on the QTabBar of the tab widget. But QTabWidget::tabBar() is protected and you can not access it. The solution is to derive a class from QTabWidget and implement a public function which returns a pointer to QTabBar : #include <QTabBar> #include <QTabWidget> class customTab: public

Categories : C++

how can i read last line of file
The main change to your code: Replace while (myfile) { getline (myfile,line); cout << line<<endl; new1=line; } by while (getline (myfile,line)) { cout << line<<endl; new1=line; } The reason the first one does not work is that after you have finished reading the last line, while (myfile) continues to evaluate to while(true). At tha

Categories : C++

How do I unload code from a Lua context
If by unload you mean undo the effects of running some Lua code, then it cannot be done unless you save the state of what is precious before running the code. This can be done by sandboxing the code. If you just want to remove a Lua table, set to nil all references to it and let the table be garbage collected automatically or manually.

Categories : C++

perfect singleton design pattern
There is no perfect singleton. In fact, it's open to some question whether there's any singleton that's worth anything at all. That said, in C++ the Meyers Singleton is usually the one that's least problematic. The core of it looks roughly like this: static T &get_instance() { static T t; return t; } So the basic idea is to define a single instance of the target type as a stat

Categories : C++

What is the Replacement Method for CCArray in Cocos2dx 3.3?
in .h file declare the array using vector cocos2d::Vector<cocos2d::Sprite *>objectArray; in .m file use below code to addobject objectArray.pushBack(sprite); and for use either use for or at for the perticuler access object objectArray.at(2); for(auto str: objectArray) { Sprite *sprite21 = dynamic_cast<Sprite *>(str); }

Categories : C++

When is a type in c++11 allowed to be memcpyed?
What I understood is An Object should have default constructor /destructor. Default Copy and Move Operations. No static and Virtual Functions has multiple access specifiers for non-static data members prevents important layout optimizations has a non-static member or a base that is not standard layout. you can test if given type is pod (Plain Old Data) by using standard function is_pod::value

Categories : C++

render depth buffer to texture using glCopyTexSubImage2D
If your texture turns out all white, it is indeed being rendered correctly. The problem, I think, is due to the setting of the far and near planes in your projection matrix. The depth buffer isn't linear, and if your near plane is very close, like 0.1 and your far plane far like 500.0 then a lot of the possible depth values are VERY close to your near plane. It's better to set your near plane to

Categories : C++

Is the lvalue reference return of a member function of a temporary object a dangling reference?
Yes, kk is a dangling reference and pp is a dangling pointer. The temporary produced by CBase() only exists for the duration of the full expression in which it appears. Note that it is still valid to have a pointer or reference refer to this object, as long as their lifetime is bound to the expression as well. Since kk and pp still exist after the full expression, this is not the case. Using kk a

Categories : C++

Calling different functions based on type
A straightforward way to do what you want uses output parameters: template<typename T> bool FetchVal(T & fetchedData) { // Get data from some function dataAsString = Get(); Convert(dataAsString, fetchedData); } then, just have as many implementations of Convert as you need.

Categories : C++

Nested vectors in Linux
You are blaming linux for your minor mistake... virtual vector<vector<Element>> decompose(vector<Element> p) = 0; This should be :- virtual vector<vector<Element> > decompose(vector<Element> p) = 0; >> should be separated > >

Categories : C++

Searching for structures in a continuous, unstructured file stream
If you are running in a 64 bit environment, I would just use memory mapped files. There is no (reasonable) memory limit for a process. You can read the file in, even jump around, and the OS will swap memory to and from disk. Here's some basic information: http://msdn.microsoft.com/en-us/library/ms810613.aspx And an example of a file viewer here: http://www.catch22.net/tuts/memory-techniques-pa

Categories : C++

Do I need to use memory barriers to protect a shared resource?
At least in C++11 (or later), you don't need to (explicitly) protect your variable with a mutex or memory barriers. You can use std::atomic to create an atomic variable. Changes to that variable are guaranteed to propagate across threads. std::atomic<int> a; // thread 1: a = 1; // thread 2 (later): std::cout << a; // shows `a` has the value 1. Of course, there's a little more

Categories : C++

Why is an external pointer to a string literal lost when leaving scope? (C++)
In this case a temporary string object would be constructed to store "Hello". And then this temporary is bound to string object s. void Enqueue (const std::string &s) That means life time of temporary is extended to the scope of string s.However when this function exits, s will be destroyed. So, in ProcessEvent that string has long gone.

Categories : C++

What is difference between Application Buffer and System Buffer
In the context of MPI, application buffer (often called user buffer) is the buffer that holds information to be sent or the place where information is to be received. Applications buffers are what one passes to MPI communication calls, e.g. MPI_Send(buf, len, type, ...); // ^^^ // app. buffer Once MPI_Send is called, a message is constructed and depending on various criteria is either

Categories : C++

Specify port number in TCP client socket
Say the client socket is going to have two connections with the same server, and the second connection should use the same local(client side) port number to connect. Not possible. Something about the tuple {source IP, source port, target IP, target port} has to be unique, to identify the connection. What actual problem are you trying to solve?

Categories : C++

How to expand & stringify such macro?
No, there is no way to get a preprocessor macro to evaluate an arithmetic expression. You can get the preprocessor to do arithmetic evaluate, but only in the context of #if, which allows you to evaluate a boolean expression. You can use that feature to rather laboriously output a number, but only by using preprocessor input in #included files, since you cannot put #if inside a macro. You don't m

Categories : C++

How can I find the highest and lowest values in this array?
Wouldn't you just keep a local variable with the max and min value seen? You are walking through all the items entered anyway? ` float max=0; float min=999; for (int i = 1; i <= days; i++) { cout << "Enter the temperature for day number " << i << ": "; cin >> temperatures[50]; temptotal += temperatures[50]; if temperatures[50] > max max = te

Categories : C++

Overloading friend operator method in template class
Your error is using friend, which changes the function from a member-function to an inline-defined friend-function. operator= can only be defined as a non-static member-function, and needs two arguments, the implicit this and the explicit right-hand-side.

Categories : C++

C++ Error: Undefined Symbol
The compiler is telling you that the definition doesn't match the implementation. In this case the parameter types don't match. Your definition: void putWord(ostream &Outfile,string word, char space); Your implementation: void putWord(ofstream &Outfile,string word, char c) { /* etc */ } Since ostream and ofstream are different types, that's not going to compile.

Categories : C++

The size of base class object and derived class object in C++
For the size of Base1 class, it should contain a vptr points to the vtable and an integer data1. Why its size is 16 while sizeof(int) is 4 in my machine. Padding to ensure proper alignment of the 8-byte pointers when Base1s are in a necessarily-contiguous† array. † the C++ Standard requires that array elements be contiguous in memory, and calculates the memory address of an element at in

Categories : C++

Tic tac toe game code
This piece of code will go out of bounds: bool isMoveLegal(int board[3][3], int row, int column){ if (row >= 0 && row <= 3 && column <= 3 && column >= 0) { if (board[row][column] == 0) return true; else return false; } Remember that arrays are 0-indexed, so it should be: bool isMoveLegal(int board[3][3], int row, int column){ if (row >

Categories : C++

C++: Global variable vs local variables. What to use?
Although there are always exceptions, I usually go by (among others :-) the following guidelines: Avoid globals as much as possible. Confine to smallest applicable scope (within reason). Avoid second guessing the compiler, except for grossly obvious situations.

Categories : C++

C++ How to correctly round a const float to unsigned int
Just add one half to round: unsigned int i = static_cast<unsigned int>(f + 0.5); Or nothing to truncate - what you have is fine (assuming f >= 0) unsigned int i = static_cast<unsigned int>(f);

Categories : C++

C++ Server socket with multiple connections
That's because you're deleting your thread as soon as you create it. You need to save them somewhere: std::vector<std::unique_ptr<std::thread>> threads; for (;;) { // as before threads.emplace_back(new std::thread((ClientHandler()), Connect)); }

Categories : C++

Interfacing with gnuplot in c++ using popen?
You didn't escape your strings properly. Try: fprintf(gnuplot,"set output "plot.ps" "); You can't have "s within a string by themselfes or it'll end the string.

Categories : C++

c++ inline function example
inline has nothing whatsoever to do with the behavior of the function. The only thing it is required to do is alter the behavior of the linker, specifically to cause the linker to allow the same symbol to be defined in multiple translation units. inline never affects a program's observed behavior1, only whether or not it might link successfully. In the past it was also used as a hint to the compi

Categories : C++

Parsing key/value pairs from a string in C++
Do you care about performance or readability? If readability is good enough, then pick your favorite version of split from this question and away we go: std::map<std::string, std::string> tag_map; for (const std::string& tag : split(input, ';')) { auto key_val = split(input, '='); tag_map.insert(std::make_pair(key_val[0], key_val[1])); } S s{std::stoi(tag_map["top"]), std

Categories : C++

compiling with local copy of gcc, incompatible libstdc++
I got it working, so I figured I should post what I did. Compiling with -I$(HOME)/include -L$(HOME)/lib -lblas -llapack -lgsl -lglsblas -O3 -std=c++11 seemed to do the trick. Wish I knew exactly what fixed the problem, but I hope this helps.

Categories : C++

Changing values in a namespace
You mentioned static, so I'm assuming you have these constants included in multiple files as static const double a = .... The easiest and simplest way I can think of that doesn't involve you touching other parts of your code is changing the constants to not be static const but rather to extern and then you can have another source file that contains them and exposes a function to set them up. Ex

Categories : C++

C++ template print object name
You'd need to add a member variable that held the objects name. I'm going to assume that you'd want to make that a const member variable. If so you'd do something like this: #define CREATE_MYTEMP(x) mytemp<void> (x){#x} template <class T> class mytemp { private: string _name; public: mytemp(){} mytemp(string name) : _name(name){} void print_name() const {

Categories : C++

C++ compiler parse the templates before instantiation? why?
It appears to me C++ compiler parses the templates even before it is instantiated. That's its job. It's a compiler, not a macro processor. if compiler parse the template definition only when it is instantiated, I don't think there is ambiguity for interpreting One problem with that is that errors in the template itself won't be detected as long as it is only instantiated with 'friendly'

Categories : C++

C++ finding the min location, sort, and swap in a 2D array
The easiest way to iterate over a (so-called) 2D array is to use two nested loops: for(unsigned int j=0; j<numRows; ++j) for(unsigned int k=0; k<numColumns; ++k) ... do something with A[j][k] ...

Categories : C++

C++ Using an enum data type as a data type for a constructor in a class file
I make you notice that RankType is just the type (name) of the enum. You have created an enum inside your class, but you have no variable of type RankType (unless you are not showing us). You are returning a type, what do you think return Card.RankType; means? I recommend you to define the enum outside the class, and if you want to initialise your card to a certain RankType, you can do it, for e

Categories : C++

Unresolved External Symbol Errors when using header and class definition files
First and most important: do not write this much code before testing any of it. Start small and simple, get something to work perfectly (even if it does nothing), add complexity a little at a time, test at every step and never add to code that doesn't work. More specifically, look at your variable custTax. You declare it in in RestaurantCheck.h as a static member variable, but then define it inco

Categories : C++

Creating users for game(reading and parsing CSV file)
Look up the code to an available "csv parser" which stands for "comma separated variable". You need is almost identical, except you use a semi-colon instead of a comma. It seems that by changing one character you parsing is done for you. You may be able to find a csv parser that accepts the character to be used as the parsing character (I've seen them before). If you wish I can find a suitable

Categories : C++

Precision when converting a string decimal number
Turns out that it is converting correctly, but, when asked to cout the number, it only gives 3-4 decimal places. Anyone know why? #include <iostream> #include <stdlib.h> #include <iomanip> using namespace std; int main() { string data1 = "138.6470184568"; string data2 = "138.6470184568"; double data3 = atof(data1.c_str()) + atof(data2.c_str()); cout << data3

Categories : C++


Recently Add
Returning the actual value of maximum of absolutes of variables
Microsoft c++ optimizing compiler has stopped working
Overloading operator[] changing value
what does the printf/snprintf format character %N do? (not %n)
Eigen and C++11 type inference fails for Cholesky of matrix product
Qt KeyPress Event on QlineEdit
Any reasons to look at alternatives to inheritance / polymorphism?
Cannot cast the structure pointer to char pointer in c++
Changing a C/++ OpenCV program to CUDA from video stabilization program
c++ change of coordinates (Pixels 1920 x 1080 to 640 x 480)
WinAPI SetSystemCursor and LoadCursorFrom - how to set default cursor?
Multiple clients in c++ server
avoid specifying redundant template parameters which contain templated function pointer
How to obtain mp3 audio packets for streaming in C/C++
How do I search for an element from each node in C++ using queue?
Difference between private static members and having them in the cpp file
Is the size of built-in datatypes in c++ managed on source code level?
Deleting elements dequeued using "top" from priority_queue c++
C++ Ordering the names of a scoreboard
QColor hsl hue precision
cannot read the text file properly anymore
g++ 4.8.* std::chrono Undeclared
How can I make a 'const tm*' from a 'const tm&'?
Can clang-format align variable or macro assignments in columns?
Obtaining First and Last Charsof Each String From A Vector of Strings
boost filesystem canonical path is not valid after conversion to const char *
SIGSEGV, Segmentation fault
Is there a way to detect if a primitive argument is variable size?
why can I pass a reference as an argument to a constructor's pointer parameter?
Which compiler flag am I missing in my build on the so file?
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.