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
61,668,145
61,668,445
Is it a good idea to set multiple class members in one method?
I have a Class which describes Process Configuration: Class ProcessConfig { private: std::string _username; ... public: const std::string &getUserName(); const std::string &setUserName(); ... } I need to get uid and gid from the username and store them ...
1. Is this a good idea to set 2 values (uid and gid) with one setter method (setUidGid())? I don't see why not, you can have a single setter, if are going to create a user and then set uid and gid you can also make a constructor for it. 2. Is this ok to use such kind of function in setter method setUserName() and al...
61,668,174
61,668,272
C++ Declare same thread variable multiple times (in a loop)
I was wondering what will happen if I do something like this: void afunction(/*parameters*/) { /*do something*/ } // And then in main... while(1) { thread aThread(afunction, /*parameters*/); athread.detatch(); sleep(1); } Does this create an infinite amount of threads (until the system crashes)? Or does...
The former. In particular, when control enters the while-loop-body's scope, the thread object aThread is created and a new OS-thread is spawned by its constructor (note I'm assuming here that you are using std::thread and not some other thread class). Then you call detach() on the thread-object, so the OS-thread is ...
61,668,255
61,668,700
Function is not returning any value | C++
I'm writing a function that will find the number with max number of divisors but the function is not returning anything. Can someone point out my mistake? This is the question Write a C++ program that creates and integer array having 30 elements. Get input in this array (in main function). After that, pass that array ...
you don't need pointers to do that this simple code can fix your problem just change the size of your array as you want i am testing with array of size 4 here #include <iostream> using namespace std; int Find_Max_Divisors(int p[]) { int count = 0, max = 0; for (int i = 0; i < 4; i++) { for (int j = 1;...
61,668,403
61,669,944
boost text serialization version (15 vs 18)
I have a custom class containing only a std::map<std::string, int>. I'm trying to serialize that using boost::serialization. I create an object with the data {"foor":13} (this is the map in my custom object). Boost serializes that as 22 serialization::archive 15 22 serialization::archive 15 0 0 0 0 1 0 0 0 4 foor 13 S...
The first serialized sample looks to be invalid alltogether. Secondly, let's check that the 15 and or 18 are the archive version numbers: #include <boost/archive/text_oarchive.hpp> #include <iostream> int main() { unsigned v; { boost::archive::text_oarchive oa(std::cout); v = oa.get_library_vers...
61,668,898
61,669,002
Storing large amounts of compile time constant data
I hope that this question hasn’t been asked before, but I couldn’t find any answer after googling for an hour. I have the following problem: I do numerical mathematics and I have about 40 MB of doubles in the form of certain matrices that are compile time constants. I very frequently use these matrices throughout my pr...
I am not sure if this can cause problems with too much data on the stack, due to the initialiser list. There should not be a problem assuming it has static storage with non-dynamic initialisation. Which should be the case if math::matrix is an aggregate. Given that the values will be compile time constant, you might...
61,669,143
61,669,271
Debug assertion failed with list
Hello everybody can you help me? the problem is that when a person enters a element from list he can insert before this element elements from another list, but I constantly knock out mistakes. Maybe someone will help? It looks like: 3 6 7 9 user enters 6 he can create another list like 8 7 5 and output is 3 8 7 5 6 7...
I don't know what your code is doing, and maybe there are other problems. However, the runtime error you get is caused by auto it2 = lis.begin(); while (*it2 != el1) { it2++; } --it2; When *lis.begin() == el1 then you never increment it2 and then decrement it, but you cannot decrement the begin iterator. Usually t...
61,669,173
61,716,634
Does Anaconda have any libraries for PCL for C++ for using in windows?
I am currently looking for best method to install pcl libraries in my windows system. I dont know if anaconda offers any pcl libraries for c++?
PCL offers prebuilt binaries for windows (AllInOne installer) at releases. Latest binaries: 1.10.1 Since your question stated "best method to install pcl libraries in my windows system", I think it's worth mentioning this non-anaconda option.
61,669,187
61,669,510
'const' keyword changing semantics
I attempted today's leetcode challenge in C++. You have to find cousins in a binary tree. Here's my code. template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; class Solution { public: bool isCousins(TreeNode* root, int x, int y)...
Removing the const in this case changes the meaning of the code, by changing which function is selected in overload resolution. Consider the following overload set and call: void f(int const &) { std::cout << "i"; } void f(bool) { std::cout << "b"; } int main() { int const i = 42; f(i); // prints i f(42);...
61,669,746
61,669,849
Pointer initialization is overriding the value
Dog.h class Dog { public: int *pVal; Dog(int); ~Dog(); static int GetVal(Dog d); }; Dog.cpp Dog::Dog(int val) { pVal = new int; *pVal = val; } Dog::~Dog() { delete pVal; } int Dog::GetVal(Dog d) { return *(d.pVal); } Test Dog fido(20); CHECK(Dog::GetVal(fido) == 20); Dog rex(21); CH...
When you make this call: Dog::GetVal(fido); you make a copy of the Dog in the argument of GetVal. The default copy-constructor is invoked which only makes a shallow copy of pVal. So when the copy goes out of scope, the memory pointed at by pVal is deleted, which deletes the memory pointed at by fido. One fix would be ...
61,669,935
61,670,006
Decrement a for loop onto a vector
My instructor wants us to decrement from 5 to -4 using a for loop, then push those numbers onto a vector. I don't understand why it's not decrementing. The compiler says std::out_of_range The for loop obviously works without the vector involved, however I don't understand why it doesn't with it...? int main() { vecto...
The loop is decrementing fine. Your use of the vector's at() method is simply wrong. You are getting the runtime error because the numbers you are pushing into the vector are not valid indexes into the vector, so you are indeed going out of bounds. at() performs bounds checking, throwing a std::out_of_range exceptio...
61,670,010
61,672,553
Can I concatenate a std::tuple of Eigen::Vectors?
If I have a std::tuple of statically allocated Eigen::Vectors (from the popular Eigen library), for example std::tuple<Eigen::Vector2f, Eigen::Vector3f, Eigen::Vector2f> Is there a way I can turn this into a single Eigen::Vector7f (i.e., Eigen::Matrix<float, 7, 1>) of the three vectors concatenated? It feels like I sh...
You can write: template<int R1, int R2, int R3> auto foo(std::tuple< Eigen::Matrix<float,R1,1>, Eigen::Matrix<float,R2,1>, Eigen::Matrix<float,R3,1> > t) { Eigen::Matrix<float,R1+R2+R3,1> res; res.template block<R1,1>(0,0) = std::get<0>(t); res.template block<R2,1>(R1,0) = std::get<1>(t); ...
61,670,268
61,670,353
How to efficiently replace characters in an std::string with iterative values from another std::string?
I have the following strings: std::string str1 = "1234567890"; std::string str2 = "B-XXXX_XXX_V-XX_X"; I want to loop through str2 and replace every occurrence of X with the subsequent value from str1, resulting in: B-1234_567_V-89_0. I have a semblance of a solution below, but it's not very efficient (it worked at o...
Your current implementation treats each individual unit of the string as a std::string rather than as a single char, which introduces some unnecessary overhead. Here's a rewrite that uses chars: int x_ind = 0; for (int i = 0; i < str2.size(); i++) { if (str2[i] == 'X') { // Don't assign str2[i] to a char; us...
61,670,324
61,670,416
How do I trim my vector with a specific member variable?
I have a class Book consisting of string title, int pages, genre. I made a few book objects and I'd like to return a Fantasy genre book that also has the second most in pages. Here's what I have done: std::vector<Book> sortPages(vector<Book> books){ //sorts books in descending order sort(...
You can use std::partition to get all the Fantasy books: auto i = std::partition(books.begin(), books.end(), [](auto const &book) { return book.genre == "Fantasy"; }); and then use std::nth_element to get the book with the second largest numbe...
61,670,669
61,670,688
Error in implementing String comparison in C++
My string s contains 0's and 1's. Why are the values of Ascore and Bscore zero, and not incrementing given the conditions below? int main() { long long int n; string s; cin>>n; // 3 cin.ignore(); long long int siz = 2*n, Ascore = 0, Bscore = 0; cin>>s; // 101011 ...
A string is composed of chars, so you need to compare against char literals, not ints. e.g. s[i] == '1' instead of s[i] == 1
61,671,255
61,673,657
Is it possible to receive a pointer to C function in Rust and call it back?
I'm learning about interfacing Rust and C++ (using the C interface). This is an example from Mozilla's guide for Rust on Android: use std::os::raw::{c_char}; use std::ffi::{CString, CStr}; #[no_mangle] pub extern fn rust_greeting(to: *const c_char) -> *mut c_char { let c_str = unsafe { CStr::from_ptr(to) }; le...
You can call freely, but unsafely, from C to Rust and from Rust to C. From Rust to C: write a extern "C" block with the prototypes of the C functions. From C to Rust: write the Rust function with a #[no_mangle] extern "C" prefix. You must ensure that any value received or returned is FFI friendly: basic types or repr(C...
61,671,287
61,671,331
Is there a possible way to set a c++ array size to the return value of a function
I'm pretty new to C++ so please bear with me: I am looking to set an array's size to the output of a function, for example: //this is not the actual function, (go figure) int getSizeInt(int size) { return size; } int main() { char charArray[getSizeInt(6)]; // Error: *function call must have a constant value in...
Is there a possible way to set a c++ array size to the return value of a function Yes. The size of an array variable must be compile time constant. A function call is a constant expression if the function is constexpr and its arguments themselves are constant expressions. Your function does not satisfy those constrai...
61,671,373
61,671,409
is < map > threadsafe for read/write at different locations?
I remember that someone tell me, if I had a map,which already has "key1" and "key2",then using thread1 to read key1, and thread2 to write "key2"(only to change "key2"'s value,not change "key2" to "key3").That will not cause any threat or mistake. But if now the map only contain "key1" , using thread1 to read key...
Is that correct? Yes, it is correct. Both for ordered and unordered standard maps. Although, there is no "hash structure" in an ordered map, and it is not possible to change the key of an element in either container.
61,671,694
61,672,330
Cutting and reorganizing numbers in a file with C++
I have the following code #include<iostream> #include<cmath> #include<string> using namespace std; #include<fstream> #include<iomanip> #include<cstdio> int main() { //Here the code that creates the file benchmarks_cleaned.dat int ncol = 16; //number of data per row double datos[ncol]; char aux2; double aux3; int i...
Your calls to get(...) are catching blank spaces and missing the 'X'. There's no need for get. Get rid of aux2 and change the while loop to: while(benchmarks2 >> aux3)
61,671,893
61,672,006
Why isn't desctructor called after function return?
so I'm starting to learn c++ and got around pointers, constructors, destructors, allocation, heap/stack memory. I have already figured out that local variables created inside functions are allocated on the stack and destructed (or deleted?) after the function return, unless we allocate it on the heap using new and thus...
why is Teest class desctructor not called on this code example after go() returns? Because of the same reason why no copy constructor was called. One object was created, and it was destroyed at the end of main. The copy from the local variable into the return value was elided. The variable local to go was created dir...
61,672,049
61,678,089
Why does false sharing still affect non atomics, but much less than atomics?
Consider the following example that proves false sharing existence: using type = std::atomic<std::int64_t>; struct alignas(128) shared_t { type a; type b; } sh; struct not_shared_t { alignas(128) type a; alignas(128) type b; } not_sh; One thread increments a by steps of 1, another thread increments b. Inc...
Non-atomic memory-increments can benefit from store-forwarding when reloading its own stored value. This can happen even while the cache line is invalid. The core knows that the store will happen eventually, and the memory-ordering rules allow this core to see its own stores before they become globally visible. Store...
61,672,370
61,672,401
Why does class member variable partially work After global class array constructor executing?
I declare and define a global class array Test arrs[] ={ {"1"}, {"2"} }; I make sure that constructor of every element in the array has executed. My Test class declaration is in the file Test.h: #pragma once #include <iostream> #include <string> using namespace std; class Test { public: string from, suffix; T...
Your method parameter is shadowing the actual member variable 'from'. Change you code to: #include "test.h" Test::Test(string variable_not_called_from) { from = "abc"; suffix = "123"; cout << "Test constructor from = " << from << " suffix = " << suffix << endl;// diagnostic } Then you will see the result y...
61,672,440
61,675,412
hexadecimal NULL inside the string
const char* sendbuf = "ABCD\x58\x34\x00\x84"; But the result is ABCDX4 X == \x58 , 4 == \x34 So my string got cut off in the middle. I understand it is because of \x00. So how to have hexadecimal null \x00 in the middle of string ? I am trying to send UDP packets.
Issue with: const char* sendbuf = "ABCD\x58\x34\x00\x84"; is that you lose size information. You would keep that information, if you use C-array const char sendbuf[/*8+1*/] = "ABCD\x58\x34\x00\x84"; or std::string literals: using namespace std::literals; const auto sendbuf = "ABCD\x58\x34\x00\x84"s; // std::string with...
61,672,566
61,672,643
If I input a float number when input is expecting an integer number, it updates the next float number value. Why does that happen?
I am a complete newbie to C++ programming. So, I was just trying out some basic C++ coding and I wrote the below program: #include <iostream> using namespace std; int main() { int number1; float number2; cout << "Enter number1 (integer)\r\n"; cin >> number1; cout << "Enter number2 (float)\r\n"; ...
You are passing float to an int. cin stops reading as soon as it sees '.' and the remaining number 7 is automatically taken as the input to the next cin. You may want to flush the input buffers after each read if you think that the values may not match the expected type. std::cin.clear(); and std::cin.ignore(100,'\n')....
61,672,608
61,672,627
vect.hpp:13:33: error: declaration of ‘operator<<’ as non-function
I have this error vect.hpp:13:33: error: declaration of ‘operator<<’ as non-function for the code : #include <iostream> template<unsigned d> class Vect{ protected: double * coord; public: Vect() {for(int i=0, i<d, i++){*(coord+i)=0;}} ~Vect(){delete coord; coord=nullptr;} Vec...
The friend declaration refers to the instantiation of the operator<< but there's no primary template declaration. You need to declare the operator template in advance. e.g. // forward declaration template<unsigned d> class Vect; // primary template declaration of operator<< template<unsigned d> std::ostream & operator...
61,672,641
61,672,698
Converting const char to std::string for title
I am working with gnuplot. In the header file I have the following function: void PlotPath(Gnuplot& gp, const char* title, bool first_plot = true, bool last_plot = true); Then, in the cpp file: template <typename T> void Path<T>::PlotPath(Gnuplot& gp, const char* title, bool first_plot, bool last_plot) { std::vec...
Make your argument std::string. std::string has a constructor that takes a const char* so it should not be a problem.
61,672,657
61,672,738
Class Template non-type member access in sub-class
I have a Matrix class template which looks like this: using matrix_size_t = unsigned int; using matrix_data_t = double; template <matrix_size_t row, matrix_size_t col> class Matrix { protected: matrix_data_t m_matrix[row][col]; //more code irrelevant to the question... } I also have a subclass template SquareMat...
I don't know if this is the right thing to do. Yes. You can also use this->m_matrix instead. m_matrix is a nondependent name, which won't be looked up in the dependent base class Matrix<size, size>, it depends on the template parameter size. Making m_matrix dependent as Matrix<size, size>::m_matrix or this->m_matrix,...
61,672,708
61,684,254
Python script hangs after SIGINT "terminate called without an active exception when"
I have a python app that collects data from a sensor. The driver for the sensor is closed source and I have written a wrapper around it to simplify its use. The entire application runs on Linux. The program has the following flow. Python call into driver setup. This starts one std::thread that I control which polls t...
After some more digging around looks like the base driver is registering a handler for the SIGINT signal and calling exit before I have a chance to cleanup my threads.
61,672,848
61,674,221
How does a QCloseEvent propagate?
I have a MainWindow derived from QMainWindow and I re-implemented the closeEvent() handler. void MainWindow::closeEvent(QCloseEvent *event) { if (this->okToContinue()) { this->writeSettings(); //event->accept(); QMainWindow::closeEvent(event); // will work just fine even if this line omitted...
What a nice question. (I never have thought about this.) After this raised my curiosity, I investigated a bit. That's the nice about OpenSource software – if you are in doubt just have a look into source code. So, I digged a bit on woboq.org: First I looked for closeEvent() in qmainwindow.cpp but I couldn't find it any...
61,673,067
61,673,241
I am facing problem in creating a Graph implementation
The code is only accepting 2 values even though I am providing limit (n-variable) other than 2. I am not able to understand what's going wrong in Graph() #include "iostream" using namespace std; class Node { private: int data; Node *next; friend class Graph; }; class Graph { private: Node *hea...
The problem is that you're not initializing most of the Nodes before you try to set their data. You're trying to use the pointers without making them actually point at anything first. You can fix this by initializing the Nodes in the loop. Here's an updated version of your loop: for (int i = 0; i < n; i++) { cou...
61,673,212
61,673,392
Appending a number to enum to get other enum
I want to get the enum value in a for loop, by appending a number, like enum example { Example_1, Example_2, Example_3, . . . Example_n }; example x; for (i = 0; i < n; i++ {x = Example_ + i; // if i = 5, I need Example_5 } I want this implementation in C++11
If you have an Example_0 in the enum, then Example_0 + 5 will give you an integer value equivalent to Example_5. Enums are just integers. All this assuming that you don't explicitly assign a value to a certain enumeration constant - that's another story.
61,673,327
61,947,836
how can i pass ifstream and ofstream to same function objects in C++?
My use case is to create a function which takes a fileName , an ifsttream/ofstream object and then opens the file for reading/writing accordingly in the given filestream object. also to check whether the operation was successful or not and if successful, returns the filestream object. My implementation is as following...
So, as others have suggested, this is due to the fact that std::ifstream doesn't inherit from std::fstream. Rather, it inherits from std::istresm instead. std::fstream on the other hand inherits from std::iostream. So you can't really do that. Some options you have to work around: Templates (as others have mentioned):...
61,673,336
61,690,694
Online sorting/percentile
My question is: the program generates a new number as time goes. Every time I want to know the percentile of the number in the sequence. I think we need some online sorting program, so that the process is fast (log n I suppose). I vaguely remember heap sorting would do the job. I wonder whether there are any existing p...
You're looking for an order statistic tree, a data structure that stores items in sorted order and lets you determine the rank (position in sorted order) of new items. Each operation takes time O(log n) to complete, since it's layered on top of a balanced tree (typically, a red/black tree). Hope this helps!
61,673,615
61,689,106
Error : The term 'bootstrap-vcpkg.bat' is not recognized : While Install C and C++ libraries for Visual Studio 2017 on Win10
I am trying to install C and C++ libraries on my Windows 10 Machine for VS-2017,and encountered the following vcpkg- error. This is the first time I am installing it on my machine.By the way I am using Windows Powershell. I searched online forums alot but not able to figure out whats wrong with my machine or the packag...
As already mentioned in the comments section, please follow the document : C modules for Windows devices instruction commands one after the other. git clone https://github.com/Microsoft/vcpkg cd vcpkg .\bootstrap-vcpkg.bat .\vcpkg install azure-iot-sdk-c:x64-windows .\vcpkg --triplet x6...
61,673,728
61,677,693
How to make a program with 2 windows that open simultaneously upon runtime in Qt?
Initially I made it in the main of the window I had made earlier
There is nothing complicated to open a 2nd window (or dialog) with the main window. To demonstrate this, I made an MCVE. C++ source testQMainWindowWithQDialog.cc: // Qt header: #include <QtWidgets> class Dialog: public QDialog { private: QVBoxLayout _qVBox; QLabel _qLbl; public: Dialog(QWidget *pQPare...
61,673,920
61,676,651
I am a novice JNI,Why doesn't my android jni C ++ try block catch an exception
I am a novice JNI,Why doesn't my android jni C ++ try block catch an exception,The code crashes when and the app crashes without jumping to exception handling this is my code Activity re code Receive H264 data with queue at JAVA layer Start a decoding thread and continuously take a frame of H264 data packets from the...
You should carefully read the documentation of avcodec_receive_frame: Return decoded output data from a decoder. Parameters avctx codec context frame This will be set to a reference-counted video or audio frame (depending on the decoder type) allocated by the decoder. Note that the function will always c...
61,675,039
61,676,901
Sorting two different vectors of class object together
Let's say I have a code like this #include <iostream> #include <vector> using namespace std; class player{ protected: int agility; int strength; int accuracy; string teamcolour; public: void shoot(){}; }; class playerA:public player{ public: playerA(int a,int s,int ac){ agility=a; strength=...
Define this compare function outside main: bool compare(player a, player b){ return a.agility > b.agility; } and call sort: std::sort (teamA.begin(), teamA.end(), compare); std::sort (teamB.begin(), teamB.end(), compare);
61,675,131
61,680,371
How to make 'this' into std::unique_ptr?
In the following code how do I return the same object from the Object::get function below. Please look at the comments in that function. The function returns a std::unique_ptr of new Object with the given id. But if the id is the same as the object's id or if the object's id was set to error, then the this pointer(i.e....
The answer to your question is straightforward. return std::unique_ptr<Object>(this); However, as Nicol pointed out in his answer, this is almost certainly NOT what you want. Consider the following code: Object foo("foo"); foo.get(); Boom! You've just called free on some memory that was not allocated on the heap...
61,675,172
61,675,805
Accessing members of base classes in the derived class through runtime indexing
Consider the following code #include <array> #include <iostream> template <std::size_t> struct base { std::size_t value; }; struct derived: base<0>, base<1> { using pointer_type = std::size_t derived::*; static constexpr std::array<pointer_type, 2> members{{ &derived::base<0>::value, &der...
This looks like a GCC bug. Your original code produces the expected output with Clang. One workaround for GCC that I was able to find is to turn members into a static member function: static constexpr array_type members() noexcept { return {&base<0>::value, &base<1>::value}; } constexpr std::size_t& operator[](st...
61,675,421
61,675,689
Why can't I print contents of vector of objects using a ranged for loop?
I'm a beginner and I solved an exercise involving 10 pie eaters with number of pies eaten set by user input. 1st task: Display Contestant number and pies eaten - Solved; 2nd task: Find winners with most pies eaten and list all - Solved; 3rd task: Find losers with least pies eaten and list all - Solved; Final task: So...
That is because the while loop never ends, since you have initialized the value of swapped = true in the while loop condition, the value of swapped becomes true when the inner for loop ends and the while loop is reprocessed. The program never leaves the while loop. thus, the line never executes SortPieEaters(pie_eater...
61,675,979
61,676,184
trying to understand condition variables
I have read about condition variables to signal between two or more threads. Now I am trying to understand some code I have. I have (simplified): class Class{ void put(Something&& something){ { std::lock_guard<std::mutex> lock(a_mutex); // Do the operation here some_opera...
For example let's say that the put function is called and it notifies but no thread is waiting because get has not been called. What happens? docs says: *If any threads are waiting on this, calling notify_one unblocks one of the waiting threads. If any, then if no nothing special happens. Then let's say get gets...
61,676,328
61,676,481
How to use Table.select() in MySQL Connector/C++ 8.0
According to the documentations here: https://dev.mysql.com/doc/dev/connector-cpp/8.0/classmysqlx_1_1abi2_1_1r0_1_1_table.html and here: https://dev.mysql.com/doc/x-devapi-userguide/en/sql-crud-functions.html, I need to construct a ProjectedSearchExprStrList if I wanna call mysqlx::Table.select(). What does this Projec...
ProjectedSearchExprStrList is defined here (11.7 Other EBNF Definitions). Expression is defined here (Chapter 12 Expressions EBNF Definitions). I wasn't able to find Alias, but I guess it should be the same as ID as defined in Chapter 12 Expressions EBNF Definitions (last link). Basically, it's pretty much the same yo...
61,677,021
61,683,937
How to call a function with types known at runtime
After loading a dynamic library and GetProcAddress, one typically get a function pointer of type void*. To call the function, when doing it at compile time, one would cast the pointer into the correct pointer type needed. However, if the type is not known at compile time but at runtime instead, and there's many possibi...
In another answer I said that https://dyncall.org/ looks to be what is needed. That answer was deleted, despite comments saying it was correct. Re-posting the information here in case anyone else needs it.
61,677,180
61,677,405
My Payroll program outputs the wrong calculation for the total of salary
I am currently working on a prototype payroll system. Every time I put the required information for the calculations, it always outputs the wrong information (I always check with a calculator). It doesn't have any errors or warnings so I think the problem is how I format the code. Can someone please teach me how to f...
I can see 2 big mistakes in your code, but without examples of input and output it is possible I missed more. The biggest error is that you are using long - which is an integer type! You need to use double so that the decimal part of the salary will be preserved in the calculation. For example, using long 10 hours of o...
61,677,262
61,692,772
Read only variable is not assignable
I am thinking this is a later Xcode issue (I am using Xcode 11) as this code was fine previously in older versions. In my main.mm file I have the following; int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString * path = [[NSBundle mainBundle] pathForResource: ...
It doesn't appear that you've done anything since your previous question, SO does really require you show some effort. Let's step through your original code to hopefully help understanding of the issue: I am thinking this is a later Xcode issue (I am using Xcode 11) as this code was fine previously in older versions. ...
61,677,319
61,678,510
When executing the code for the computation of cos x using the Taylor Series, the answer comes out to be 1 no matter what I put the angle as
I'm sorry to be taking up some of your valuable time. I'm just a beginner programmer and was trying to compile a relatively simple code (for you guys). In my opinion, I have got my functions right, but my function 'output' 's declaration is causing some issues and I'm finding it difficult to find out what did I do wron...
There are several issues in your code. First of all, main program { ... } is not a valid entry to a C++ program (which I assume you meant to use as the main function). Every C++ program must contain an int main() { } function which is the start point. So you would have to rewrite it as following: int main() { calculat...
61,678,175
61,678,227
Recursive search in binary tree
I am a beginner and i am stuck on a function that searches unordered binary tree for given key. Node consists of value and pointers to left and right node. Here is my code: node *btree::search(int key, node *leaf){ if(leaf != NULL) { if(key == leaf->value) { return leaf; } ...
It's quite a common beginner mistake. Your recursive function returns a node pointer, but when you make the recursive calls you ignore the return value. search(key, leaf->left); search(key, leaf->right); It should look like this node* ptr = search(key, leaf->left); if (ptr != NULL) return ptr;...
61,678,263
61,679,664
Close OleCreatePropertyFrame externally
I am using OleCreatePropertyFrame to display property pages of the webcam. But, I wasn't able to make the dialog modal or close the frame externally when closing the camera. OleCreatePropertyFrame( NULL, // Parent window 0, 0, // Reserved lpcostr, // Capti...
OleCreatePropertyFrame is standard API for modal dialog box meaning that it is supposed that the mesasge box is displayed until closed interactively. That is, you are not supposed to be able to close it from code. This function always creates a modal dialog box and does not return until the dialog box is closed. One ...
61,678,546
61,678,624
Boost.Asio lambda capture failed to compile
I found that I can't move an Asio socket object boost::asio::ip::tcp::socket&& to a lambda for the boost::asio::write() function. I trim the case into a test program below in order to try the compiler results. If I uncomment the boost::asio::write(sock,... line, both clang and gcc blamed that there is no sock.write_som...
boost::asio::write takes sock by non-const reference. It means that sock is affected by this function. sock is data member of closure generated by lambda. By default, function call operator of closure is marked as const. So you are allowed only to pass sock to other const functions. If you want to let lambda modify...
61,678,608
61,678,853
I get a linking error (LINK 2019) when I try to augment a class with template
I'm trying to build a simple heap data structure for practice. When I build the version for double it works fine. class heapt { public: heapt(); heapt(std::initializer_list<double> lst); void print_heapt(); private: int size; int length; double* elem; //points to root }; Its constructors work...
In your templated class declaration you are using heapt(std::initializer_list<double> lst); but in your definition you are using std::initializer_list<Elem>. You should change the declaration to heapt(std::initializer_list<Elem> lst); You are still missing definitions for print_heapt and build_heapt but otherwise it sh...
61,678,630
61,678,878
Is returning std::pair superior to returning std::vector of size 2?
The title reflects my question, is returning std::pair any superior to returning std::vector of size 2 for same variable types? As example; return std::make_pair(1, 92); vs std::vector<int> myV{1,92}; return myV;
If you have the choice between these two, i.e. you know you're returning two elements, then - probably, yes. Why? More exact semantics. Returning a vector implies that, potentially, there are many output values. std::vector is a "heavier" class - typical implementations allocate memory on the heap for storing element ...
61,678,718
61,678,857
Declaring an optional class field using templates in C++
I am using templates in an embedded environment where I need to statically declare everything. I would like to know if there is any way of declaring an optional field in a class using templates or similar technique. Now in one of the classes I am trying to do something like this ... template<typename Filter, typename...
You can partly specialize it: template<class Filter> class MeasurementChannel<Filter, void> {}; Alternatively, to not copy all the class code to partial specialization, you can only specialize the relevant part: template<class Compensation> class CompHolder { protected: Compensation comp; // don't start identi...
61,678,808
61,679,004
Can't find out why im getting Segmentation fault
im new to cpp and i am trying to solve an exercize but im getting Segmentation fault. first part of code consist in initializing an vector of vector.(Task 1) then there is task2. I try to print Task 2 before the while cicle but it never prints.So i guess the error is in the first part of code! below you can find the co...
You need to learn to use the debugger, as it will very quickly tell you where it segfaulted. Program received signal SIGSEGV, Segmentation fault. main () at x.cpp:25 25 if(mat[i][j]==1){ (gdb) p i $1 = 5 (gdb) p j $2 = 5 You are attempting to access outside the bounds of mat. mat[i][j]==1 is not true for the 0...
61,678,826
61,968,596
SDL2 program eats a lot of memory when minimized
I'm just trying to create a simple SDL2 window with a simple renderer. When I debug it, it runs normally, the memory still normal. But when I minimize it, press the minimize button then suddenly the memory just keep going up and only when i reopened that window then the memory goes back normal. Memory spike The code: #...
switch (m_event.window.event) { case SDL_WINDOWEVENT_MINIMIZED: while (SDL_WaitEvent(&m_event)) { if (m_event.window.event == SDL_WINDOWEVENT_RESTORED) { break; } } break; ... So when you minimize the Window, SDL keeps waiting for events. No further code could memory...
61,678,963
61,681,278
Is there a C++ function to sort a std::stack?
I have a std::stack in my code and I need to sort it. Is there any built in function to do this? As std::stack does not have std::end. Can I use std::sort or would I have to go to the same old approach of using an auxiliary stack to sort the original stack?
There could have been a std::stack::sort template using two auxiliary stacks and polyphase merge sort (time complexity O(n log(n)), see below), or the template could have been implemented based on the underlying container type: std::deque, std::list, or std::vector, since the container type can be specified for std::st...
61,679,097
61,679,633
C++ Singleton instantiate with overloaded operator -> possible?
Today I'm working on a singleton test case in c++. The singleton is working fine but I would like to instantiate the static object when the user try to access a member of it, so if the variable isn't created when we try to access a member of it, it will not crash instead it will simply generate my singleton. Here's my ...
PDG::_instance is a pointer to PDG so -> simply dereferences the pointer and you can't override the behaviour. To override the -> operator you must call it on the class directly not on a pointer: (*PDG::_instance)->SePresenter(). To preserve your desired syntax and to remove the undefined behaviour from dereferencing t...
61,679,758
61,682,135
Record ownership in symbol tables
I am implementing a symbol table as described in the dragon book: class SymbolTable { std::unordered_map<std::string, Record> table; SymbolTable* parent; public: SymbolTable(SymbolTable* p) : parent{p} {} const Record* lookUp(const std::string& name) const { for (auto* scope = this; scope != n...
The lookup for names in records usually doesn't follow the bottom-up approach implemented using a parent pointer from scope to scope. (In fact, that simple datastructure may not be entirely applicable to scopes either; as soon as you introduce lexical closures, your scope relationships become more complicated.) Althoug...
61,680,255
61,734,354
C++ libhiredis with libev and custom event loop
My application uses libhiredis with libev backend. I need to send Redis async commands and process the resulting Redis async callback. However, unlike the simple example from here I cannot use the default event loop. The following code approximates the example with a custom event loop. However, when compiled with only ...
I found out that hiredis community has their own GitHub instance where I can ask questions. Since I had't yet received the answer here, I asked there. The answer can be found at https://github.com/redis/hiredis/issues/801#issuecomment-626400959
61,680,473
61,682,967
Infinite looping when inserting an item into a linked list
Trying to insert a value into a linked list, but it enters an infinite loop when it is passed through the 2nd time. Been scratching my head for an hour for this problem. Is it due to variable placement issues or just algorithm in general? Edit 1: Changed NULL to nullptr, created a counter that tells the value of karak ...
Object need to be created inside the loop to prevent the list from becoming a circular linked list. So I added list = new List(); inside the loop so the program can create the objects inside the loop. #include <iostream> #include <stack> #include <string> using namespace std; struct List { char karak; List* nex...
61,680,983
61,700,575
LoadLibrary returns 126 when loading a dll in runtime
I'm having MFC dll file that is trying to load another dll during runtime using LoadLibrary function. The code below is working fine in a console app with MBCS character set. However the same code that I've used in MFC dll is not working. The GetLastError is trying always returning 126 which is Module NOT Found. My ...
I already found the root cause now. I forgot to tell that I'm attaching the dll in my application process while doing the debugging. The application is requiring that the Soft.FXX.dll should be in the same directory with it. I really thought that feeding the whole dll path to LoadLibrary function is enough.
61,681,868
61,682,012
API macro for making C++ library
I am a beginner in C++. I have created a CMake library project, and I added 2 libraries, one is called mosaic (shared) and mosaic_s (static). And the problem is that how can I use macros to automatically set a macro for __declspec(dllexport) when building shared library and set it to nothing when building a static one....
Define a symbol in your make file that will tell you if it is shared or not and then you can use the preprocessor like #ifndef SHARED #define EXPORT #else #define EXPORT __declspec(dllexport) #endif and then in your code you would have EXPORT whatever_you_are_exporting and if you have defined SAHRED in your make file...
61,681,965
61,729,294
Having trouble creating data buffers for custom objects oneAPI
I am new to oneAPI and similar frameworks, so I am having trouble with data management using SYCL data buffers. My task is to find substrings in a given string using Aho-Corasick algorithm. My Idea was to build a trie and after that submit a kernel that would parallelly find substrings in the trie. So for that I crea...
if I understood correctly, you are attempting to use std::unordered_map, std::string and std::set in device code. I'm not an expert on Intel-specific oneAPI SYCL extensions, but in pure SYCL 1.2.1 this is not allowed and I would be surprised if this works in DPC++. The SYCL 1.2.1 spec does not really define how SYCL in...
61,683,016
61,683,100
how to create a variable-template?
#include <iostream> using namespace std; template<int base, int x> struct Power { static constexpr int a = base * (Power<base, x - 1>::a); }; template<int base> struct Power<base, 0> { static constexpr int a = 1; }; ///////////////////////////////// I failed in creating a variable-template here. templat...
using is used for declaring type alias. Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types. As variable_template it should be template<int base, int x> constexpr int power_v = Power<base, x>::a; LIVE
61,683,371
61,684,582
Sentinel node in doubly linked list
I'm working on implementing my own doubly linked list. I have decided to use sentinel node at the end of the list which will store pointer to the last node in the list and the last node will store pointer to the sentinel node. Is this a good approach or the sentinel node should be used in different way? My code: templa...
That is a way to use a sentinel node, but ask yourself: what makes the last node special in a doubly-linked list? A doubly-linked list has symmetry; forward and backward look the same, modulo some naming differences. Putting a sentinel node after the last node breaks this symmetry, unless you also put a sentinel node b...
61,683,550
61,683,628
Not able to understand the meaning of this code
I dont understand what the following code is doing auto sgn = [&](int x) { if (x > 0) return 1; else return -1; }; What is the role of ampersand here? Is it a pointer? And is this block a structure or something like that? I came across this block of code in codeforces round 636 division 3 editorial.
The & here means that the lambda captures all variables by reference. The lambda returns 1 or -1 depending on the value of the argument x, so the capture really doesn't actually matter here.
61,683,579
61,684,333
Lua C API - loading multiple files with variables and functions of the same names
Say I have two Lua files which I'll be using from the standard Lua C API, that share a common library: common.lua function printHello(name) print("Hello from " .. name) end file1.lua require "common" local scriptName = "file1" function doSomething() printHello(scriptName) end file2.lua require "common" local...
Here's how you do it in pure Lua 5.1: file1_env = setmetatable({}, {__index = _G}) local file1_chunk = loadfile('file1.lua') setfenv(file1_chunk, file1_env) file1_chunk() file2_env = setmetatable({}, {__index = _G}) local file2_chunk = loadfile('file2.lua') setfenv(file2_chunk, file2_env) file2_chunk() file1_env.doSo...
61,683,603
61,683,733
Confusion between "rvalue" and "rvalue reference" in book
(I searched for [c++] "functional programming in c++" book, which give only 4 unrelevant results.) I'm reading Functional Programming in C++ from Ivan Čukić, and at page 118 there's a sentence which I'm not sure I've understood. The section is about rvalue and lvalue overloads of member functions, and the sentence is t...
the word in bold really puzzles me, in that the sentence seems meaningful to me only if I remove that word. I agree. IMO to be more precise the sentence should be The second overload will be called on objects from which you're allowed to stead the data -- rvalues (prvalues or xvalues). Rvalue reference is used for ty...
61,683,761
61,688,035
New instance of class in a shared memory segment C++
I'm actually trying to step-up in thread, process and shared memory in C++ but I'm actually stuck with my Inter Process Communication. I decided to use a message queue cause i already used some in past project but never with multiple process. Here is my problem, I can't get register events from different process. I thi...
I would use a managed memory segment so you can "just" construct your types in shared memory (note: be sure they are POD or take a shared-memory allocator to properly handle any dynamic allocation/reference). #include <boost/interprocess/managed_shared_memory.hpp> #include <iostream> struct MyQueue { /* */ }; namespa...
61,684,068
61,684,240
what does int numbers[n+2]; statement do?
#include<iostream> int fastFibonacci(int n) { int numbers[n+2]; // int numbers[n]. numbers[0] = 0; numbers[1] = 1; for (int i = 2; i <= n; i++) { numbers[i] = numbers[i - 1] + numbers[i - 2]; } return numbers[n]; } int main() { int n; ...
int numbers[n+2]; is the declaration of an array of ints with space for n + 2 ints, this is a variable lenght array and is not part of C++ standard, though some compilers allow it it's not somenthing you should use. If you need a variable lenght array use std::vector. With int numbers[n+2]; if n is equal to 0 you still...
61,685,096
61,685,130
How to access pybind11 array_t<> data pointer in debugger
I would like to access the data pointer for a pybind11::array_t<T> typed NumPy array wrapper, while stepping in a debugger. As below, the debugger does not know the type of array_t<T>, so the data(...)/mutable_data(...) accessors are not available. (lldb) p o (pybind11::array_t<unsigned long long, 16>) $24 = { pybind...
Based on the implementation of array_t::data in pybind11's numpy.h, a solution is to use the pybind11::detail::array_proxy to access the data pointer: (lldb) p ((uint64_t*)pybind11::detail::array_proxy(o.m_ptr)->data)[652] (uint64_t) $26 = 87112
61,685,472
61,687,010
UE4: Actor disappears after play is hit
I am using Unreal Engine version 4.25. I have created an actor and placed it on a blank template. The actor is visible in the editor but becomes invisible once the play button is hit. I am trying to move the object in circles with my code. Here's the code: MyActor.cpp #include "MyActor.h" // Sets default values AMyAct...
This fixed it, I did not create a mesh: https://www.youtube.com/watch?v=30XEdBoPw6c I added the following: .cpp AMyActor::AMyActor() { ... Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root")); RootComponent = Root; Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh")); Mesh->Att...
61,685,613
61,685,654
Encryption with substitution cipher
I am replacing each letter of the alphabet with another letter of the alphabet. For example, each 'a' gets replaced with a 'Q', and every 'b' gets replaced with a 'W'. I have written code to encrypt the sentence bellow. #include<iostream> #include<string> #include<cctype> using namespace std; int main(){ string ...
Your encrypted string is empty, so indexing into it with .at() throws an exception. To solve this problem, you could append the characters, like this: for(int i=0;i<original.length();i++){ if(std::isalpha(original.at(i))){ encrypted += key.at(alphabet.find(original.at(i))); } else ...
61,685,616
61,687,884
How does one pass numeric variables in QXMLStreamWriter functions?
I am using a QXMLStreamWriter class to write data to an XML file. When dealing with variables that contain numeric values and passing them to the writeTextElement() function before converting them to a string using QString(), I get undesired results.
I believe QString::number() is the correct way to do this. int numVar = 10; QString nameVar = "elementName"; xmlStreamWriter.WriteTextElement(nameVar, QString::number(numVar));
61,685,790
61,687,131
Using find() in a vector of maps, C++
For my class, I need to find usage for the following structure: vector<map<int, map<char, float>>> My idea was to create a basic encryption method, that's output depends on the date of use (each day has its own coding for the characters throughout the year). The outer map of the vector represents the months, and the in...
You didn't test your constructor. Here: for(int i = 0; i < month_lenght[j]; ++i){ map<char, float> char_value; ... char_value.emplace(c, f); ... month.emplace(day, char_value); day++; } The trouble is that emplace doesn't overwrite, it defers to prior values. If you try to emplace an entry with a key for w...
61,686,223
61,686,418
C++ Mutex locking for a set of threads
I understand the basic principle of mutex's is to protect specific code path from being accessed by more than 1 threads. In my current setup, I have 10 threads of type A (A1-A10), and 10 threads of type B(B1-B10). By type I mean, threads that are running infinite loop and calling method A() and B() respectively. From t...
What you're looking for is 10 mutexes, one for A1/B1, one for A2/B2, etc. You can put them in an array and just access the proper one. Also, to be clear, mutexes don't usually protect code paths. What they protect is data. So if you have a list, that list might have a mutex so that only one thread at a time can be modi...
61,686,298
61,686,701
Fizz Buzz: Ideal solution
So, Fizz Buzz is a very simple problem and there are quite a lot of solutions to this problem. In a recent interview, the interviewer asked me to write a function for Fizz Buzz, So I single-handedly came up with the following approach. void fizz_buzz(int range) { for(auto i = 1; i < range; ++i) { if(i % 15 ...
I don't think you need an entire string just to check if anything is printed, a single bool would do. Besides that, I'd collect the numbers in an array for easy extensibility. Other than that, your second solution seems pretty okay. Here's my go at it: #include <cstdio> #include <utility> void fizzbuzz(int const rang...
61,686,345
61,686,854
In what sense const allows only atomic changes to mutable member variables?
I'm reading Functional Programming in C++ from Ivan Čukić, and I am having a hard time interpreting a point in the summary of Chapter 5: When you make a member function const, you promise that the function won't change any data in the class (not a bit of the object will change), or that any changes to the object (to ...
The author is making a claim about best practices, not about the rules of the language. You can write a class in which const methods alter mutable members in ways that are visible to the user, like this: struct S { mutable int value = 0; int get() const { return value++; } }; const S s; std::cout <<...
61,686,390
62,567,955
Problem with Operation on Border pixels of an image
I am trying to implement a demosaicing algorithm (interpolation) for a raw image with the Bayer pattern GRBG. The program logic was to use the neighboring pixels to assign the values to R,G and B channels(I have attached the code). I am having a problem for this logic at the border pixels. For example let i be the pixe...
The above stated answer works. But to prevent the hassle of using min,max with each pixel. It can be done as shown below with an Opencv function: int main(int argc, char** argv) { Mat img_rev = imread("C:/Users/20181217/Desktop/images/imgs/den_check.png"); //number of additional rows and columns in...
61,686,513
61,687,319
Parallel computing in C++ with OpenMP brings no difference to elapsed time
I am studying OpenMP. I am tried implementing some examples to test my understanding. Below is some simple code where I try to compute a simple sum (adding just zero each time) and compare the efficiency between parallelized code with openMP and the other code. Here it is: #include <iostream> #include <omp.h> #include ...
OpenMP threading takes time so if your code does almost nothing in the part that has been parallized (here you just do a sum) the gain of making things in parallel is nullified by the time it takes create/select the openMP threads. Furthermore in your code you use a reduction so all of you thread are most probably bloc...
61,686,537
61,687,392
Detecting whether a destructor has been called
Im making a board game where the game ends when one piece is destroyed e.g a king dying in chess. Now I have the possibility of searching through all my objects and seeing that e.g there WERE two pointers to king objects and now there's only one hence game is over and the team with the remaining king won. I was howev...
I experimented with using a static variable that is modified by the 'king' destructor but this is out of the scope of my game_rules class. This seems reasonable. I don't see why scope is a problem. The variable would be private to the king class, but with public read-only access. class king : public piece { publ...
61,686,559
61,686,843
Storing unique_ptr in vector
I have read many topics about this on SO and no solution worked for me so far, so I must be doing something wrong. This works: std::vector<CalendarDay*> calendarWeek; calendarWeek.push_back(new CalendarDay(hWndParam, ctrlRc, timeParam, week * MY_CLDR_DAYS + day)); This does not work (and it should, according to this):...
Based on your code, it looks like the issue is with the last line of the function calendar.push_back(calendarWeek). It should be calendar.emplace_back(std::move(calendarWeek)), otherwise, you are attempting to copy the vector of std::unique_ptrs, and since std::unique_ptrs do not have a copy constructor, you are gettin...
61,686,602
61,686,710
Leetcode May Challenge : Check If It Is a Straight Line
Here is my code for the problem : Check If It Is a Straight Line bool checkStraightLine(vector<vector<int>>& a) { double m = (((double)a[1][1]-a[0][1])/(a[1][0]-a[0][0])); for(int i=1;i<a.size()-1;i++) { double slope=(((double)a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0])); ...
Given: int a = 1 , b = 2; this line of code: double d = (double)(a/b); // d is 0. is not the same as: double d = ((double)a/b); // d is 0.5 In the first case, you are doing an integer division before converting the result. In the second case, you are converting the numerator to a double, and then dividing, which d...
61,686,778
61,731,613
Are thread shared variables directly accessed?
Reading about the C++ memory model and ordering directives raised me a questions - in the same process when a thread-shared atomic variable (eg. atomic) is set in one thread - and the ordering of the load is after the store - is it possible that the load is not seeing the stored value? Rephrased - is ordering a guarant...
I am not sure if I understand your question correctly, but I can try to provide some details about the C++ memory model. The default memory order of all operations on C++ atomics is sequential consistent. Formally this means that there is a single total order (S) of all sequentially consistent operations (regardless by...
61,687,260
61,687,488
How to filter file names with space character in a QFileDialog?
With Qt I'd like to open a QFileDialog in which only those files are shown, which contain a space character. Here is a simple example: QFileDialog::getOpenFileName(nullptr, "Open file", "/tmp", "My1stFilter (* *);;My2ndFilter (x y)"); However My1stFilter (* *) matches all files while My2ndFilter (y x) matches all fi...
You need to forego the native file dialog which simply doesn't support this. Then you can use a proxy model to filter based on your criteria. See Regular Expression Filter for QFileDialog
61,687,844
61,696,733
Remove carriage return from json text
I get json text returned from an api call and I run it trough a script JSON Serialization and Deserialization from here https://www.mql5.com/en/code/13663. My issue is that it only process the first few parts of the json because of what I believe to a linebreak/carriage inside the json structure. I dont get any error m...
I tried to use the same library, it seems to have a bug with parsing arrays. That is why I used https://www.mql5.com/en/code/11134. It has a disadvantage: you need to delete all the objects, unfortunately; as a result there's plenty of code. But at least it works. Seems your json has incorrect format, I used to cut it ...
61,687,868
61,687,953
Forward declaration of std::hash<MyClass>
I have multiple classes which overloads std::hash operator(). Let's say: A.h class A { ... } namespace std { template<typename T> struct hash; } A.cpp template<> struct std::hash<A> { public: virtual std::size_t operator()(const A& joint) const noexcept { .. } And similar classes let's say class B and cl...
You have to define the std::hash<A> specialization in A.h, so that B and C will be able to see that the specialization exists and that it has an operator() member. If B and C can't "see" the std::hash<A> specialization, then they will instantiate the primary std::hash template, which is disabled because the standard li...
61,687,918
61,688,001
(C++)Process returned -1073741819 (0xC0000005) when working with a linked list, but the algorithm works
The goal of this program is to remove any elements from the list that are greater than the following element. I've managed to make this program perform this task, however it crashes right after doing so and does not print the list afterwards, outputting an 0xC0000005 error code. #include <iostream> using namespace std...
When it reaches the last node in the list, aka curr->next equals null you are trying to access curr->next->data but next is null. Change your if statement to this: while (curr != NULL) { if(curr->next != NULL && curr->data > curr->next->data){ DeleteNode(curr->data); curr =...
61,687,961
66,496,853
Automatically include header files in intellisense with vscode when using precompiled header
I am on macOS 10.15, I am using vscode for a project. For this project, I set up precompiled headers. The compilation works well, but the precompiled headers are not included in my files. Instead, they are included with the compiler option -include pch.hpp (as stated here ). The problem is that because I have not those...
Use forcedInclude, c_cpp_properties.json: "configurations": [ { ... "forcedInclude": ["${workspaceFolder}/include/config.h"], ... } ]
61,687,993
61,688,033
Why does these two code pieces give different results
I was trying to learn about "<" operator on c++ strings and tried some test cases. I realized the two codes which I thought should behave the same was giving different results. Below are the codes, what is the reason for this? string s="test"; string k="tes"; cout<<(s<k)<<endl; //returns false so it prints 0 c...
(s < k) compares the values of the strings as you would expect. ("test" < "tes") compares the pointers to the beginning of the string literals as the compiler decides to arrange them in memory. Therefore, this comparison may return 0 or 1 depending on the compiler and settings in use, and both results are correct. The ...
61,688,058
61,688,145
function not returning lowest grade of students to main
I want to do a program to calculate average of students grades while dropping lowest score. To do so I created 3 functions for average of scores, gettting scores from user input and lowest score. However, in the main function I am not getting the lowest value returned rather I only get the initial value. Here is the c...
You are calling for the function lowgrade() from main and sending students, which is set to 0. The variable numberstudent in the function will be zero. It never reaches inside the for loop and therefore takes only the first argument. edit: when you declare on student variable inside getscores function, it's a local var...
61,688,371
61,688,404
How to return the max value between 3 values?
I am trying to return the max value using the max function but its not working on 3 values. CodeBlocks Error: error: '__comp' cannot be used as a function The Code: #include <iostream> using namespace std; int main() { cout << max(5, 10, 20); }
Use this overloaded function std::max that accepts an object of the type std::initializer_list<int>: cout << max( { 5, 10, 20 } ); This function has the following declaration template<class T> constexpr T max(initializer_list<T> t); Otherwise the compiler tries to select the function template<class T, class Compare> ...
61,688,787
61,689,822
Memory usage for map from an to elements of strictly increasing values
Data structure and usage of the map M In my code, I have a map called M defined as class T { public: size_t a; size_t b; size_t c; size_t d; size_t e; size_t f; size_t sum() { return a+b+c+d+e+f; } } const std::vector<T> M; M is a const. It is build at the beginning of a ...
If you know the previous value, it is enough information to know which of the variables increased by one. As there are six of them (a, b, c, d, e, f), you can represent that information with 3 bits. For n-entries, you will need 3 * n bits in total. In terms of size, that is an improvement, but it will violate your cons...
61,688,870
61,689,561
Logical Issue or Syntax issue with sorting String function
I'm new to C++ and coding in general. I'm attempting to make a simple program that essentially takes in two words and will tell you if these two words are anagrams or not.I also understand that there is likely a pre-made function to sort a string, like an array however I am trying to grasp the concept itself and hence ...
Adding to Daniel's answer, you don't need a temporary string in the sorting function, just process the passed string and return it. Also consider supporting letter cases as well, you can use std::transform from the STL algorithm library. #include <algorithm> Add this before looping in your sorting function or after ta...
61,688,894
61,689,004
Private variable is assigned correctly
Background: I do not know C++, I know C. Problem: In a file called lruTable.hh, I have defined struct lnode { struct lnode *next; struct lnode *prev; }; struct Table { struct lnode *list; int size; }; class lruTable { private: struct Table *table; public: lruTable(); }; I want the class con...
The followoing line does not allocate the right amount of memory. struct lnode *ln = (struct lnode *) malloc(sizeof(struct lnode *)); You need to use struct lnode *ln = (struct lnode *) malloc(sizeof(struct lnode)); Couple of points regarding your code. In C++, you don't need to use struct Table and struct lnode aft...
61,688,948
61,689,051
Temporary pointer before releasing?
I've took a look into atlbase.h to see how CComPtr<> is implemented, and stumbled upon Release() function in base class CComPtrBase<> which releases the underlaying object like this: // Release the interface and set to NULL void Release() throw() { T* pTemp = p; if (pTemp) { p = NULL; pTemp-...
There's two possible explanations here: If p->Release() throws then it will not be set to NULL in the second variant, while it will in the first. Note that the enclosing function is declared throw() so it shouldn't be throwing exceptions. It's possible that this function was written before the throw() specifier was ad...
61,688,981
61,689,014
How to inherit from two classes and call the constructor of the parent class I need to make an object of?
Hello I am fairly new in C++ and I am trying to make a programm that you have objects of Application class. Application class should inherit from two classes. The class Games and the class desktopApp. When I build my programm I get the two followin errors: no matching function for call to 'desktopApp::desktopApp() no m...
Having two base classes A and B, a class C that inherits from both, looks like this: class C : public A, public B{ public: C(/*params*/) : A(/*params*/), B(/*params*/){/*code*/} }; So in your case your Application should looks like this: class Application:public desktopApp, public Games { string name; public:...
61,689,026
61,689,050
std::distance not giving expected output
std::distance is returning the same value in a for loop, despite one of the arguments changing on each loop. #include <vector> #include <iostream> using namespace std; int main() { vector<int> q{1, 2, 3, 4, 5}; for (auto i = q.rbegin(); i != q.rend(); i++) { static int index_dif = distance(i, q.rend()...
static variables are only initialized once, so this line: static int index_dif = distance(i, q.rend()); will only use the first value of i to initialize index_dif. Remove the static and you should see the expected output. Here's a demo.
61,689,504
61,689,530
My C++ function gives unusual error, regarding declaration
#include <bits/stdc++.h> using namespace std; void union(int x, int y, int link[], int size[]) { int a = find(x, link); int b = find(y, link); if (size[a] < size[b]) swap(a,b); if ( a != b) { size[a] += size[b]; link[b] = link[a]; } } int main() { cout<<"Hello World"; ...
union is a reserved keyword in C++, and so, you cant use it for a function name. Rename it to something else, for example union_. That will solve your problem.
61,689,648
61,689,718
Why do I get error on the definition of a function that returns a unique_ptr to a an object of a template class?
This works fine: template <typename key_t> class BST{ struct node{ node(const key_t mKey) : key(mKey){} key_t key; std::unique_ptr<node> left; std::unique_ptr<node> right; }; //stuff //this function definition works fine here std::unique_ptr<node>& _find_next_succe...
You're missing the keyword typename within the template parameter for the unique_ptr in the function definition: template <typename key_t> std::unique_ptr<typename BST<key_t>::node> & //missing keyword BST<key_t>::_find_next_successor(std::unique_ptr<node> &curr){ ... } The compiler needs that keyword to know that nod...
61,690,215
61,690,340
Does system("cls") work fine in a virtual windows machine?
I have to submit a C++ project for marking soon, and I call system("cls") to clear the console a few times in my code. I know there are better methods but I just went for the easiest option. As far as I am aware, system("cls") only works in Windows. The person who is going to mark my code will be using a virtual Windo...
Yes it will. A Windows VM contains a regular Windows installation, running on a virtualised processor (under the control of the 'hypervisor').
61,690,230
61,690,259
Chinese character too large for enclosing character literal type
I'm trying to assign the Chinese character 牛 as a char value in C++. On Xcode, I get the error: "Character too large for enclosing character literal type." When I use an online IDE like JDoodle or Browxy, I get the error: "multi-character character constant." It doesn't matter whether I use char, char16_t, char32_t...
All of your character literals are standard chars. To get a wider type, you need to include the proper prefix on the literal: char letter = '牛'; char16_t character = u'牛'; char32_t hanzi = U'牛'; wchar_t word = L'牛';