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,940,256
61,940,308
When to pass a pointer and when to pass the memory address of a pointer?
I am looking at the following piece of code: StJetEvent* jets = 0; jetChain->SetBranchAddress("AntiKtR060NHits12",&jets); Where we have that: The class of jetChain is TChain and the definition of SetBranchAddress is: Int_t TChain::SetBranchAddress ( const char * bname, void * add, TBranch ** ptr = 0) ...
The syntax &z returns a pointer to z. The terms "address of X" and "pointer to X" mean almost exactly the same thing. int z; int* q = &z; // now q is a pointer to z int** r = &q; When we say "q is a pointer to z", we mean two things: The type of 'q' is pointer to whatever type 'z' is. The value of 'q' is the address ...
61,940,413
61,940,474
What kind of automatic type conversion is happening when calling std::filesystem::exists with a std::string?
According to this, std::filesystem::exists takes a std::filesystem::file_status or a const std::filesystem::path&. However, the following code works by passing in a simple std::string: string filename; getline(cin, filename); if (std::filesystem::exists(filename)) { cout << "Exists" << endl; } How does this work?...
std::filesystem::path has a constructor that takes a path::string_type which std::string falls under. It is not marked as explicit, so it is allowed to be used here for an implicit construction.
61,940,524
61,940,840
Segmentation error range-based for loop over neighbouring elements c++
I am trying to loop over a vector and need to manipulate the current element as well as the next one. I am currently trying this, but get an seg fault: for (const auto& element : * vec) { const ClassObj * obj1 = &element; const ClassObj * obj2 = &element + 1; if(!obj2) break; } Why does this...
It is possible to use a range-based for loop here, but it's kind-of ugly: for (const auto& element : vec) { const auto* obj1 = &element; if (obj1 == &vec.back()) break; const auto* obj2 = &element + 1; ... // do whatever with *obj1 and *obj2 } Most people will likely prefer a standard index-based for l...
61,940,708
61,945,265
Creating a packaged task for a lambda function with iterators as arguments
(using C++17 and g++ 7.5.0 on Ubuntu 18.04) dp1 below works fine, but dp2 results in the following error: undefined reference to `pthread_create' collect2: error: ld returned 1 exit status #include <vector> #include <iostream> #include <random> #include <thread> #include <future> int main(void) { //define lam...
Looks like the loader is missing pthreads library. Try adding the library with something like g++ -o myprog myprog.cpp -lpthread
61,940,862
61,941,186
A functional C++ program that doesn't use these characters: ';'. '{', '}', '\'
This is a problem that was given at a regional contest last year. Basically, you need to make a simple program in C++ that can print the result of several strings of the format(digit, operator, digit), until EOF is reached. The operators are the usual +, -, *, \. For example 3+5 2+2 4*3 9/3 Results in 8 4 12 3 The c...
Trigraphs and if statements could achieve this. #include <bits/stdc++.h> int main(void) ??< if (std::ios_base::sync_with_stdio(false)) if (std::cin.tie(0)) ??< ??> if (int x = 4) ??< if (int y = 5) ??< if (int c = x + y) ??< ...
61,940,917
61,941,235
Array loop termination in dynamic array
I am practicing loops in arrays, does the dynamic array's loop can't be terminated with null character. for (int i=0; arr[i]!='\0'; i++) And how can I terminate these loops without using this format: for (const auto& value : arr)
For an array allocated on the free store int* arr = new int[size]; there are two ways to know where the end is. The most straightforward is to remember how big it is: for (int i = 0; i < size; ++i) // do something with arr[i] The other way is to set the last element of the array to a sentinel value -- a value tha...
61,941,173
61,941,399
How do I get the function pointer to a function restricted by a concept?
I have a function template and an overload for a concept: template<typename T> void f() {std::cout<< "general" << std::endl;} template<std::integral T> void f() {std::cout<< "integral" << std::endl;} Now I want to get a function pointer to the function for the concept. It works fine when I use a helper struct: typedef...
It looks like that might be a bug right now, to get around it you can do something like... #include <type_traits> #include <iostream> template<typename T> void f() requires (!std::integral<T>) {std::cout<< "general" << std::endl;} template<std::integral T> void f() {std::cout<< "integral" << std::endl;} typedef void ...
61,941,408
61,941,600
Unable to index matrix in C++?
Newbie to C++, I'm providing matrix index as user input. Unable to run this script. Suggestions! #include<iostream> using namespace std; int main() { string fools[3][4] = {{"cat","dog","mon","junk"}, {"dad","mom","sis","fath"}, {"fox","cow","buff","chip"}}; for(i...
When you are doing this: cin >> fools[num1][num2]; The input read from the console is directly the value in the fools matrix. If you do this: cin >> fools[0][0]; whatever you enter in the console will modify "cat" and store the new value as a string. Suppose if you enter 0 1, it will change "cat" to "0 1". You need t...
61,941,722
61,941,931
Differentiate logic_error in C++
I would like to be able to catch different logic_errors and be able to differentiate them. Can I somehow pass additional parameters to the logical error which to catch later. The idea is that I need to print. Right now I am just catching the default errors that stof can return. "Sorry invalid temperature" or "Sorry i...
what() text is implementation defined, and GCC only does lazy (but efficient) printing like that. But you can split the extraction into two functions: float getTemperature(const std::string& temperature) { try{ return std::stof(temperature); } catch(std::logic_error& e){ std::cout << "Sorry...
61,942,066
61,942,298
Why there is no output when I use string in c++?
class A{ private : string a[3]; public : A(); void ShowA(); } A::A(){ string a[3] = {"aa","bb","cc"} } void A::ShowA(){ for(int x=0;x<=2;x++){ cout<< a[x]; } } int main(){ A a; a.ShowA(); return 0; } In this code, I think the output is aabbcc but there is nothing. Just...
As the comments tell you, you are creating a local variable a inside your constructor, instead of setting the value of the attribute a. You can set the value of a in member initializer list. The code becomes #include <iostream> #include <string> using namespace std; class A { private: string a[3]; public: A...
61,942,091
61,971,950
Qt VS Tools: error reading VS project settings
I develop an application using Visual Studio 2015 + Qt VS Tools extension. For me it's first time I used Qt (version 5.14.1) in my project. Everything was working fine until something wrong happened. I was asked to make release version of my application, it worked fine on Windows 10 and Windows 7 64-bit systems. Then I...
Well, after some more procedures that didn't help, I just did clean-reinstallation for my Windows 10. Fortunately, that helped :)
61,942,380
61,942,810
C++ pow() function changes behaviour when put inside a function
I have been programming in C++ for a while now. I have seen previously that power function gives wrong answer for bigger powers due to precision issues but today while solving coding problems I saw that under the same type of parameters, pow() function gave different values when put inside a function vs when evaluated ...
The problem is that the output of pow is a floating point double. In your custom function you convert that output to long long, which will truncate if the value returned by pow is slightly low instead of slightly high. See Is floating point math broken?. When you call pow directly the value is kept as a double even ...
61,942,572
61,950,080
Mock method with namespace using GMock
I am writing unit tests using GMock/Gtest in C++. I'm failing to mock a method in a namespace. For example: namespace::method_name() in the called function. Example code: TestClass.cc. // Unit test class TEST(testFixture, testMethod) { MockClass mock; EXPECT_CALL(mock, func1(_)); mock.helloWorld(); } MockCla...
You cannot mock free functions, you have to create interface: struct Interface { virtual ~Interface() = default; virtual bool func1(const std::string&) = 0; }; struct Implementation : Interface { bool func1(const std::string& s) override { corona::func1(s); } }; void helloWorld(Interface& interface) { ...
61,943,423
62,463,114
c++, reading string from file, segmentation fault
I have got segmentation fault and I don't know what's wrong. More then year ago I've wrote program which should write on hdd strings, integers and doubles included in my classes. I've been always using this piece of code: class Ttimes { public: string name; }; class R { public: string name; vector<Ttimes> ttt; }...
I've read Your answers, search in books and changed whole idea of reading-writing :) Now when I write I use: int stringSize=text.length()*sizeof(char); file.write(reinterpret_cast<char*>(&stringSize),sizeof(stringSize)); file.write(text.c_str(),stringSize); And when I read I use: int stringSize=0; string text; plik.re...
61,943,884
62,108,753
Find service`s uuid of a bluetooth device
I'm trying to get information about services provided by bluetooth devices. Using WSALookupServiceNext I can get list of all services. However, regardless of what bluetooth device I try to discover, the resulting WSAQUERYSET structure (pqs) never contains lpServiceClassId field (while the lpszServiceInstanceName is alw...
Answering my own question: In order to get service ID we have to parse SPD structures which are returned from WSALookupServiceNext function call and accessible via WSAQUERYSET.lpBlob member. For more details see Mike Petrichenko's comment. Also, there is a very good example how to implement it from Qt framework source ...
61,944,069
62,601,296
Can this piece of code be modified such that it works with fast-math enabled?
Can the code below be modified such that it works correctly even when compiled by GCC with fast-math enabled? #include <iostream> #include <float.h> using namespace std; int main() { char divider = 2; float power = 1; float number = 1; float current = number + power; cout.precision(20); // Divide until r...
Adding this piece of code into the loop solves the problem for me. std::ostringstream buff; buff << current Edit: Even adding this into the condition works: && ! isinf(current)
61,944,469
61,952,377
Problems with MCS lock implementation
I'm trying to implement an MCS lock in C++ with atomics. But unfortunately threads get stuck in a deadlock. One thread is waiting for the flag to turn false in the acquire method, while the second thread is stuck in the do while loop in the release method. So the problem must be in storing/loading the next node atomica...
The problem is in your release implementation: if (!succ) { // if this compare-exchange fails, it loads the new value of tail // and stores it in p if (tail.compare_exchange_strong(p, nullptr, std::memory_order_acq_rel)) return; do { succ = p->next.load(std::memory_order_acq...
61,944,536
61,946,415
Declare size of a vector inside class
I am trying to declare the size of a vector inside a class. I want the vector size equal to another attribute of this same class. Vector "table" is inside the class Hashtable. "bucket_count" is the intended size for the vector "table". the error given is "member is not a type name". Please let me know what another way ...
The easiest solution would be vector<list<string>> table{(size_t)bucket_count};
61,944,599
61,944,699
Understanding writing a CMakeLists.txt
I have the following code that works perfectly with gcc by running the command: gcc -L ~/Installed/C_LIBS/cmocka/lib -I ~/Installed/C_LIBS/cmocka/include hello.c -lcmocka -o hello When I try to convert that to a CMakeLists.txt it breaks after running cd build && cmake .. && make with the following error codes: Scanni...
The include_directories() command only affects header search paths (stuff that is used through #include). It has no effect on library search paths. Since you know the full path of the library, you should just be linking directly against said full path: target_link_libraries(hello ~/Installed/C_LIBS/cmocka/lib/libcmock...
61,944,697
61,944,921
Why is my while-loop breaking for specific inputs and works fine for other inputs?
I am new to programming and I am using the book "Programming : Principles and Practice Using C++(Second Edition)" by "Bjarne Stroustrup". I was told to try and write a simple calculator program in Chapter 6. I am able to perform many operations of '+' and '-' but when the program reads '*' or '/', it breaks the while-l...
The whole if (operation == 'X') block needs to be moved above the while (cin >> double_in) loop, otherwise cin >> double_in will fail when it reaches the X. More importantly, while (cin >> double_in) needs to be if (cin >> double_in) instead, since you need to read only 1 double value per operation character, and then ...
61,944,802
61,944,856
How to remove trailing separator from cout<< output console?
#include <iostream> using namespace std; template<class... Ts> void Fun(Ts... ts) { cout <<"TS: "; ((cout<<ts<<", "), ..., (cout<<endl)); } int main() { Fun(1,'a',"blah", 2.13, 3.14f); //console: 1, a, blah, 2.13, 3.14, } I want to remove the , separator after 3.14, how can I do that? I have tried cout<<"\b...
You might do template <class... Ts> void Fun(Ts... ts) { const char* sep = ""; cout << "TS: "; (((cout << sep << ts), sep = ", "), ..., (cout << endl)); } Demo or even, as you have header: template <class... Ts> void Fun(Ts... ts) { const char* sep = "TS: "; (((cout << sep << ts), sep = ", "), ..., (co...
61,944,952
61,945,215
C++ logical negated comparison operator doesn't work
I have a pretty simple class foo, that implements the < operator. I tried to implement a descending sort by negating the result of the operator like here: std::sort(foos_.begin(), foos_.end(), [](Foo& a, Foo& b) { return !(a < b); } ); Unfortunately, this gives me a SIGSEGV error. I guess because the result of the ...
Shouldn't !(a < b) be the same as (b < a)? no, !(a < b) is equivalent to b <= a. <= and >= doesn't respect strict weak ordering. You need: std::sort(foos_.begin(), foos_.end(), [](const Foo& a, const Foo& b) { return b < a; } );
61,944,959
62,032,881
Gradle and Cmake failing to find cpp file that is definitely there
I run gradle to build an android .aar and it reports that it can't find a file, but the file definitely is there. $ ./gradlew.bat assembleRelease > Task :webrtc-native:externalNativeBuildRelease FAILED Build mrwebrtc arm64-v8a ninja: error: 'C:/Developer/Microsoft-MRWebRTC/libs/mrwebrtc/src/interop/data_channel_intero...
I discovered it was because I had 'caseSensitive' flags enabled on some of my directories. Be careful, this is a new feature of WSL2 and there are some peculiarities where you may be enabled in without realizing. Windows cmake cannot traverse directories that have this flag enabled on them. Read about it here: https://...
61,945,275
61,954,665
Search and extract XML nodes by an attribute
I have some difficulties at extracting a specific XML node. Here is an example: <group name="syslog,"> <rule id="01" level="0" noalert="1"> <category>syslog</category> <description>Generic template for all syslog rules.</description> </rule> </group> <group name="firewall,"> <rule id="02" level="0" noale...
Here you go simple, console application to do this: #include <QCoreApplication> #include <QXmlStreamReader> #include <QDebug> #include <iostream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); const QString xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<docume...
61,945,276
61,945,494
How does the dimention argument of `sgemm` work?
I'm trying to understand the documentation for sgemm as I am transitioning code from using this library to a different library. The function prototype is sgemm ( character TRANSA, character TRANSB, integer M, integer N, integer K, real ALPHA, real, ...
LD stands for leading dimension. BLAS is originally a library of Fortran 77 subroutines and in Fortran matrices are stored column-wise: A(i,j) is immediately followed in memory by A(i+1,j), which is opposite of C/C++ where a[i][j] is followed by a[i][j+1]. In order to access element A(i,j) of a matrix that has dimensio...
61,945,439
63,657,707
How to Install compiler g++-4.8.5 in ubuntu 20.04
As the title said I can't install that specific version of g++ in my current ubuntu (20.04). I have been trying the usual things as: sudo apt install g++- (and displaying all posibilities but there where only versions from 8 to 10). Same happend looking for gcc possibilities. Also tried this: gist.github.com/applicatio...
These steps should work: sudo dpkg --add-architecture i386 sudo apt update sudo apt upgrade sudo apt-get install gcc-multilib libstdc++6:i386 wget https://ftp.gnu.org/gnu/gcc/gcc-4.8.5/gcc-4.8.5.tar.bz2 --no-check-certificate tar xf gcc-4.8.5.tar.bz2 # cd gcc-4.8.5 # ./contrib/download_prerequisites # cd .. sed -i -e '...
61,945,554
61,945,839
Order of execution of recursive function
I recently tried this problem: There are N wines in a row. Each year you sell either the leftmost or the rightmost wine. The i-th wine has initial price arr[i] and price y*arr[i] in the y-th year. What is the maximum possible total profit? I was able to solve the problem correctly using recursion, but I cannot under...
First of all parameter evaluation order in C++ is not defined. See : https://en.cppreference.com/w/cpp/language/eval_order Arguments of max is in your case evaulated from right to left. First you are calling the function with initial parameters: l = 0 , r = n-1, y = 1 When statement int sum=max(arr[l]*y+func(arr,n,...
61,945,743
61,945,810
Is there a way to clear empty array in c++ , check code below for explanation
generated = (rand() % 11); cout << "GUESS THE NUMBER 10 TIMES" << endl; for (int i = 0; i < 10; i++) { cin >> guesses[i]; if (generated == guesses[i]) { cout << "CONGRATS ! YOU HAVE FOUND THE CORRECT NUMBER ! " << generated << endl; restart(); break; } } cout << "HERE ARE YOUR GUESSES:" << endl; for...
Yes. Keep a count of how many inputs you take c and loop up to c instead of 10 in your second loop: int c = 0; cout << "GUESS THE NUMBER 10 TIMES" << endl; for (int i = 0; i < 10; i++) { cin >> guesses[i]; c++; if (generated == guesses[i]) { cout << "CONGRATS ! YOU HAVE FOUND THE CORRECT NUMBER ! "...
61,945,773
61,945,882
C++20 Concept test not working in MSVS 16.5
I'm new to C++20 concept, but from examples I've seen, this code should work... #include <iostream> #include <string> #include <concepts> #include <memory> using namespace std; struct hasToString { string toString() { return __FUNCTION__; } }; struct noToString { }; template<typename T> concept ...
concept has_toString = requires(const T & t) { t.toString(); }; Since t is a const object, its toString() method must be a const method. This is not directly related to concepts but with the way C++ class methods have worked even before C++11. struct hasToString { string toString() { And, of course, this ...
61,946,081
61,946,246
Need to read a line of text from an archive.txt until "hhh" its found and then go to the next line
My teacher gave me this assignment, where I need to read words from a file and then do some stuff with them. My issue is that these words have to end with "hhh", for example: groundhhh, wallhhh, etc. While looking for a way to do this, I came up with the getline function from the <fstream> library. The thing is that ge...
As you discovered, std::getline() allows you to specify only 1 char for the "sentinel" that it stops reading on, where '\n' (line break) is the default. What you can do is use this default to read an entire line of text from the file into a std::string, then put that string into an std::istringstream and read words fro...
61,946,586
61,946,741
Compile error associated with std::unique_ptr and abstract classes
I have class that inherits from a base class. The base class contains pure virtual functions that are overridden in the derived class. I instantiate the base class object with std::unique_ptr of the derived class but get a compile time error class Base { public: ~Base () = default; initBase () { count = 0; } ...
There are several typos in your code: In Base: Change initBase () { count = 0; } to Base () { count = 0; } In Child: change myClass(std::unique_ptr<Base> base) { _base(std::move(base)) }; to myClass(std::unique_ptr<Base> base) : _base(std::move(base)) { } change ~myClass() = default(); to ~myClass() = default; In m...
61,946,603
61,946,674
glpointsize() Fails to Shrink a Point
I'm trying to write a simple opengl program that cyclically grows and shrinks a single point at the center of the screen using glPointSize() and a variable pointSize. Printing the value of pointSize and stepping through the code with a debugger appears to show that pointSize updates correctly on each iteration. The ren...
Your code does not clear the screen with glClear. Therefore, when the point grows, you can see it. When it shrinks, it's simply drawn 'inside' the bigger dot, without you noticing it. You could catch that if you changed the color of the dot as it changes the size. Simply clear the color buffer at the beginning of the f...
61,946,614
61,946,764
PostgreSQL C++ libpq encoding UTF-8 problem
I don't have problem inserting UTF-8 (korean character in my case) using direct sql command in PGAdmin or psql console. But when I need to insert values in C++ by using libpq library, I got the encoding error and I couldn't resolve it until now. I have tested DB connection, etc and works well. So I will just share the ...
I have managed to solve it, sorry for my lack of understanding in encoding processing. I just need to convert ANSI to UTF-8, below is my working code. If there's a better solution, please post your answer. int AnsiToUTF8(char* szSrc, char* strDest, int destSize) { WCHAR szUnicode[255]; char szUTF8code[255]; ...
61,947,035
61,947,355
How to write a copy constructor to copy a pointer?
I have a simple class: class Device { std::string _serialNumber; DeviceInfo(std::string serialNumber){ _serialNumber = serialNumber; } } and now I create a pointer variable: Device *device1 = new Device(); I want to make a copy of device1's content, but device2 should point to a differe...
You need a custom copy constructor when you have a member var can't be copied trivially. As an example: if you have int* memVar in your class because if it was copied trivially the new object would have memVar having the same address contained by memVar of the source object. Now your class objects can be copied trivial...
61,947,186
61,947,501
Iterating through a custom double linked list
I am implementing a double linked list. I have implemented functions for adding to the head and tail of the list. I have been trying to make a function that would print all the elements of a given object. Though the function prints the first value it does not print any other item in the list. d_list.h #include<iostr...
there are some mistakes in your addastail() and addashead() method. I removed these mistakes,Check this: void addashead(T data){ Node<T>* curr_node=new Node<T>(data); if(this->head==nullptr){ this->head=curr_node; this->tail=curr_node; this->l_size=l_size+1; ...
61,947,356
61,947,417
Why does assignment operator overloading create a copy of an object?
In the below given code, I have written cout statements in all the class constructors, destructor and overloaded assignment operator. #include <iostream> using namespace std; class person { string name; int age ; int id ; static int num; public : person (string name , int age) : name(name) , age(ag...
That's because your operator=() looks like this: const person operator= (const person &other) That returns by value. const doesn't really make sense in this context. What you actually mean to do is return by constant reference instead: const person& operator= (const person &other) That one & will make all the differe...
61,947,783
61,947,828
Eliminating Memory Leak in C++
I have created a function named substring and used it in the following way:- char* substring(char* source, int startIndex, int endIndex) { int size = endIndex - startIndex + 1; char* s = new char[size+1]; strncpy(s, source + startIndex, size); s[size] = '\0'; return s; } char *game1 = new char[10]...
The problem is near char *game1 = new char[10] You have assigned char[10] to game1 which you never deleted. Try by adding delete[] game1; before game1 = a0; Actually you don't need to assign that char[10] to game1 I don't know why you have done it. Removing that may also work. Just declaring as char *game1;
61,948,116
61,948,186
Passing array of vectors by reference in C++
In the main function, I defined an array of vectors like this: vector<int> v[n+1]; where n is taken from stdin. In the main function, I am calling a function passing this argument like this: func(v); In the function definition, I defined it this way: func(vector<int>& v[]) # I want to pass v by reference. ...
vector<int> v[n+1]; where n is taken from stdin is illegal C++, even if it's allowed by some compilers as VLA. Use std::vector instead: #include <vector> void func(std::vector<std::vector<int>>& v); int main() { int n = 24; std::vector<std::vector<int>> v1(n); func(v1); }
61,948,819
61,948,894
How to get the data type in a vector using template?
I'm writing a function template like this: template <class T> class MyClass() {} template <typename A, typename B> auto func(A<B>& data) { return MyClass<B>(); } So I can using the function like this: vector<int> vi; auto a = func(vi); vector<string> vs; auto b = func(vs); list<int> li; auto c = func(li)...
You can declare A as template template parameter, otherwise you can't use it as A<B> in the function parameter declaration since it's not considered as template. template <template <typename...> class A, typename B> auto func(A<B>& data) { // ... use B as the data type ... } Another way is STL containers (includin...
61,949,124
61,949,189
cout prints inaccurate result and printf prints accurate result
The following code in C++: double x = 500000.6; printf("%f\n", x); cout << x << endl; prints the following: 500000.600000 500001 Why cout isn't printing the correct value (500000.6)? Putting the following line as the beginning of the code makes cout prints correct result: cout.precision(7); However, sett...
By default, the precision is the total number of significant digits. It's not the number of digits after the decimal point. 500000.6 has seven significant digits, 500001 has only six. Try this instead cout << fixed << setprecision(1) << x << endl; When used for fixed format, the precision is the number of digits after...
61,949,180
61,949,266
C++ Importing filename from variable
I'm have variable 'filename' with contents 'code.h', i'm need do this, #include <filename> why it's not working? Or #include not works with variables?
#include is for other header files not variables. If you want to conditionally include header files you can use precompiler commands: //config.h #define USE_HEADER_CODE_H //other.h #include <config.h> #if defined(USE_HEADER_CODE_H) #include <code.h> #else #include <other_code.h> #endif
61,949,282
61,950,941
functions with an indefinite number of parameters
I want realize code like this: template <typename... Args> class A { public: A(Args... args) {ind = std::make_tuple(args...);} std::tuple<Args...> ind; }; void foo() { std::cout << std::endl; } template <typename First, typename... Rest> void foo(First _first, Rest... _rest) { std::cout << _first; ...
You have to "unpack" the parameters from the tuple before you call it. maybe something like that: template< size_t ... Ints > class integer_sequence{}; template < typename T, size_t N > struct add_sequence; template < size_t N, size_t ... IDX > struct add_sequence< integer_sequence<IDX...>, N> { using type = int...
61,949,926
61,949,958
Template operator[] overloading strange C2676
I'm trying to overload the [int] operator in a templated class, but I always get a C2676 error followed by a visual studio E0349 "no operator [] matches these operands WMSTR [ int ]" My template class: template <typename T, unsigned int N> class MyString{ public: // ... Non relevant tested code template<t...
You're declaring both the operator[] as function template, their template parameters can't be deduced and then calling fails. Making them non-template should work fine; I suppose you just want to refer to template parameter T and N of class template MyString in operator[]. T& operator[](int index) { // Assert index...
61,949,988
61,950,031
Is it possible to use a member of a template parameter?
Following is a simple example. template <typename TA> class A { }; template <class A> class B { A a; A::TA ta; }; int main(){ B<A<int> > b; } where, I have a template class A with a unknown type (TA) as template parameter. In class B, I want to define some variables using class A and its member type. I ...
template <typename TA> class A { public: using type = TA; }; template <class A> class B { public: A a; typename A::type ta; }; Does this help?
61,950,207
61,950,371
A custom operator overload in C++ without overhead
I want to be able to define a custom operator that works like this: struct Matrix { int inner[5]; static Matrix tensor_op(Matrix const& a, Matrix const& b); }; int main() { Matrix a; Matrix b; Matrix c = a tensor c; return 1; } The following code works perfectly, except that it does not optim...
It is optimized by MSVC. Look at the generated code for main() (Using /GS- to remove the security check, just to make it clearer): $LN10: sub rsp, 120 ; 00000078H lea r8, QWORD PTR c$[rsp] lea rdx, QWORD PTR a$[rsp] lea rcx, QWORD PTR $T1[rsp] call static Matrix Matrix::tensor_op(Matrix const &,Matrix const ...
61,950,473
61,951,114
Wait for child process to terminate when using waitpid
Here is my example code #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <signal.h> #include <errno.h> id_t pid; void handle_sigterm(int sig) { printf("handle me \n"); } void forkexample() { // child process because return value zero pid = fork(); int...
You can use waitpid() to wait for the child inside signal handler of parent also. This does make sure that parent will wait for child even though it receives signal. Some advices are as below. Why do you think it is a C++ program? signal handler name you set for sa_handler is wrong. handle_sigint() is not defined.
61,950,490
61,950,716
C++ Erase objects from vector based on member function
I have a vector made up of objects from a class like this: class Destroyable {//....... public: bool isDestroyed(); //......... }; How would I erase all of the elements that return true for isDestroyed()?
You can use std::mem_fn to adapt a pointer-to-member-function as a function object with an explicit parameter of the class. std::vector<Destroyable> vec = /* some values */ auto last = std::remove_if(vec.begin(), vec.end(), std::mem_fn(&Destroyable::isDestroyed)); vec.erase(last, vec.end()); In C++20 you can reduce th...
61,950,657
62,313,556
Which is the safer way to store `uint8_t*` C buffers in Rust?
I'm doing #[no_mangle] pub extern "C" fn receiveBufferAndPrint(buffer: *const u8, size: usize) { for i in 0..size { println!("{}", unsafe { *buffer.offset(i as isize) }); } } To receive an uint8_t* buffer from C. What is the safest way to convert this buffer into a Rust object that deletes this memory...
If C is lending you the buffer, then use std::slice::from_raw_parts, and then you can copy that slice to Vec<T> or Box<[T]> if you want to keep the data. If C is passing ownership of the buffer (i.e it's heap-allocated and C won't free it), then you can use c_vec crate to ensure it's freed properly (using libc::free() ...
61,950,722
61,950,793
glDrawArrays is not working for some reason?
I do not understand why this is not working with glDrawArrays. If you see anything out of place or missing I really need to know. #define GLEW_STATIC #include <GL/glew.h> static int CompileShader(unsigned int type, const std::string& Source) { unsigned int id = glCreateShader(type); const char* src = Source.c...
The 2nd parameter of glVertexAttribPointer is the tuple size of a coordinate, rather then the number of floats in the array of vertices. Each of the vertices in the array consists of 2 components, hence the size argument has to be 2 rather than 6: glVertexAttribPointer(0, 6, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0); ...
61,950,886
61,959,656
boost::interprocess::file_lock erroneous behavior when used with std::ostream
I am trying to use file_lock for restricting multiple instances of the same program running at the same time (Implementing something mentioned in this answer). I am using 1.66 version of boost on Linux. Before locking the file, I make sure that file exists (by opening it using std::ofstream with std::ios::app). I notic...
I have found the reason. It was due to boost::interprocess::file_lock were implemented using Classic POSIX File-locks. This link explains the issue with POSIX locks and hence, with boost file_locks. More troublingly, the standard states that all locks held by a process are dropped any time the process closes any file ...
61,951,230
61,951,469
Access class implementation instanciated from template parameter packs
I would like to instantiate all States in the MachineT as a shared_ptr<T> then access them by typename. In the following code, it refers to the instantiation (MachineT constructor) and a way to access the states (get function). Is there any hashmap trick or a way to store in the class an "Index" information such as Sta...
It's perfectly doable. Here's how to do it in C++14: #include <memory> #include <tuple> template <typename... States> class MachineT { public: MachineT() : states_{ std::make_shared<States>()... } { } ~MachineT() {} template<typename T> std::shared_ptr<T> get() { return std::get<std::shared_...
61,951,395
61,951,471
Why in function 'int main()' -> 's' may be used unitialized in this function?
#include <iostream> using namespace std; int main(){ int n,s; cin >> n; for(int i = 1; i <= n; i++){ s += i; } cout << s; return 1; } Error : suma_gauss.cpp: In function 'int main()': suma_gauss.cpp:14:11: warning: 's' may be used uninitialized in this function [-Wmaybe-uninitial...
It is not just a "maybe". s is used uninitialized in your code, always (maybe not in the loop, but latest at cout << s;). s += i is equivalent to s = s + i;, hence your code has undefined behavior. PS: The compiler points you at cout << s; because depending on n, the loop may not be executed at all. However, it could (...
61,951,774
61,951,869
Qt+OpenCV: Symbols not found for architecture x86_64
I want to use the stereo-module of OpenCV, programming with Qt. When building my project, i get the following errors: My setup: OpenCV 4.3.0 + contrib 4.3.0 compiled from source, used CMake GUI to make Qt Creator 4.11.0, Based on Qt 5.14.0 (Clang 10.0 (Apple), 64 bit) My pro-file: Who can help me?
According to the documentation for StereoSGBM it is part of the calib3d module, which is part of the contrib that you have mentioned already have. I see you have linked against core, imgproc, imgcodecs and highgui but the calib3d is missing.
61,952,066
61,954,286
Error during running : char at memory place
I have an error I don't understand. When I execute my code I got that: Exception non gérée à 0x00007FF9CC11A799 dans perception.exe : exception Microsoft C++ : char à l'emplacement de mémoire 0x000000ACEC0FE568. a eu lieu  That can be transleted in English by Uncatched exception at XXXXX in perception.exe : Exceptio...
As suggested me @Someprogrammerdude in comments, the problem was the throw. I should replace the string by a proper exception, that solved my problem. Because, my program was throwing an exception during the execution (I could see it after changing the string). Thanks.
61,952,169
64,809,967
Unknown CMake command "check_language"
I have a project containing both "normal" code and CUDA code. The whole project is managed by cmake. Now, depending on the availability of CUDA on the target machine I would like to be able to switch the CUDA-files on and off. For that, I intended to use the CMake-command "check_language", and implemented it in the fol...
Add the CheckLanguage module to the CMakeLists.txt file to use enable_language with include(CheckLanguage). As Tsyvarev posted here
61,952,209
61,952,321
When is it safe to capture a lambda inside another lambda by reference?
Suppose you have the following program: static std::function<int(int)> pack_a_lambda( std::function<int(int)> to_be_packed ) { return [=]( int value ) { return to_be_packed( value * 4 ); }; } int main() { auto f = pack_a_lambda( []( int value ) { return value * 2; } ); int result =...
static std::function<int(int)> pack_a_lambda( std::function<int(int)> to_be_packed ) { return [&]( int value ) { return to_be_packed( value * 4 ); }; } is Undefined behavior as you "return" reference to local variable. By value is the safe way here. static std::function<int(int)> pack_a_lambda(const st...
61,952,780
61,952,944
C++ Why am I recieving the error redefinition of class?
Below are two files, one contains the main functions and the other the h file main class issuesofRelevance{ public: vector<string> issues; int significance = 0; //initalize 0 int approach = 0; //initalize 0 issuesofRelevance() { } void setStance(vector<string> issues, int significance...
Let's say the main function is in main.cpp and the class is in IssuesofRelevance.h. You didn't mention anything about if you included the .h file in your .cpp file. But I am assuming that you did. So I am assuming you wrote #include "IssuesofRelevance.h" At the top of the main.cpp function. Now, what #include directiv...
61,952,870
61,953,069
How to store values ​in 2-D array?
#include<string> #include<vector> #include<iostream> using namespace std; class CMatrix { private: string name; float** matrix; int nRow; int nCol; int nElement; //총 element 수 public: CMatrix() { this->name = "Anonymous"; this->nRow = 4; this->nCol = 4; matrix...
It might be helpful if you also add the output of the error. Other than that, I can't see a reason why you would use raw pointers, or not use std::vector<> or just simply use multi-dimensional arrays. Also, you have a memory leak, make sure to delete all the new initialized value of the matrix in the class destructor. ...
61,953,129
61,953,794
Use accessor syntax in cython for cpp classes
If I have a class defined as follows in C++ class sample { private: int data; public: sample() { data=0; } int get_data() { return data; } void set_data(int data) { this->data = data; } }; and I want to expose it to cython code using: cdef extern from "...
Disclaimer: I don't know cython, so I cannot say if the following will be fine for cython. However, my strategy would be to implement access via s.data already in the C++ code to keep the bindings slim and straightforward. C++ has no attributes, but one can emulate them: #include <iostream> template <typename T,typena...
61,953,563
61,953,829
template sum function freezes for char
#include <iostream> // std::cout template <class T> T Sum(T x, T y) { return x + y; } int main() { std::cout << Sum<int>(5, 10); std::cout << "\n" << 'a' + 'b'; std::cout << "\n" << Sum<char>('a', 'b'); return 0; } The program freezes on the last line when using cpp.sh site, can somebody please explain why...
Assuming signed 8 bit char, which is very common, adding 'a' and 'b' and storing the result in a char overflows and causes undefined behavior. Thus, the program is free to do anything. In my testing with GCC it prints some garbage and main exits with 0.
61,953,847
61,954,033
Deleting element in priority queue other than top element in C++
Is there any inbuilt function for deleting a given element (other than top element) in priority queue class of C++ STL? If not how to delete it in O(log n)?Should i implement the heap data structure from scratch for this 'delete' functionality?
Is there any inbuilt function for deleting a given element (other than top element) in priority queue class of C++ STL? No. If not how to delete it in O(log n)? By using another container. std::set is the simplest compromise. A custom heap implementation may be more optimal.
61,954,228
61,954,705
What is the difference between variadic template and ellipsis?
I know the title does no make much of a sense, but the code will explain my problem. template<typename T> void foo(T...) {std::cout << 'A';} template<typename... Ts> void foo(Ts...) {std::cout << 'B';} int main(){ foo(1); foo(1,2); } Try to guess the output of this program before reading the continuation: S...
What even is the first overload? Per [dcl.fct] Where syntactically correct and where “...” is not part of an abstract-declarator, “, ...” is synonymous with “...”. So this makes the first overload a variadic function (that also happens to be templated) that is equivalent to: template<typename T> void foo(T, ...) {s...
61,955,006
61,955,059
What is better style: ++x or x++ in for loops
I was having a discussion with a stubborn person I know over which of these two forms was more semantically correct, although there is no logical difference to the code: 1. for(int x = 0; x < 10; x++) // do something 2. for(int x = 0; x < 10; ++x) // do something Is it better to pre-increment or post-increment in a f...
If you don't need the side effect of post increment, then the pre increment version is the better choice. In case of an int it does not result in different code, but in case of an iterator you probably get better performance with pre increment because post increment needs to create a temporary copy of the original iter...
61,955,130
61,958,537
Show longer String with ImGui
I'm using ImGui, the implementation for OpenGL worked fine but now I have a problem with rendering some Text. For some reason, whenever I try to render a string with ImGui::Text(someString.c_str()); ImGui renders only the first 19 characters. If I try to render the same Text with ImGui::Text("This is a Text longer than...
The Problem was that I never had the Idea to use another string... The content of someString contained a 'ü' which terminated the string. But why 'ü' doesn't work with ImGui is another question.
61,955,186
61,957,126
CopyMemory gives segmentation fault
My program is supposed to take input via the console and use shared memory so that another process can get access to the input. Apparently CopyMemory is causing a segmentation fault. std::string Input; std::cout << "What Text do you want to encrypt? "; std::getline(std::cin, Input); //create named ...
The first argument to CopyMemory should be shmBuffer, not the handle. HANDLE is superficially a pointer datatype, but dereferencing it is a sure way to get access violation.
61,955,286
61,955,658
Process exit code 0xC0000135 while running Qt hello world
Here is my main.cpp code: #include <iostream> #include <QtWidgets/QApplication> #include <QtWidgets/QPushButton> using namespace std; int main(int argc, char *argv[]) { QApplication application(argc, argv); QPushButton button("Hello, world!"); button.show(); return application.exec(); } Running it in...
From the CMake documentation for set(ENV ...): This command affects only the current CMake process, not the process from which CMake was called, nor the system environment at large, nor the environment of subsequent build or test processes. So, this does not set the PATH environment variable within your CLion environ...
61,955,332
61,956,107
Why ADL has a different behavior for operator function than other functions?
I have created a C class inside a NS_C namespace that way: #include <iostream> namespace NS_C { template <typename T> class C { public: C operator+(long) { std::cout << "NS_C::C::operator+\n"; return *this; } void not_operator(C<T>, long) { std::cout << "NS_C::C::not_...
From overload_resolution#Call_to_an_overloaded_operator: We have in overload sets of candidates for overloaded operator: 1) member candidates: if T1 is a complete class or a class currently being defined, the set of member candidates is the result of qualified name lookup of T1::operator@. In all other cases, the set ...
61,956,176
61,957,178
Cannot access one class from another class in Visual Studio C++
I am trying to utilize wxWidgets in Visual Studio (2017) C++. I created two classes. Namely, cApp.h and cMain.h. Then i tried to create new instance of Cmain in cApp. However, it below error: Error C2248 'cMain::cMain': cannot access private member declared in class 'cMain' When I hover over the .h file in Solutio...
The compiler is right, cMain is private. In C++, members of a class are private by default, basically because of a protection model. From "The Design and Evolution of C++"(Bjarne Stroustrup): [...]only the declarations placed in the class declaration (supposedly by its owner) can grant access. By default, all informat...
61,956,348
61,956,534
Is there any overhead of using static member function over a normal function?
I am using template classes for making functions. So I decided to define the functions inside a class. template<class T> struct A { static T F(){} static T F1(){} }; There are no variables inside the struct that I need to use. I am calling the functions using A<int>::F(). Time is very important to my work (ev...
In short No there's no overhead generated at run-time for template function call or static member function call. So go ahead. If your profiler tells you something, you may of course come back with another question :-) More details Templates are a compile-time business. So a call to a templated function will not bri...
61,956,365
61,972,988
Building Python submodules from C++ extensions via cmake
I'm trying to incorporate a c++ extension as a submodule into an existing python library via cmake. Building the C++ extension works fine and importing it as a python module works, but not as the submodule of the header library. I have the following directory structure: frontend/ foo.py bar.py backend/ b...
I think I've resolved the issue with the following lines: Change in the setup.py file: ext_modules = [ Extension( "frontend.backend", sources=["frontend/backend/backend.cpp"] ) ] Change in the CMakeLists.txt file: pybind11_add_module(backend "frontend/backend/backend.cpp") set_target_properties( backen...
61,956,435
61,957,580
How to compile non-common language in CMake
I am trying to switch from Makefile to CMake for one of my projects. The issue is that in the compilation steps, I use a non-common language compiler (Futhark) to generate a .c and .h file. The relevant part of the Makefile looks like this. fut_compile: futhark/select_where.fut mkdir -p build && futhark c --library f...
Do it like this: // build/select_where.c build/select_where.h: futhark/select_where.fut // mkdir -p build && futhark c --library futhark/select_where.fut -o build/select_where add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/select_where.c ${CMAKE_CURRENT_BINARY_DIR}/select_where.h CO...
61,956,462
61,956,574
What's 'mymap[1];' instruction where mymap is std::map?
I found a code which use the instruction mymap[1];. Did any one know the meaning of it? Here is a sample code which compiles successfully: #include <iostream> #include <map> using namespace std; int main() { std::map<int,int> mymap; mymap[1]; cout<<mymap[1]; return 0; }
mymap[1] gives you the element with the key 1. For example, you could assign to it: mymap[1] = something;, or print it: std::cout << mymap[1];. If the element is missing, it's inserted automatically. The new element is value-initialized, which for scalar types essentially means zeroed. As you noticed, doing just mymap[...
61,956,672
61,956,818
How to get if the file is type of JPEG with jpeglib.h
I would like to ask you if there is any way how to get information(bool value) if the file is jpeg. I solved it in png like this: bool isPng = !png_sig_cmp(reinterpret_cast<png_const_bytep>(header), 0, number); I tried to search on the internet and read the documentation of jpeglib, but didn't solve it. Thank you for ...
If you read the first few bytes of the file you should see the JFIF characters in a jpeg. Using jpeglib you can attempt to read the header data and fail on that.
61,956,907
61,962,891
Can you profile a single call of a function with perf?
I have a C++ function that I want to profile and only that function. One possible way is to use chrono and just measure the time it takes to run that function and print it out, run the program a few times and then do stats on the samples. I am wondering if I can skip having to explicitly code time measurements and just...
Have a look at Google's benchmarking library to micro-benchmark the function of interest. You can then profile the resulting the executable as usual using perf. For example, let's say that following the basic usage, you generated an executable named mybenchmark. Then, you can run perf on the binary as usual $ perf stat...
61,957,085
61,957,167
why iterator doesnt get to end of vector?
I made a vector v which is [-5,-3]. I assigned an iterator iti to its beginning and then assigned another iterator itj as iti+1. Since my vector only has 2 elements, I would think that itj is recognized as the end of the vector or v.end(). But it is not. Any ideas why that might be happening? vector<int>v; v.push_back...
end is an iterator to the (non-existing) element after the last element. iti + 2 would equal end because the vector has 2 elements. Generally, for a vector of size N: begin + N equals end.
61,957,162
62,000,353
Visual Studio 2019, no Intellisense with "Show all files"
I have started learning C++ with Visual Studio 2019 and noticed a strange behaviour. When you create an empty project you are represented with "Filter" files. Now if I active "Show All Files" I can create directories. I created the following structure: /Core/ /Engine/ Main.cpp Now if I create a "class" it is, by defau...
Now if I start editing the newly created files I loose Intellisense. If I uncheck "Show All Files" I get it back. Does anyone else have the same problem? I have faced the same issue as you described and when I migrate a file to another folder under the Show All Files filter, Intellisense does not work, which is r...
61,957,581
61,957,980
What does it mean to return an Object in C++ Code?
What does it mean when I am supposed to return on Object of my class in C++? Example: Return an EvenNumber object that represents the next even number Now EvenNumber is my class and I have to create a function that returns the Object of that class that stores the next even number. int EvenNumber::getNext() { if (e...
To return an object of your class EvenNumber from getNext, you will need to provide a converting constructor that takes an int: class EvenNumber { private: int evenNum = 0; public: EvenNumber(int n) : evenNum(n) {} EvenNumber getNext(); } EvenNumber EvenNumber::getNext() { if (evenNum % 2 == 0) { ...
61,957,584
61,958,345
Defining max and min values for a variable in C++
I'm working on a project, and was curious about if there's an easy way to define custom max and min values for a double variable. At the moment, there's a quite large if-else if block handling this, but my question is can I do something in the variable's declaration so that these checks are unneeded?
was curious about if there's an easy way to define custom max and min values for a double variable. Since C++17, there is standard library function std::clamp that you can use to set out of-bound value to maximum / minimum depending on which boundary it exceeded. If you need some other behaviour for out-of-bound valu...
61,957,657
61,958,711
How to pass const string parameter from perl to c++ using swig
I am new to Swig and I need help in debugging this error. My motive is to create a logging system with less time consuming using Swig, C++ , Perl. But i got error while passing the string parameter form Perl to C++ via swig. I have placed my entire code and error below. Please help me to solve this issue. Thanks in fu...
You need to include a typemap for std::string in your interface file so SWIG knows how to handle the type, see chapter 9.4 in the manual: 9.4.1 std::string The std_string.i library provides typemaps for converting C++ std::string objects to and from strings in the target scripting language. %module Logger %includ...
61,958,276
61,958,757
Matrix and vector multiplication returns wrong result using GLM
I have this equation with constant c and vec4 x=(x_1, x_2, x_3, x_4): x_1*c + x_2*c + x_3*c + x_4*c where sum(x_i) = 1 That means, the result should be c: =(x_1 + x_2 + x_3 + x_4) * c = 1 * c = c So I have a vec4 and a matrix4*3 multiplication like this: (x_1, x_2, x_3, x_4) * ((? c ?), (? c ?), (? c ?) (? c ?) ) Howev...
OpenGL matrices and GLM matrices are stored in column major order. The vector has to be multiplied to the matrix from the right: glm::vec3 result = sumTo1 * M; glm::vec3 result = M * sumTo1; See GLSL Programming/Vector and Matrix Operations and OpenGL Shading Language 4.60 Specification - 5.10. Vector and Matrix Ope...
61,958,353
61,967,287
The max count of layers in QOpenGLFunctions and QOpenGLFunctions_4_3_Core
In my program, if use QOpenGLTexture, I can set 256 layers texture like this: texture= new QOpenGLTexture(QOpenGLTexture::Target2DArray); texture->create(); texture->setSize(24,24); texture->setLayers(256); texture->setFormat(QOpenGLTexture::RGB8_UNorm); texture->allocateStorage(); and set data...
When set the z value of texture cords, I use GL_BYTE, in fact I should use GL_UNSIGNED_BYTE.
61,958,404
61,958,477
Running Makefile not completely
I am a rookie to MaKefile and I've been learning it recently. However, I got trouble when I tried to run make command on my terminal. Here's my Makefile: CC = g++ CFLAGS = -g -Wall bin = ./bin/ makedir: @echo "build ./bin" mkdir $(bin) all: algo OBJS = $(patsubst %.o, $(bin)%.o, BB.o BF.o method.o a...
When you run make without arguments, the recipe for the first target in the Makefile is followed. Your first target is makedir, whose recipe performs those two commands and nothing else. So, the computer is doing what you asked it to do. I recommend that you put the all target first, and make makedir a prerequisite of ...
61,958,676
61,958,837
Diagonal Difference of a Square Matrix
I'm trying some HackerRank challenges to kill some time and I came across an easy exercise where I'm required to calculate the absolute difference between the sums of a square matrix diagonals. I really believe it's an easy exercise and should've taken little time to finish, but my algorithm doesn't seem to work for so...
You are using d1, and d2 uninitialized in the loop, which invokes undefined behavior. You need to initialize them like this: int d1 = 0, d2 = 0, i = 0; Note that if you turn on as many warnings as possible, the compiler will warn you about these kinds of mistakes.
61,958,694
61,958,758
C++ how to check if a program is running for the first time?
Using text files as a database. How do you get your program to know if it is running for the first time? If it is run for the first time, then the application needs to create the tables where the entities will be stored. If it is not run for the first time, then it should run the application with the user data if there...
Don't. You don't care whether the program is running for the first time. You care whether the tables exist. If they don't, create them. That covers first launch and also any future "accidents".
61,958,746
61,958,774
how to convert string to int like the example given below
I have a string and i want to acces the number inside the string. I have tried something like that, string s="the number is 2."; int number= stoi(s[14]); I just want to access 2. I have used stoi but it hasn't work. what should i do?
std::stoi expects a std::string, not a char. If you want a single char, you can get it out of the string like this: int number = std::stoi(s.substr(14,1)); If you have more than 1 digit in the number you want to convert, you can just do: int number = std::stoi(s.substr(14)); which will extract as many digits after th...
61,958,793
61,959,184
Can't figure out why overloaded operator[] isn't getting called
I got a class Matrix and a class Row. Matrix has as member variable a pointer to a pointer of an object from class Row. I overloaded the operator [] for Matrix and Row. But somehow the overloaded operator from Row is never getting called and I can't figure out why not. Example Code: matrix.h class Row { int* value;...
So I just figured it out myself. I tried to call the []-operator from Matrix through mat[][], but since mat is a Row** Row& Matrix::operator[](int i) is never getting called.
61,959,099
61,960,296
Why is late binding needed in this example?
I understand why the virtual keyword is needed for overriding when objects of subclasses are dynamically created but, in the following example, why is late binding needed (virtual keyword) to override? Can't the compiler tell at compile time that pa is pointing to a derived class? class A { public: int f() { retu...
This question really does not revolve around whether the compiler can "know" or not the precise type of object pa refers to. It revolves around the semantics of C++. When you declare a method f, you are telling the compiler how you want a call to f to be handled. In the case that A::f is not declared virtual, you are s...
61,959,389
61,959,545
Using "push_back" for vector with "get" function C++
I have a class called "Region", and I have a class called "Map". The "Map" class has a vector of type "Region *" called "regions" as a member. In the .cpp file for the "Map" class, I have a "getRegions" function that returns this "regions" vector. In main.cpp, I initialize a "Region *", called "australia", and then try...
Without seeing all your code it's difficult to tell, but based on your shown code, and described behavior, my guess is that your function looks something like: auto Map::getRegions() -> std::vector<Region> { // ... return regions; } This would mean you are making a copy of the vector, and you are push_backing onto...
61,959,512
61,961,407
How to get area of convex hull of 2D points using Boost?
I'm new to boost, and everything I try results in screens full of compiler errors. Here's my latest attempt: #include <boost/geometry/algorithm/convex_hull.hpp> #include <boost/geometry/algorithm/area.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <...
The problem was with the includes. <boost/geometry.hhp> must be included. This works: #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/adapted/boost_...
61,959,944
61,960,363
Executing a non blocking thread in C++
I have a main program, this main program executes a thread that perform an action until the user triggers a stop. The problem that I have is if I add th.join() the main program won't continue until the thread finishes. And If there is no .join() the program crashs. #include <iostream> #include <thread> #include <option...
Joining a thread will cause the program to stop until that thread is finished, and that's why the program blocks. We have to call join() eventually so that all child threads finish before the program exits, but we shouldn't call join until we need the child thread to be finished. The simplest way to get the program to ...
61,960,114
61,962,948
Copy constructor with pointers fails when returned by a function
I am a new user here and this is my first question, so please don't judge me hard. I cheked many similar questiontions like this not only on this site, also on others too. But I didn't find the answer. The problem is to create copy constructor with pointers. For those people who may ask: why do you need pointers?: I h...
Let's start by making your stmt class copy correct. Once you do that, then the issues will come from other parts of your code that do not involve stmt leaking memory, or accessing invalid memory: #include <vector> #include <string> #include <algorithm> struct stmt { std::string lexeme; int *size; int *lay...
61,961,075
62,007,487
Is symbol ’ special one for boost regexp?
Regular expression: “[^”]*“ String: “lips“ Result: match String: “lips’“ Result: not match I expect both strings to match. C++ code: #include <iostream> #include <string> #include <boost/regex.hpp> using namespace std; using namespace boost; int main() { const string s1 = "“lips“"; const string s2 = "“lips’“...
boost regex library does not use utf-8 by default. utf-8 quote symbol and apostrophe have common byte, that`s why regex does not work. Code for utf-8: #include <iostream> #include <string> #include <boost/regex.hpp> #include <boost/regex/icu.hpp> using namespace std; using namespace boost; int main() { const stri...
61,961,921
61,995,070
Clangd not finding standard headers
I am using Atom to write C++ code and have installed the llvm suite to use an Atom package which uses the clangd language server. It seems to be working, except that clangd doesn't seem to find the standard headers (e.g. iostream, algorithm). I installed llvm using the prebuilt Windows binaries. The error that shows up...
I figured it out thanks to "How to use clang with mingw-w64 headers on windows". Using the llvm prebuilt binaries, clangd looks for MSVC libraries, which I did not have; I use the MinGW compilers. To have clangd look for the header files in the appropriate location, where the MinGW standard header files are located, I...
61,962,124
61,962,454
Why does my program go into endless loop when char array is overfilled?
I'm attempting to write a program in C++ that lets user enter a positive integer and a name into array with fixed size and print them out. The program seems to work correctly when I enter correct data from the first time of launching the program. The problem I'm experiencing is when entering incorrect value for Char a...
This loop is problematic: while(strlen(name) > 30) { //Loop that checks whether the cout << "Name exceeds the allowed character count!" << endl; //entered name exceeds the cin >> name; // allowed character count. } Th...
61,962,349
61,962,457
Using a static member from a derived class instead of the base class
As above, I'm trying to create a static variable name called increment_rate that has a default value of 1.05 for all Employee class. However, the Developer class (derived from Employee class) enjoys a default increment_rate of 1.10 instead (yay to programmers). In the Employee class, I have a public method called apply...
I'm not sure why there is a need for a static variable.. Assuming the apply_incr() is not static, you could very well have it like this: class Employee { public: virtual double getIncrementRate() const { return 1.05; } } class Developer : Employee { public: virtual double getIncrementRate() const override { ...
61,962,539
62,917,113
How can I get the value of a widget the exact moment a button is clicked FLTK
The goal is to be able to get the value of a widget such as FL_Input when I click my button. One way I could do this is by using events and classes. Such as #include <FL/Fl.H> #include <FL/Fl_Window.H> #include <FL/Fl_Button.H> #include <iostream> using namespace std; class MyButton : public Fl_Button { static int...
You may define a new class derivated from Fl_Input which has a member of type std::vector<std::string> where you store the text written in your input field. #ifndef __MYINPUT_H #define __MYINPUT_H #include <FL/Fl_Window.H> #include <FL/Fl.H> #include <FL/Fl_Input.H> #include <iostream> #include <vector> class myinpu...
61,962,786
61,962,869
Error passing values into array/values in array missing
I have a text file and I passed it to a char array. It was fine when I display in a getline() loop but after going through encryption, only the last line is encrypted and displayed. I have tried to display values in array before entering shift key and what is inside the array is the last line of the text only. What has...
This is wrong because you need to use strcat too // Read file into char array ifstream infile("plaintext.txt"); while (getline(infile, plaintext)) { strcpy_s(msg, plaintext.c_str()); for (int i = 0; i < plaintext.length(); i++) { cout << msg[i]; } } Instead: // Read file into char array ifstrea...
61,963,192
61,980,883
MPI memory corruption on specific core counts only
For some background, I'm working on parallelizing a basic PDE solver with MPI. The program takes a domain and assigns each processor a grid covering a portion of it. If I run with a single core or four cores, the program runs just fine. However, if I run with two or three cores, I get a core dump like the following: **...
It turns out there was an error in my Grid constructor while assigning points (it read points[0][j] = ... while assigning the y points) that I somehow caught and corrected while I was copying the code into my post but not in my code. The error only showed up in 2 and 3 core runs because the grid was perfectly square fo...
61,963,213
61,963,318
I wanted to reverse my array. Why this code gives garbage value?
#include <iostream> using namespace std; int main(){ int n; int a[n]; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } for(int i=n;i>=0;i--){ cout<<a[i]<<" "; } } Input:- 4 1 2 3 4 Output 4199008 4 3 2 1
For starters the program has undefined behavior because the variable n is not initialized int n; So this declaration int a[n]; is invalid. Moreover variable length arrays is not a standard C++ feature. Instead use the standard class template std::vector. Also within this loop for(int i=n;i>=0;i--) { cout<<a[i]<<" ...
61,963,379
61,963,676
How to use std::find() with a 2d std: array?
I am writing a function CreateGrid() that is trying to take a std::string and a 2d std::array as parameters, and put the individual characters from the std::string into the array. The rest of the array, if space is left, should be filled with the alphabetical characters A-Y, inclusive, in alphabetical order, providing ...
This is not normally trivial since you have nested arrays. std::find can only return an iterator to the outer array, which isn't useful if you need to change the value in the inner array. However, I notice that you don't actually use it other than to see if the sought element was located. So, we can redefine the oper...