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
62,113,098
62,113,590
Why we actually need runtime polymorphism?
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class. Like, suppose this was a problem. #include <bits/stdc++.h> using namespace std; class base{ public: virtual void fun(){ cout<<"base ca...
Polymorphism is useful any time that the software can't be told at compile time exactly what everything is going to be at runtime, or when you need a container to be able to hold a heterogeneous assortment of things that all implement a common interface. A good example is UI toolkits. Pretty much all UI toolkits have ...
62,113,549
62,113,632
Creating a C++ object with and without new keyword
Creating an object with new keyword: #include <iostream> #include <string> using namespace std; class Person { private: string name; public: Person(string name) { setName(name); } string getName() { return this->name; } void setName(string name) { this->name = name; } }; int main() {...
Let's see what's going on in the background. First case While using new keyword, new created an object and returned a pointer to that object. +--------------------------+ person1 ----------> | Person Object | | name = Rajat | ...
62,114,031
62,118,683
How to write a platform independent wrapper function in C++
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application. As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac) To support for multiple platforms, I am planning to write a wrapper function with #if tags. bu...
I would not write it like that: void WrapperSprintf( char buffer, const char *format, ... ) { #if defined(_WIN32) _snprintf_s(buffer, sizeof(buffer), format,...); #else snprintf(buffer, sizeof(buffer), format, ...); #endif } You don't need a function here. What you want is to select the correct function. Rat...
62,114,077
62,114,149
Details about the specification of the function "strcpy'' and possible solution
I want to copy string from the line into strs #include<iostream> #include<fstream> #include<string.h> using namespace std; #define N 100 void readAndWrite(); int main() { readAndWrite(); return 0; } void readAndWrite() { fstream in; char* strs[100]; for (int i = 0; i < N; i++) { strs[i] =...
You forgot to check the return value of calloc, that's why the compiler is telling you it might be zero (null), in case there is insufficient memory available to allocate.
62,114,096
62,114,267
How do I populate an array in C++?
Okay so I have a textfile with only 2 lines of doubles that are comma separated. This will always be the case. Each line will have to go into its own separate array of type double where I will later have to use a linear search to find one array in the other. example of the textfile: 2.5,6.7,3.4,7,6.7,6,4,5,83.6 6.4,7,8...
few things - one try not to use using namespace std second - you check inputfile.good() only relevant after reading third - you need an index to run over the array so I added the I that increment with the loop, But I didn't check if it counts more then thy array length so if it relevet add a check for that to. #i...
62,114,100
62,114,457
Randomizer picks a number from the vector and delete it
So, program picks this number from the vector, it's actually a sequence {1...n} and I want to print out and delete random number from it. However, everytime program prints out {n...1} sequence. Example: Vector(1,2,3,4,5) => program picks random number 4 => Vector(1,2,3,5) => random number 1 => Vector(2,3,5) and until ...
The problem is in your for loop. Even if it finds that a number eg. 1 is present in [1 2 3 4 5] and sets inVector = 1 it will carry on and check next numbers in the nums and set eventually inVector = 0 unless it's the last number. You have to terminate the loop just when the condition is met eg. if (choice == nums[i]...
62,114,321
62,114,626
Draw a object comparing two different values of stencil buffer
First draw Geometry_A and write to stencil buffer with the following value. glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP); // replace stencil buffer values to ref=1 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glStencilFunc(GL_NEVER, 1, 0xFF); // never pass stencil test glStencilMask(0xFF); Draw Geometry_A Draw G...
Can we draw a geometry comparing both the values of stencil buffer from Geometry_A and Geometry_B Yes of course, just set a bit in the stencil buffer, instead of changing all bits. Set the bit mask 0x01 for geometry Geometry_A glStencilFunc(GL_NEVER, 1, 0xFF); // never pass stencil test glStencilMask(0x01); Set th...
62,114,423
62,114,562
Why am I getting a compilation error in a C++ factorial function?
I am trying to write a simple factorial function in C++ by using the ternary operator. It gives a compilation error. int factorial(int n) { (n == 0) ? return 1 : return n * factorial(n-1); } It says Expected ':' to match this '?' I am new to C++.
?: is an ternary operator that takes three expressions and evaluates them in some way to produce a result. return 0 in your case is not an expression but it's a statement, so your syntax doesn't work and gives error. It cannot be used where a value is expected. The correct code and it's syntax should be as follows : in...
62,115,279
62,116,030
Base of Global Call Stack in C/C++
I have read that each function invocation leads to pushing of a stack frame in the global call stack and once the function call is completed the call stack is popped off and the control passes to the address that we get from the popped of stack frame. If a called function calls on to yet another function, it will push ...
First of all, there is no such thing as a "global call stack". Each thread has a stack, and the stack for the main thread is often looking quite different from the thread of any thread spawned later on. And mostly, each of these "stacks" is just an arbitrary memory segment currently declared to be used as such, sub-all...
62,115,330
62,119,950
C++ - How to bind a callback to a class method without being static?
I have my class: class Foo { public: (...) private: void mycallback(void* buff, wifi_promiscuous_pkt_type_t type); void registerMyCallback(); }; The mycallback is the callback. I want to use a method esp_wifi_set_promiscuous_rx_cb to register the mycallback so that when a WiFi packet is detected,...
Th library you are using is C package. Thus the only guaranteed way pass a valid function is to pass a C function with C linkage. This function can then call the method on your object. If you want the callback method to be non static you need to store a pointer (ore reference) to the callback object somewhere that your...
62,115,861
62,134,783
How to benchmark custom interface using google benchmark
since I can't find really good resource or documentation besides what's on the github readme, I'll ask the community here. Assuming that I have an interface called Base, and multiple derived types. I want to benchmark a virtual function Foo of all derived types with the same function and the same argument passed to Foo...
Your approach is pretty much correct. If you want to avoid the multiple benchmark functions, move the core of the benchmark to a separate function and call it from each of the per-type ones. Something like: static void Benchmark(Base* b, benchmark::State& st) { for (auto _ : state) { b->DoTheThing() } } void ...
62,115,979
62,123,516
How to implement better error messages for flex/bison
I need to have proper error messages for syntax errors for a grammar I'm writing. I've figured out that I can define a rule (? not sure about the terminology) for newlines in the flex file that increments a line-number counter, and I can use that in yyerror(const char*). However, I also need to know the exact position ...
Output Unexpected and Expected Tokens Just with using #define YYERROR_VERBOSE 1 yyerror outputs already something like syntax error, unexpected '+', expecting NUM or '(' Print Line Number To print the current line number you can make use of yylineno. You need to declare it with extern int yylineno; in the .y fi...
62,116,070
62,133,194
Getting error messages from QtCreator when trying to build hello world program but the code can still be executed
Im doing another QtCreator setup on a new system, and now Im getting errors when I try to build even a hello world program.Seems something is wrong with my C++ libs of how Qt is trying to put them together. I'm truly stumped here, any suggestions at all are appreciated. Looked at this a bit more, and it is even strang...
So this is caused by some changes they have made to the Clang code model( which I do not/never have used ) and apparaently is quite a common issue. See: https://forum.qt.io/topic/107181/lot-of-errors-but-it-builds-and-runs-successfully/2 To disable go to Help->About plugins and uncheck the Clang code model box. Restart...
62,116,124
62,116,296
How to deduce nesting class template type from typedef composition?
I would like to define a type from an typedef alias for a specialized class template. Using the same (but unknown) class template type and modifying the contained type. How to deduce the class template type of the alias? I tried using template template parameters $ clang++ prog.cc -Wall -Wextra -std=c++14 -pedantic: //...
It's doable, but you have to take stock of the error. You wrote a template accept as an argument another template, but you pass it a concrete type. That's a mismatch. Templates aren't types, but recipes for creating them. You can use partial template specialization to recognize when your meta-function is given a type t...
62,116,277
62,117,863
Why std::count is slower that plain for loop with MSVC Compiler but equal with GCC?
I am testing the performance of the C++ standard library algorithms and encountered a weird thing. Here is my code to compare the performance of std::count vs plain for loop: #include <algorithm> #include <vector> #include <iostream> #include <chrono> using namespace std::chrono; int my_count(const std::vector<int>& ...
This is because MSVC vectorizes your manually written code, but is unable to do the same for std::count. This is how vectorized code looks: movdqa xmm5, XMMWORD PTR __xmm@00000001000000010000000100000001 and rcx, -8 xorps xmm3, xmm3 xorps xmm2, xmm2 npad 3 $LL4@my_cou...
62,116,557
62,120,050
Is there a way to bring all definitions in a C++ struct/class into scope without deriving from it?
Musing on a Sunday... Deriving from a class brings all names from the base class into the scope of the derived class. However, it also adds the base class non-static data members to every instance of the derived class. Is there a way to achieve the former without the latter? I'm asking in the interest of concise notati...
Deriving from a class brings all names from the base class into the scope of the derived class. Let me stop you there. Yes, it is true that inheriting from a base class causes the (non-private) names in the base class to be accessible from the derived class definition. However, that's not why you inherit from a base ...
62,116,567
62,116,692
Improve the usecase of a template-based library
I'm creating a lib in c++, using templates. The problem I'm trying to resolve, the use case of itself is annoying. First creates a container "Q_fun" with templates and the rest of classes use it, so all the classes have the same template parameters. main.cpp lib::Discrete<unsigned> status(3),actions(21); ...
Use a type-trait: template <typename T,unsigned st, unsigned ac> struct my_types { using Agent_t = Agent<T,st,ac>; using Q_fun_t = Q_fun<T,st,ac>; using Trainer_TD_t = Trainer_TD<T,st,ac>; }; Now the template parameters need not be repeated: using types = my_types<double,1,1>; types::Agent_t agent; types::...
62,116,603
62,116,715
Unable to pass "this" pointer to another class and calling any methods of that class in CPP
Here I am trying to pass the instance of ATMMachine using "this" keyword to the HasCard class and trying to call any method of ATMMachine from HasClass using that instance. But I am not able to call any of the methods of ATMMachine. For example unable to call machine->insertCard(); Could someone please help me to find...
But I am not able to call any of the methods of ATMMachine. with the forward declaration class ATMMachine; you only tell that this class exists, but the compiler does not know anything of its member functions until the full class definition is reached. That's why you get an error like this: invalid use of incomple...
62,116,773
62,117,331
Compiling C++ repl May 2020
Compiling C++ repl I wonder whether you can help. I am working through the FreeCodeCamp tutorial on C++ and I am using repl.it as an online IDE. https://www.freecodecamp.org/news/the-c-plus-plus-programming-language/ The "+new repl" command and choosing a langauage C++ works just fine. Since I wanted to create a Repl...
Delete the .replit file on the and see if that resolves your problem. Check this image for reference: Image reference
62,116,908
62,117,017
Conditional passing of a default argument to a function (using the '?' operator)
There be a function declared as CalculateTimeSilence(float SilenceThresholdOverride = -1.f); Is there a way to call it, so that I can utilize the conditional '?' operator to either choose a value for SilenceThresholdOverride or leave it at the default value? Expressed as pseudo-code: CalculateTimeSilence(bUseOverride ...
When you are calling the function with out specifiying the parameter, then the default is added at the call site, so when you call CalculateTimeSilence(); Then you are actually calling CalculateTimeSilence(-1.f); There is no default or similar mechanism to get the default argument, but you can do that "manually" cons...
62,117,095
62,117,187
Strange side effect from a copy constructor
This simple code: #include <iostream> #include <vector> struct my_struct { int m_a; my_struct(int a) : m_a(a) { std::cout << "normal const " << m_a << std::endl; } my_struct(const my_struct&& other) : m_a(other.m_a) { std::cout << "copy move " << other.m_a << std::endl; } my_struct(const my_struct &...
Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect... When you call push_back on std::vector, vector may need to grow it's size as stated in the cppreference: If the new size() is greater than capacity() then all iterators an...
62,117,277
62,120,643
C++ Multithreading - algorithm alternative of merge sort with threads
I have written a merge sort algorithm that sort array with integer data. Now I need to write another sorting algorithm again with multithread concepts -phthread, which again sorting array with integer data. My task background: I have 2 child processes which sorting(with different algorithms) one integer array and firs...
One portable option is to use Intel Parallel STL. It is compatible with C++11 and implements parallel std::sort. C++17 parallel algorithms in GNU C++ standard library and gcc-9 delegate to Intel Parallel STL.
62,117,281
62,117,424
expected 'while' or expected '}' Answered before yes, but I can't fix it myself
I have already checked all the other questions but I just can't fix it.. I am a nuub at coding. I don't know why it says it needs a while or where to put it, and it gives the wrong answer for the LOCS function also is there anything i can do about the default pointer warning. this is just a start i will be extending th...
#include <iostream> using namespace std; void main() { //Declaring the constant variables const double BONUS_RATE = 5.0; //Declaring the variables int hours; int sales; int Status; string permanent, casual, Name, status, result, employee; double rate, sale_bonus, netPay, gross; ...
62,117,466
62,117,758
Why is the copy constructor of this template class not getting called?
The copy constructor never gets called (I'm using g++ with -std=c++11): pointers.cpp: #include <iostream> template <typename T> class SharedPtr { private: int *m_Count; T *m_Ptr; public: SharedPtr(T *ptr = nullptr) : m_Count(new int), m_Ptr(ptr) { *m_Count = 1; } SharedPtr(con...
None of the code in main() calls the copy contructor of SharedPtr: SharedPtr<Entity> e0; calls SharedPtr(T *ptr = nullptr) SharedPtr<Entity> sharedEntity = new Entity(); calls SharedPtr(T *ptr = nullptr) e0 = sharedEntity; calls operator=() which is not defined in your SharedPtr
62,117,500
62,118,002
How to pass lambda function by pointer?
I am a new in c++ maybe I miss something, but actually what I need to do is: I have a class that processing something in other thread, during this processing I need that it invoke a callback for progress. How I see I can do it, I need to declarate pointer (maybe shared_ptr) for my callback function as a class member, t...
I am using VC++ I hope this code will be successful for you. class RobocopyCopy { typedef std::function<void(int)> TVoidIntCallback; TVoidIntCallback evnt; public: RobocopyCopy* set_monitoring_done_callback(TVoidIntCallback monitoring_done_callback) { //set callBack function from out side. ...
62,117,594
62,118,896
C++ template instance as function parameter and lambda binary predicate
I am in the process of fixing some of the sonarcloud issues on my project. One complaint is the function where I read and deserialize the settings for my application. Basically there are 50 or so blocks of this in one function: if (!m_logLevel.deserializeFromSettings(settings, HGGW_KEY_LOGLEVEL) || m_logLevel.value() <...
The reason your code reports an error is that for a function template declared as: template <typename X> void readAWSSettingOrPopulateDefault(AwsProperty<X> property, QString key , X default_val, QSettings settings , bool (*predicate)(X)); the compi...
62,117,660
62,117,992
No need for the operator () in std::generate?
Why we don't add the operator () in std::generate (myvector.begin(), myvector.end(), RandomNumber)? Being something like this: std::generate (myvector.begin(), myvector.end(), RandomNumber()). Code taken from cplusplus: int RandomNumber () { return (std::rand()%100); } int main () { std::srand ( unsigned ( std::time...
Function pointers and functors are not the same thing RandomNumber is the name of a function. It'll decay to a function pointer here. That's one way to pass a callable to algorithms like std::generate. Another way is to create a type, a class, a functor, which has a call operator (operator()). We can also pass an insta...
62,117,843
62,119,086
C++ Converting MIDI Note ID in a note
I have a Midi keyboard that when plugged in my program i can red the values of each pressed if but i have been having difficulties into finding an appropriate method to convert each Note ID into a specific note. the key id jumps from 128 to 640 to 1152 to 1408 it increases for each key i press. this are some ways that ...
For anyone else that might encounter this I previosuly used this to try to acess the data wcout << "Velocity is " << HIWORD(dwParam1) << endl; //velocity wcout << "Key ID is " << LOWORD(dwParam1) << endl; //keyID but this was the correct way to do it HIBYTE(dwParam1) << endl; //NoteNumber i think? LOBYTE(dwParam1) << ...
62,117,987
62,119,712
How to convert Windows ProductType to name?
The GetProductInfo() function returns pdwReturnedProductType as a numeric type argument. Is there a function to convert this number to a name? Or, can you suggest to me a really full list of such product name constants? The MSDN article is missing some values, like 0x59 - "Industry Pro (Embedded)".
Look at the OSEdition Enumeration defines on MSDN, it has the numeric values you are looking for, including 0x59: This section provides the product enumerations for the OSEdition element. #define PRODUCT_EMBEDDED_INDUSTRY 0x00000059 AFAIK, there is no function to convert these numeric values into human readable name...
62,118,084
62,118,438
Rcpp select/subset NumericMatrix column by a NumericVector
I can select all the rows of a matrix and a range of columns of a matrix as follows: library(Rcpp) cppFunction(' NumericMatrix subset(NumericMatrix x){ return x(_, Range(0, 1)); } ') However, I would like to select columns based on a NumericVector y which, for instance, could be something like c(0, 1, 0, 0, 1). I tr...
Alas, Rcpp doesn't have great support for non-contiguous views or selecting in a single statement only columns 1 and 4. As you saw, selecting contiguous views or selecting all columns is accessible with Rcpp::Range(). You'll likely want to upgrade to RcppArmadillo for better control over matrix subsets. RcppArmadillo ...
62,118,196
62,118,761
How to use std::valarray in if statement without redundant computation?
I have the following code with float, for example: std::vector<float> v = {0.f, 1.f, 2.f}; for(size_t i = 0; i < v.size(); ++i) if(v[i] != 0) // An optimization for `v[i] != 0`. v[i] = v[i] * v[i] * v[i]; // Time-consuming computation. Now I want to replace float with std::valarray<float>: using vfloat = s...
If you want to skip elemets in v[i] use a nested loop using vfloat = std::valarray<float>; std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}}; for(size_t i = 0; i < v.size(); ++i) for(size_t j = 0; j < v[i].size(); ++j) if (v[i][j] != 0) v[i][j] = v[i][j] * v[i][j] * ...
62,118,530
62,118,616
Why does auto&& var2 not imply rvalue reference?
Why does auto&& var2 not mean rvalue reference in the code below? I would be grateful to have some help with this question. Widget&& var1 = someWidget; // here, “&&” means rvalue reference auto&& var2 = var1; // here, “&&” does not mean rvalue reference Given that Widget&& var1 is an rvalue reference...
Given that Widget&& var1 is an rvalue reference, why isn't it an rvalue? someWidget, var1, and var2 all have a name and, therefore, they are all lvalues regardless of their declared type. The term rvalue reference is about the type of the reference, var1, whereas the term rvalue is about the value category of the exp...
62,118,553
62,118,739
Checking whether current object is destroyed or not inside the same class in C++
I have to call a function of a class from another function of the same class. But the problem is for some cases the current object can be destroyed. So for this case calling the function is creating errors. Is there any way to check whether the current object is destroyed or not from inside the class? Another thread m...
Is there any way to check whether the current object is destroyed or not from inside the class? No, there is no way to do that. I presume that "from inside the class" means "by using state of the object". Well, if the object is destroyed, then there is no state that could be observed. Any attempt would result in unde...
62,118,923
62,119,072
Is the file mode flag “ios::app” used to delete a file if it already exists?
I had this question in mind about the file mode flag ios::app. Is it used to delete a file if it already exists?
No, the flag std::ios::app isn't used to delete a file if already exists. When std::ios::app flag is set, all output operations are performed at the end of the file. Rather you could use to delete a file if exists (you must have filesystem library which exists in c++17 and above): try { if (std::filesystem::remove(...
62,118,981
62,119,003
Learning c++, compilation error "no matching function for call"
In the book Accelerated C+ I'm trying to run the code #include <iostream> #include <string> int main() { std::cout << "Please enter your name: "; std::string name; std::cin >> name; const std::string greeting = "Hello, " + name + "!"; const std::string spaces(greeting.size(), " "); const std::string second = "* " ...
The second argument for the std::string constructor needs to be a char, not a string: const std::string spaces(greeting.size(), ' '); You also need to do the same thing for the following line, and get rid of the + symbol: const std::string first(second.size(), + "*"); // wrong like this: const std::string first(seco...
62,119,591
62,124,210
How to continue using gdb to debug c++ code after reconnecting to remote Ubuntu machine using ssh?
My local machine is of Windows 10 and I have a bad network condition. So when I ssh to log in remote Ubuntu machine, and try to debug using gdb, which costs perhaps 30 minutes to the breakpoint, I often get connection close error. And when I ssh again, I have to start over. Is there a recoverable function of gdb so ...
Is there a recoverable function of gdb so that I can continue using it after reconnecting? No. You need to use a program designed to keep your session alive: tmux or screen. Spending time learning to use them well now will pay for itself many times over.
62,119,661
62,119,705
error solving Balanced Brackets check from hacker rank using stack
while solving Balanced Brackets check from hacker rank using stack, the error I am getting is : Solution.cpp: In function ‘std::__cxx11::string isBalanced(std::__cxx11::string)’: Solution.cpp:7:17: error: control reaches end of non-void function [-Werror=return-type] stack<char> c; ^ cc1plus: so...
As the error message says, your function does not always return a value. You could fix that by returning "NO", in the case that your stack is not empty at the end of the function: if (c.empty()) return "YES"; return "NO"; Note that the return value of "NO" will only be returned in the case that "YES" is not return...
62,119,808
62,119,927
C++ versions, what they mean, how to update them
Is the c++ version you use tied to the version of compiler you have or IDE? If it isn't either of those, how do I use c++ 11 on my IDE? How do i update what C++ version i use in my programs? How do I check what version I'm using? I know that printing the __cplusplus variable can tell me what version I'm using, but this...
The C++ version you can use is obviously tied to the compiler you use. If your compiler doesn't support some newer standard then of course you cannot use it. As for IDEs; some IDEs are tied to a specific compiler, some can use different ones. Some compilers support multiple language versions but require you to explicit...
62,119,901
62,119,980
Almost all of the constructors and deconstructors in my classes are implicitly defined as deleted?
Variable.h #pragma once #include <unordered_map> namespace ssu { class GenericArray; class Variable { enum Type { NONE, BOOL, STRING, INT, FLOAT, ARRAY, DICT, TYPE_MAX }; private...
Union declaration Unions cannot contain a non-static data member with a non-trivial special member function (copy constructor, copy-assignment operator, or destructor). If a union contains a non-static data member with a non-trivial special member function (copy/move constructor, copy/move assignment, or destructor), t...
62,119,958
62,120,083
Vector invalid subscript. SFML
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message: Unhandled exceptio...
For what I can see here, the problem might be the snake.body.at(0) That you are using inside your code a lot of times, when maybe the body has no elements, and so there is no 0's element
62,120,036
62,120,153
Document enum class values using Doxygen without enabling EXTRACT_ALL
I wasn't able to show documentation for values of enum classes without setting EXTRACT_ALL. The comments for preserve, truncate and append aren't there. The enum itself is documented. If I enable EXTRACT_ALL I get a list. My code is: namespace grimoire { ... /// @brief Behaviour of function open_for_write for already...
Doxygen does not always pickup an enum, this can be overcome by means of using the \file command. Furthermore you document the enum values after its definition, this means you should not use /// but ///< So the limited example would looks like: /// \file /// @brief Behavior of function open_for_write for already exis...
62,120,288
62,120,555
Correct way to declare an Array member in a class
I have a class that looks like this class StatisticsQuantiles : public StatisticsMC { public: StatisticsQuantiles(double p_, unsigned long NumberOfPaths); virtual void DumpOneResult(double result); virtual std::vector<std::vector<double>> GetResultsSoFar() const; virtual StatisticsMC* clone() const; pri...
the size of std::array must be known at compile time, which is not the case here. So std::vector is your option I believe. If you are worried about the efficiency of push_back re-sizing, you can reserve the memory in your constructor. ResultList.reserve(NumberOfPaths); push_back then won't re-size unless you insert mo...
62,120,299
62,120,440
Outputing 64bit integers in c++
I wrote the following code- #include <iostream> #include <tuple> int sumarr(int64_t arr[], int length) { long long int sum= 0; for(int i=0; i<length; i++) { sum += arr[i]; } return sum; } void minimaxval(int64_t arr[], int length,int64_t *x,int64_t *y) { long long int c=0; long long...
In 'summar' you have wrong return type. If you change it to int64_t everything will be fine. P. S. And yes this is also my first answer)
62,120,455
62,120,523
set a value of std::variant by index
I was trying to create something like the upcoming (if ever) std::expected using std::variant. I thought it would be very easy to something like that, yet maybe not optimal. However, I faced some interesting exercise with std::variant and it is how to assign a value by an index? The only way how I got close to it is in...
The function you're looking for is variant::emplace. Your function becomes: void SetValue(auto&& value) { data_.template emplace<1>(std::forward<decltype(value)>(value)); }
62,120,458
62,120,588
How to change Vector Objects into different colours?
I've been trying to get my code to change vectors objects into different colours. I've put an example of two of the methods I've used for vectors and getting colours. Does anyone have any information on how to do this? #include <iostream> #include <vector> #include <windows.h> std::vector<std::string> playerInventory;...
You seem to already know how to change the colors, so what you need to do is just change the color inside your loop, for each element of the vector. Example: for ( int x = 0; x != playerInventory.size(); ++x ) { SetConsoleTextAttribute( color, 10 + x ); std::cout << playerInventory[x] << std::endl; } Keep in m...
62,120,533
62,141,354
Embeding V8 in C++ causes "unrecognized external symbol" errors related to libcpp
I am trying to embed v8 into my application (using Visual Studio 2019). First, I built it to x86 (ia32) debug static linked library. I also wanted it to be monolitic. There were some errors, but eventualy I managed and I succesfully built it. I ran v8 test after compiling and the result was good. Next, I wanted to use...
Try adding use_custom_libcxx = false to args.gn, that should help.
62,120,549
62,120,874
Why for gcc 'UNIX' and 'unix' macros are not the same thing?
I have a weird problem with gcc in Ubuntu Mate. I need to write a golang program which uses a third-party C library, but i'v run a problem. When I try to connect the third-party library in this code: package main // #cgo CFLAGS: -I /opt/cprocsp/include/interfaces/ // #cgo CFLAGS: -I /opt/cprocsp/include/ // #cgo CFL...
This query to a popular Internet search engine brings only a single page matching the word "unix" in the proper context: it's this page on system-specific macros. That page hints at two things: GCC does not guarantee that UNIX macro is defined. The unix macro is described as being "common" but nothing is stated about ...
62,120,709
62,120,756
I cannot write c++ arrays now because of "error C4430: missing type specifier - int assumed. Note: C++ does not support default-int"
Hello to all the handsome people who want to save me from my pain, I am new to c++, and after having done the usual intro stuff like strings, loops, arrays, pointers that w3schools tells you, I decided to write some code. I decided to start with a simple challenge that asks you to write some loops that will sort a few ...
You haven't declared result. C has the idea that using an undeclared variable causes the compiler to assume that the variable is declared extern int. Some C++ compilers support this for backwards-compatibility, but it's not part of standard C++. In this case, the compiler seems to support this so it assumes extern in...
62,121,459
62,121,502
C++: seeding random number per Stroustrup's examples
I'm using small modifications Stroustrup's C++ examples for random numbers in C++ 4th Ed Page 127-130. I'm having trouble modifying the example on Page 130 below to use a non-deterministic random seed. I get warning when adding in the code re{rd} in Rand_ints constructor. I have included the warnings but am unsure wh...
The compiler is telling you that the data members of Rand_int will be initialized in the order that they are declared (rd, then re, then dist) but that this does not match the order in which you have specified them in the constructor's initializer list: dist{low,high}, re{rd()} This warning is intended to alert you to...
62,121,765
62,122,611
Is a std::function member variable of the class type allowed (incomplete type)?
I am wondering if this is fine to do, it compiles fine for me but I am not sure if it actually is ok: class Foo { std::function<Foo(Foo& f)> my_function; }; The function my_function takes a Foo reference and returns a Foo. It is a member variable inside Foo, and usually these incomplete types are not allowed. For ex...
It is true that, in general, it is invalid to instantiate templates from the standard library with arguments that are incomplete types: [res.on.functions]/2 In particular, the effects are undefined in the following cases: (2.5) — if an incomplete type (6.9) is used as a template argument when instantiating a templat...
62,122,442
62,122,777
Is it possible to define both const and regular version of the function with a single definition? (using templates, auto, decltype, etc)
Suppose that I am writing an iterator and const_iterator for singly linked list. Suppose that I have a following classes: template <typename T> struct Node { T value; Node* next; } template <typename T> struct NodePtr { private: Node<T>* node; public: T& operator*() { return node->value; } const...
I don't think there is a way to write the function only once. Most things you can do with auto and templates but the problem is the const specifier for the function itself. I know of no way to make that in any form conditional. You could make it always const and then the nodePtr mutable but that kind of defeats the poi...
62,122,480
62,122,792
How to create two functions with the same name and different return type and runned based on boolean parameter
I have two functions with the same name but different return types. I want to run the function based on their third parameter. If the third parameter is true I want to run the first and If the parameter is false to run the second function. I was trying different things on my own because I couldn't find information onli...
This solution is not about having two different functions but if you wanted the function to return a different type depending on the bool value using boost::any. boost::any function(int a, int b, const bool c) { std::string str = "Hello world!"; int num = 10; if ( c ) { return boost::any(num); ...
62,122,548
62,123,396
Makefile specific to directory structure
I'm trying to compile my project using a makefile. I'm new to makefiles so forgive my ignorance. The problem I'm running into is that I would like the output command to build all of the .o files but If I run it as such it will not build the .o files and instead will try to compile all .o files in the /obj directory. Ho...
This line: output: main/main.cpp main/main.hpp $(OBJ)/*.o cannot work correctly as written. What does this do? It tells make, the target output (which, by the way, you never actually create: this rule creates a totally different file out/recipe_book.out, but leave that aside for now) depends on the files main/main.c...
62,122,597
62,122,956
Count decimal numbers in a string using the standard library
I have white-space separeted integers inside a string, e.g.: std::string s = "1 2 33 444 0 5"; The string is well-formed: just white-space separated numbers without any letters, new-lines, etc. How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g....
This solution uses only the STL, has no loops, and will handle arbitrary number of leading, trailing, and extra whitespace: std::string s = "1 2 33 444 0 5"; std::stringstream ss(s); int const count = std::distance(std::istream_iterator<int>{ss}, std::istream_iterator<int>{}); Here's ...
62,123,033
62,124,035
Overload Resolution differs between compilers
I have constructed the following minimal example of my problem: #include <iostream> struct Foo { Foo() { std::cout << "default" << std::endl; } Foo(Foo& f2) { std::cout << "non-const" << std::endl; } Foo(const Foo& f2) { std::cout << "const" << std::endl; } }; int main() { std::pair<Fo...
Like already said, probably the implementations of std::pair for both of them differ. I wrote two very similar implementations of a pair that exhibit exactly your differing behaviors, even without changing the type of the pair: godbolt #include <iostream> struct T { T() { std::cerr << "default\n"; } ...
62,123,133
62,123,273
How to pass a templated function parameter with a subclass of the templated type in C++?
Compiling the following contrived example: class Base {}; class Derived : public Base {}; template< typename T > class A {}; class B { public: static void f( const A< Base >& ) {} }; int main() { A< Base > tb; A< Derived > td; B::f( tb ); B::f( td ); return 0; } using g++-8 gives me the ...
It is true that Derived is derived from Base, but that doesn't mean that A<Derived> must therefore be derived from A<Base>. C++ templates don't work this way. All that A<Derived> is, is a class, instantiated by the A template. You could've simply declared: class A_Derived { // ... }; With the same members (if i...
62,123,157
62,123,218
Compile java to object files compatible with C/C++
So I am working(actually still planning) on a GUI project, and I need control over every single pixel on the window. I have done a lot of Java and I know how to do that, the problem is that I want to do all the logic on C++(because I just love how it works) and I don't even know how to setup a GUI in C++(I already too...
Look into JNI. Years ago, when doing the game of life in programming class, I chose to have a C function do the pixel work, just like you are thinking of, because it, ahem, back then, made the graphics work run many times faster. Noticeably, back then anyway. Write the Java Program and Compile Generate header file fro...
62,123,176
62,123,455
Returning an array from a function to main in c++
How can I return this array to the main function for further use in my program? int* enterMarks(int marks) { int arr[marks]; cout << "Please enter " << marks << "marks (0<=Mark<=100):" << endl; for (int i = 0; i < marks; i++) { cout << i+1 << ">"; cin >> arr[i]; } cout << "Thank you..." << endl; return *arr;...
For starters variable length arrays like this int* enterMarks(int marks) { int arr[marks]; //... is not a standard C++ feature. In C++ the size of an array shall be a compile-time constant. Secondly a pointer to a local array with automatic storage duration returned from the function will have invalid value because t...
62,123,528
62,123,730
Time complexity for 2 nested loops
If I'm taking input through 2 nested For-loops like this cin>>x; for(i=0;i<x;i++) { cin>>y; for(j=0;j<y;j++) } The complexity of the Outer loop is O(X) but I'm confused about the Time complexity of the inner loop as the Y is variable.
The complexity of the outer loop is not O(x), because the time it takes to run the outer loop depends on the value of y entered. Let's say we have a sequence y1,y2,...,yn of inputs for y. Then the first loop would take y1 operations and the second iteration would take y2 operations and so on for each of the x iteration...
62,123,767
62,123,834
Where trailing return type is actually needed in C++?
I am reading about trailing return type. I came across this site https://blog.petrzemek.net/2017/01/17/pros-and-cons-of-alternative-function-syntax-in-cpp/ which is explaining about the need of these return types and it mentioned as below. template<typename Lhs, typename Rhs> decltype(lhs + rhs) add(const Lhs& lhs, co...
It knows the capitalized types Lhs and Rhs, but not the lowercase variables lhs and rhs. They're declared after the decltype.
62,123,778
62,123,955
2D array of 0's ruining logic of unrelated loop - C++
The listed code is from a larger project that I am working on (I deleted almost everything else that wasn't necessary for this posting) that is having some trouble running properly. I found the line that is causing the error but I'm hoping for an explanation as to why this line is causing it. #include <iostream> #incl...
rem is not completely initialized. The loop that assigns values only iterates until hold is zero, so it does not set the higher elements. But the loop that prints it always prints n * m elements. The effect of defining nextGen is incidental. It may affect where rem is placed in memory, resulting in it happening to cont...
62,124,666
62,124,753
Can't assign empty initializer to vector of unique_ptrs
I have the following code: std::unordered_map<std::string, std::vector<std::unique_ptr<class EventTrigger>>> triggers; if (triggers.end() == triggers.find(eventName)) { triggers[eventName] = {}; } That results in an error about using a deleted constructor of unique_ptr. If, on the other hand, I do this, everything...
triggers[eventName] = {} resolves to vector<T>::operator=(std::initializer_list<T>). This operator requires copying elements from the initializer list to the vector. triggers[eventName] = std::vector<...>() resolves to vector<T>::operator=(vector<T>&&) - the move assignment operator. This doesn't require copying any el...
62,124,822
62,124,874
Input/Output Operators Overloading in C++
Stuck with ostream/istream operator overloading Q1. why we are using ostream& operator as friend? Q2. Why we are passing two arguments in ostream & operator << (ostream &out, const Complex &c) Q3. why we are referencing to Cout and in ? istream & operator >> (istream &in, Complex &c). Ref to: Overloading stream Oerator...
A1. To access the private members A2. The first argument is the stream and the second is the object. operator<< and operator>> expect two arguments A3. Because they are modified in the function. The functions read from resp. write into the stream. In addition: Don't use using namespace std; Don't initialize members in...
62,125,123
62,130,866
SFML Cross-compilation for Windows on Linux
I'm trying to compile a simple program with SFML (basic helloworld but with a big green circle). I'm supposed to build the program on Linux for Linux and Windows. When I compile for Linux the program compile and run perfectly, however when I try to compile the Windows Executable, I get the following error: /usr/bin/x8...
Thanks to @tsyvarev here is the solution that worked for me: I added this line to my toolchain for Windows link_directories(gitlab_ci/SFML-2.5.1-WIN/lib) The final result is: # Sample toolchain file for building for Windows from an Ubuntu Linux system. # # Typical usage: # *) install cross compiler: `sudo apt-get i...
62,125,465
62,126,041
How to merge vectors returned from function?
I have a function that returns a vector of strings and inside my main function I would like to combine all the vectors returned from the function. However I keep hitting an error vector iterators incompatible, but I make sure I return a ptr from the function so the vector is not deleted when the function ends. const un...
Your function can return std::vector without using pointer. #include <iostream> #include <string> #include <vector> using namespace std; vector<string> loadTransactions(string filename) { vector<string> transaction {}; //some processing return transaction; } int main() { vector<string> allTransactions...
62,125,693
62,125,942
why is this regex in C++ throwing an invalid range in bracket expression exception?
I am playing around with C++ regular expression: #include <iostream> #include <regex> using namespace std; int main() { std::regex e("[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]"); std::string str = "¡";//u00A1, trying to match this character bool match = std::regex_match(str, e); cout << match << endl...
The problem is that you are using a char based regex but a 16 bit regular expression. Try switching to wchar_t as your character type. #include <iostream> #include <regex> using namespace std; int main() { std::wregex e(L"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]"); std::wstring str = L"¡";//u00A1, trying ...
62,125,871
62,169,380
Simple coroutine leaking with GCC 10
Consider the following simple coroutine, which tracks its construction and destruction: #include <coroutine> #include <iostream> struct simple { static inline int x = 0; int id = 0; simple() : id{ x++ } { std::cout << id << " constructed\n"; } simple(simple&&) : id{ x++ } { std::cout << id << " move constructe...
As Oliv mentioned, it appears this is just a bug with GCC's experimental coroutine support. A ticket has been raised here.
62,125,949
62,126,051
Why is the output of `typeid(T&).name()` given as `T` instead of `T&`?
As the subject, you could check the related code on https://godbolt.org/z/qtjVP6. For your convience, the code is posted below: #include<typeinfo> #include<iostream> class Widget{}; Widget someWidget; int main() { Widget&& var1 = Widget{}; // here, “&&” means rvalue reference auto&& var2 = var1; ...
Per C++ Reference (emphasis mine): 1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the referenced type. So for type = T&, typeid(type) will give results about T (reference removed). It's easy to understand IMO, as ...
62,125,989
62,126,126
Returning smart pointer from raw pointer
This is the way i am returning smart pointer from a raw pointer. std::shared_ptr<Geometry> Clone() const { Circle *sc = new Circle(*this); return std::shared_ptr< Geometry >(sc); } Is it the correct way to return Smart pointer from raw pointer ?
The term "correct" is quite vague. Ok, this code should work, if you ask of that. However there are more details you should take into consideration. First, it is better to construct the object in the same expression where you construct the smart pointer: std::shared_ptr<Geometry> Clone() const { return std::shared_...
62,126,099
62,126,273
Unexpected difference between char* and string with std::getenv
I have code that looks something like this: #include <cstdlib> #include <iostream> #include <string> std::string string_from_env(std::string var) { std::string out = std::getenv(var.c_str()); return out; } int main() { const char* x1 = string_from_env("TEST_HOST").c_str(); const char* x2 = string_from_env("TE...
The pointer returned by std::string::c_str points to memory owned by the string object. When the string is destroyed (or even mutated in certain ways), that pointer becomes invalid. Since the temporary string objects returned by string_from_env in your first three calls aren't immediately bound to references, they are...
62,126,242
62,126,315
How can a mersenne_twister_engine be serialized using Boost?
I have a class that implements std::mt19937 and I would like to be able to save and load the state of the random number generator for consistency. I'm aware that the << and >> operators can be used to save/load the engine's state and that I can separate the save and load functions when I archive the file if necessary. ...
From this output/input operator reference regarding the output operator: Serializes the internal state of the pseudo-random number engine e as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream ost. The stream could be any kind of output stream, for example an output string st...
62,126,465
62,126,760
Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example: // // \begin{eqnarray*} // y_1 &=& x_1 \\ // y_2 &=& x_2 // \end{eqnarray*} // int main() {} With clang++ (version 9.0.1-10) I can compile my code without problem: clang++ -Wall prog.cpp but with g++ (version 9.2.1) g++...
Such comments are legal, but they could have unexpected effects, hence the warning. The next line after the one with the backslash at the end is a continuation of the comment, regardless of the // at the beginning. So this // \\ Hey dude! int main () {} is a valid C++ program. And no, the backslash before the last one...
62,126,626
62,127,054
How do i drag item from QListWidget and drop to QPlainTextEdit?
As shown in the image on the left side i have a QListWidget named "my_listwidget" populated with 3 commands and on the right side i have a QPlainTextEdit named "my_textedit". i am able to drag from QListWidget by using this code ui->block_commands_listwidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->b...
The problem is simple: QPlaintTextEdit does not recognize the mimetype that the QListWidget sends by default, so the solution is to override the mimeData() method adding the text of the selected items as plain text: #include <QtWidgets> class ListWidget: public QListWidget{ public: using QListWidget::QListWidget; ...
62,126,804
62,127,313
CreateWICTextureFromFile returns E_NOINTERFACE
I want to create a Texture loader. However, when I create the following line: HRESULT res = CreateWICTextureFromFile(device, file.c_str(),&resource,&shaderResourceView,0); it returns E_NOINTERFACE. The file I want to load definitively exists and both the ID3D11Device and the ID3D11DeviceContext are created successfull...
Make sure you have initialized COM as that's the most likely problem. #if (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/) Microsoft::WRL::Wrappers::RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); if (FAILED(initialize)) // error #else HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED)...
62,126,983
62,168,270
How to delete table rows in word using Qt
I want to delete some table rows in a doc file by using QAxobject,like this: QAxObject* range_delete = table->querySubObject("Rows(int)", 6); if (range_delete) { range_delete->dynamicCall("Delete()"); } but it doesn't work,the range_delete always get Null. So, How can i do this in a correct way ? And then what if ...
I find a way to solve this problem. I found that, when there are vertically merged cells in the table, individual rows cannot be selected,So, the range_delete always get null.And then, I choose the oher way to select the row that I want to delete. the code: //step one ,select the cell that the row contains QAxObject* c...
62,127,028
62,130,834
wxWidgets Drop Files eventhandler initialization problem (invalid static_cast)
I am trying to make a simple program to drop files on a list using C++ with a (wxWidgets) wxListCtrl. Tools I use: Code::Blocks 20.03, MinGW 17.1, wxWidgets 3.1.3, wxFormBuilder 3.9.0. OS: Windows 10 Pro. I tried the following: (in a function SetupGUI() which is called in the DnD_SimpleFrame class constructor.) m_lis...
If you carefully look at the error message: error: invalid static_cast from type 'bool (DnD_SimpleFrame::*)(wxArrayString&)' to type 'wxDropFilesEventFunction' {aka 'void (wxEvtHandler::*)(wxDropFilesEvent&)'} you can see that it says that it can't convert something from one type to the other one. The types may be dif...
62,127,692
62,127,857
Controlling randomness in Z3
Similar (but somewhat opposite) to this SO question, I do want to expose randomness if possible. That is, I want the two consecutive queries to provide different results. Is that possible? Here is my code: void oren_example() { int i; // context + solver context ctx; solver solver(ctx); // sorts ...
This is typically done by adding constraints to outlaw previous models. Note that unless you add new constraints, you will not get a new solution. If you simply want to rely on randomness after solving from scratch, try setting random seeds used by z3. There are a few of them: $ z3 -pd | grep seed random_seed (unsi...
62,127,799
62,128,576
streaming a bitmap while it is modified in C++
What I am trying to do is use some process to alter the contents of a bitmap image ( dimensions and everything else is kept constant). While I run a process to perform transformations on it, I want to concurrently stream the image to my screen as it happens. So it's basically video without a series of images, but rathe...
You could stream the images in a video encoder directly. For example you can feed ffmpeg with raw PGM/PPM images as input and you will get the compressed video as output without the need to ever create the actual images on disk. Writing a PGM or PPM image means just generating a few header bytes followed by actual pixe...
62,127,854
62,128,041
How to print next letters until Z and continue to A?
This code prints the next letters of what I input. For example, I input "v", it will show vwxyz, but I want it to print the others too, like vwxyzabc..... int main() { char a; int flag = 0; scanf("%c", &a); while (a <= 'z') { printf("%c", a); a++; } printf("\n"); return 0; } I a...
If the incremented character is not an alphabet, deduct 26 to go back to the starting and do the loop until you see the entered character. #include <cctype> // std::isalpha char curr = a; do { printf("%c", curr); ++curr; if (!std::isalpha(static_cast<unsigned char>(curr))) curr -= 26; } while (curr != ...
62,127,901
62,127,954
Simple way to reference member variables of base class templates
Is there any way to reference member variables of base class templates without base class names and scope resolution operator? template<typename D> struct B0 { int value; }; struct D0: B0<D0> { D0() { B0<D0>::value = 1; // OK. value = 1; // OK without `B0<D0>::`. } }; template<typen...
As the solutions, you have to make the name value dependent to make it visible for name lookup. Besides the one you've showed, you can also: Use using to introduce the name, template<typename T> struct D1: B1<T> { using B1<T>::value; // or move it in method's scope according to your intent D1() { val...
62,127,964
62,128,913
Iterate array elements in specific order
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right. The input data is a one-dimensional vector of integers: {1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, ...
I suppose this will do the job: Edit: I added this explanation since some people could not understand this solution so far although it just contains some simple linear index calculation, and since I did not see any non-TL;DR but complete solution : We iterate through the input data front to back. We always calculate th...
62,128,083
62,128,134
Does declaring a vector with size offer any improvements over using push_back in C++
Let us say we know the size of a vector we will be needing, (say 'n'). Does using vector<int> Array(n); offer any improvements over using Array.push_back(element) one by one? Which is recommended and why?
With vector<int> Array(n); you create a vector that contains n elements, all memory needed for those elements is allocated immediately. When you use e.g. Array.push_back(value); then the vector needs to be resized, which could mean the memory have to be reallocated and all the contents have to be copied to the new me...
62,128,313
62,129,169
Question about Introspection / static_assert (C++17)
I have a (container like) class that accepts several of my other types/classes as the data member. Now I would like to specify some properties (edit: positive integer) of the data type as compile time information. This works fine, but I would like to static_assert that the provided type is correct (uint8_t), the actual...
What you want to do depends on what exatly do you want to check. Want to check that char_count has value 2? static_assert(DataType::char_count::value == 2, "char_count is not 2!"); Want to check that char_count is an integral constant (or something else) that has uint8_t as type member type alias ? static_assert(std:...
62,128,390
62,133,845
Problem in code to divide N conditionally
So, I'm trying to solve the following Problem Statement For an integer N, find the number of times the following operation can be performed: Select an integer z which satisfies the 3 conditions: 1. Z can be expressed as p^e where p is prime and e > 0 2. z is a factor of N 3. z is different from all previous zs Now re...
The number N can be factored into (p1 ^ e1)(p2 ^ e2) .... For each of these factors p^e, the most that you can divide N by is (p)(p ^ 2)(p ^ 3).... Of course, all those powers need to sum to less than or equal to e. So you only need to compute all the factors once, and then for each e, find the largest triangular numbe...
62,128,493
62,129,015
Clang vs G++ lvalue to rvalue conversion
The question related to this one. By tracing slt_pair. h and move. h, it's seems that the difference between Clang and G++ is internally. I have tried to simulate the assignment of the object (pair.first) as same as the implementation of std_pair.h, the output is same as Clang output it's reasonable output, but why wh...
I think not everything in your example does what you think it does. The static_cast in the returns is meaningless, the result of cast1 and cast2 will automatically be an rvalue since you return by value. Further, cast1 and cast2 are also internally identical since std::remove_reference_t<Foo> is just Foo. You would nee...
62,128,669
62,145,044
Get latest USN data from Change Journal
The MSDN C++ code only shows how to obtain the change journal records starting from the buffer. MSDN Code for Reading Change Journal. My query is how do I fetch just the latest USN records from Change journal. I've increased the buffer size to my requirement. #define BUF_LEN 789824 Also, I cannot set the buffer to the...
Adding a large buffer leads to large memory allocation, which in turn leads to performance degradation. A workaround for this is to keep #define BUF_LEN 4096 (a small value) and increase the value of iterations to the maximum size of the change journal. for (I = 0; I <= 2415919104; I++) Here, the large value is simply...
62,129,062
62,129,202
The solution is executed with error 'out of bounds' on the line 25
Receiving an out of bounds error during compilation, tried alternate approaches still the same. it says error occurred on line 25 which is just a cin statement within bounds. where exactly am I going wrong. Clang, Debugger is generating this error. int main () { int n; cin >> n; int work[n]; for (int j = 1...
This is wrong: for (int j = 1; j <= n; j++) { cin >> work[j]; } Array indexes are from 0 to size-1 (included). Change to: for (int j = 0; j < n; j++) { cin >> work[j]; }
62,129,197
62,129,349
std::async with non static member functions
I am trying to evaluate a part of my code asynchronously #include <stdio.h> #include <string> #include <memory> #include <future> #include <map> namespace IG { typedef std::map<uint, std::string> CadDef; class FooFoo { CadDef foo() { CadDef cdef{}; cdef[1] = "aa"; ...
You can use a lambda like following, using a policy* auto handle = std::async(std::launch::async, [&ptr](){ return ptr->foo(); // Ofcourse make foo public in your snippet }); auto res = handle.get(); *Not necessarily required
62,129,242
62,130,838
No implementation found for void com.organization.app.Activity.a() in Release
What I'm trying to do is simply invoke a native function from my Java android activity that is implemented in my C++ codebase. The signature can be anything, but let's define it as void fooBar(). My workspace is organized in a tree structure of gradle projects, all of them "com.android.library" projects except for the ...
I found the solution. I did some cross-referencing between Debug and Release and found out that either turning off minifyEnabled or removing the proguard file declaration made the exception go away. After that, I looked into the proguard file I was using (which happened to be the default one for optimization) and saw t...
62,129,248
62,129,382
Why can the compiler not optimize floating point addition with 0?
I have four identity functions which do essentially nothing. Only multiplication with 1 could be optimized by clang to a single ret statement. float id0(float x) { return x + 1 - 1; } float id1(float x) { return x + 0; } float id2(float x) { return x * 2 / 2; } float id3(float x) { return x * 1; } A...
IEEE 754 floating-point numbers have two zero values, one negative, one positive. When added together, the result is the positive one. So id1(-0.f) is 0.f, not -0.f. Note that id1(-0.f) == -0.f because 0.f == -0.f. Demo Also, note that compiling with -ffast-math in GCC does make the optimization and changes the result....
62,129,606
62,133,876
Temporarily disable window during a function call
Consider: class Worker { public: void DoWork(); }; class MainWindow : public QMainWindow { Q_OBJECT private: Worker MyWorker; public: void DoWork(); }; I want the DoWork function of my MainWindow to behave like: void MainWindow::DoWork() { setEnabled(false); std::future<void> Resu = std::async(std::launc...
You can use a QFutureWatcher to receive notification about the completion of your QFuture without the need to be busy-waiting calling processEvents. Basically you subscribe to the signal QFutureWatcher<void>::finished to know when the operation is complete. In the associated slot you re-enable the widget. Particularl...
62,130,245
62,131,114
Infinite cycle due to QTextStream
So, I get infinite cycle while trying to read lines from file (line by line). I was trying to use do{}while(); cycle like that: QTextStream stream(stdin); QString line; do { line = stream.readLine(); } while (!line.isNull()); but I get empty string. Sure, I checked file path (it is right). I was trying to use /...
So, I got it. I opened the file incorrectly. I was using: if(!file.QIODevice::open(QIODevice::ReadOnly)) but it should be like that: if(!file.QFile::open(QFile::ReadOnly))
62,130,443
62,130,503
C++ - operator= self assignment checking
class Person { private: string name; int id; public: Person(string name, int id): name(name), id(id) {} const Person& operator=(const Person &another) { if (*this == another) // What is the problem here? return *this; // do copy return *this; } }; I want to make...
In *this == another you are trying to check whether both objects have the same value. For this to work, you have to define the operator== for Person. That is, Person::operator==() will determine whether two Person objects have the same value. However, since you want to protect against self-assignment, what you really n...
62,130,548
62,130,592
Removing .h extension in user defined c++ header file
Can we remove .h extensions while we define our own header file in c++? like in case of standard header files in c++. I have created a header file and named it add.h and tried including it using #include "add" but it didn't work. after following up the comments and answers: using codeblocks ide i have created a "add" o...
Can we remove .h extensions while we define our own header file in c++? Sure, as long as that matches the filename of the file. As far as the language is concerned, the name of the file is largely irrelevant. However, .h or similar such as .hpp is conventional, and helps the reader of the source to understand what th...
62,130,989
62,135,265
Switching from OpenCV 3 to OpenCV 4 causes webcam to record at a max of 5 fps instead the usual 30 fps
I'm having some trouble since I changed from OpenCV 3.x to 4.x (compiled from source) in my C++ project. I've replicated this behaviour in a small example that just opens a webcam and records for 5 seconds. With 3.x I am able to set the webcam framerate to 30 at full hd, but the same code with 4.x just ignores the cam...
This is a known bug that affects OpenCV > 3.3
62,131,292
62,131,466
How to keep object of subclass in another class in cpp? Base class undefined error
I'm coding simple shop program in cpp. I have 3 classes: Shop, Client, Bucket. Shop is parent class for Bucket. Shop has vector of clients and every client has his own bucket. I've got problem with #include's. I have to include Client.h in Shop.h so the Shop could see the vector of clients, but it seems I also have to ...
Bucket.h includes Shop.h which includes Client.h which includes Bucket.h... And so on forever and ever. This is a circular dependency. Shop.h doesn't need to include Client.h, it only needs to forward declare the Client class: #pragma once #include <vector> #include <string> #include "functions.h" // #include "Client.h...
62,131,475
62,131,839
shared_from_this when inheriting from class defined by third party
I've read many posts on stack-overflow about shared_from_this, bad_weak_ptr exceptions, and multiple inheritance while trying to research my problem. All of them propose you inherit a base class from enable_shared_from_this, and then derive from that. Well, what does one do when the class you have to derive from is a c...
You get the error because you are not public inheriting from enable_shared_from_this and shared_ptr and make_shared cannot detect that the object requires such support. Not because of inheritance from third party class. So, to fix just inherit as public: class A : public ThirdPartyClass, public std::enable_shared_from_...
62,132,093
62,132,114
Passing reference to class constructor, "provides no initializer for"
I'm trying to pass a class reference to a field, but I get the error "'mazeGenerator::maze' references must be initialized". I tried initializing 'maze' above the class constructor. Why is this happening? class mazeGenerator { public: Maze& maze; mazeGenerator(Maze& mazeObj) { maze=mazeObj; } }
You must initialize data members of reference type with a member initializer list, like this: mazeGenerator(Maze& mazeObj) : maze(mazeObj) {} This is also the case with const data members. Note that putting the declaration of the data member above the constructor doesn't actually make any difference; it could be decla...
62,132,181
62,143,820
Adding boost header files gives compile time errors
When i add the header file #include <boost/fusion/adapted/struct/adapt_struct.hpp> It gives couple of errors error C2988: unrecognizable template declaration/definition error C2143: syntax error: missing ';' before '<' error C2913: explicit specialization; 'boost::type_of::id2type_impl' is not a specialization of a...
After reading drescherjm , sehe's comments i changed some settings in the visual studio and when i changed platform Toolset from visual studio 2017 v(141) to visual studio 2015 v(140) , the program compiled sucessfully.
62,132,659
62,132,931
Does std::move invalidates the raw pointer points to something owned by unique_ptr?
If I have a unique pointer and I took a pointer to the something owned by unique_ptr: auto t = std::make_unique<int>(67); auto m = t.get(); auto d = std::move(t); std::cout << *m; I know m will be valid until t is modified or destroyed. But when I move ownership from t, m is still valid. Could someone make me under...
m is a raw pointer to the integer owned by t. auto d = std::move(t); transfers ownership to a new smart pointer d. The internal raw pointer of d gets set to the adress of your ressource and the raw pointer of t get's set to nullptr. The integer that is now owned by d is still at the exact same location as before. That ...