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
69,428,557
69,437,512
Is it possible to explicitly specify template arguments in a generic lambda passed to a function?
I want to create a compile-time loop over a small container (like 4-8 elements) with a size known at compile time. It's not hard to create just one simple loop: I can create a template functor F with operator() overloaded and call it like in the code below constexpr std::array<T, N> array{/*fill the array*/}; template <std::size_t index> struct F { void operator()() { std::vector<T> some_container{/*fill it in runtime*/}; some_container[index + some_offset] += std::get<index>(array); // Use safe array access } }; template <template<std::size_t> typename F, std::size_t... I> void iterator_implementation( const std::index_sequence<I...> /*unused*/) { ((F<I>{}()), ...); } template <template<std::size_t> typename F> void iterator() { iterator_implementation<F>(std::make_index_sequence<array.size()>{}); } Though, if I want to create ten such loops and want to conveniently pass a bunch of references with it (closure), I should definitely use lambda functions. In order to use std::get in the lambda, I should use generic lambdas. So, the functor from the example below may become auto f = [&some_container, some_offset]<std::size_t index>() { some_container[index + some_offset] += std::get<index>(array); // Use safe array access }; I cannot simply pass this lambda to the iterator because it's impossible to pass a variable of a template type without specifying template parameters, and also I cannot simply get a type of the lambda and provide it as an F in order to call F<I>{} to recreate the lambda. If I use typename F instead of template<std::size_t> typename F, I cannot call f<I> because typename has no template parameters, so cannot be used with them. I can also pass std::get<index>(array) and index as ordinary arguments to the lambda function and avoid usage of template parameter but saving the safety of the access. Though, I wish to try using compile-time constants wherever it's possible in order to check how it works. I believe that passing a compile-time constant numeric as a template argument may help the compiler to optimize my code more than if the number is an ordinary variable in my code (even though smart compiler should "see" this and optimize the call). So, it's a question about new knowledge rather than discussing whether such an approach will help. Is it possible to use generic lambda in a fold of parameter pack as I need? P. S. Despite the question title, it's not a duplicate of How to pass generic lambda into function because in my question template parameter should be specified explicitly, while in that question it can be deduced.
In a generic lambda, operator() is a template, but the lambda type is not. Instead of instantiating a template at an index F<I>{}(), one needs to instantiate operator() at an index. Since the lambda has captures, one will need to pass it instead of just the type as a template argument. Replace: template <template<std::size_t> typename F, std::size_t... I> void iterator_implementation( const std::index_sequence<I...> /*unused*/) { ((F<I>{}()), ...); } with: template <typename F, std::size_t... I> void iterator_implementation(F f, const std::index_sequence<I...> /*unused*/) { ((f.template operator()<I>()), ...); } Full example: https://godbolt.org/z/rYTP1KTYc
69,428,611
69,429,164
Using std::make_unique with the GetProfileBinary function call
I have seen this answer (Advantages of using std::make_unique over new operator) where it states: Don't use make_unique if you need a custom deleter or are adopting a raw pointer from elsewhere. This is is my code: void CAutomaticBackupSettingsPage::GetLastBackupDate(COleDateTime& rBackupDate) { DATE* pDatTime = nullptr; UINT uSize; theApp.GetProfileBinary(_T("Options"), _T("BackupLastBackupDate"), pointer_cast<LPBYTE*>(&pDatTime), &uSize); if (uSize == sizeof(DATE)) rBackupDate = *pDatTime; else rBackupDate = COleDateTime::GetCurrentTime(); delete[] pDatTime; pDatTime = nullptr; } Code analysis gives me two warnings: and The latter warning suggests I use std::make_unique but since my pointer data is returned from the GetProfileBinary call, and given the statement in the related question, does that mean I should not use std::make_unique? I admit it is something I have not done before. The useage of GetProfileBinary clearly states: GetProfileBinary allocates a buffer and returns its address in *ppData. The caller is responsible for freeing the buffer using delete[].
pDateTime is supposed to be nullptr, and GetProfileBinary handles the allocation. Code Analysis mistakenly thinks you forgot the allocation. It does need to check for success before calling delete[]. We can't use delete[]pDatTime because pDatTime is not an array. But GetProfileBinary allocates using new BYTE[size], so we need to cast back to BYTE. You can also add a NULL check before reading pDatTime, that might make Code Analysis happy. if (pDatTime && uSize == sizeof(DATE)) rBackupDate = *pDatTime; else rBackupDate = COleDateTime::GetCurrentTime(); if(pDatTime) delete[](BYTE*)pDatTime; You can use std::unique_ptr<BYTE[]> cleanup((BYTE*)pDatTime) for deletion, but this has to be after GetProfileBinary is called. Example: DATE* pDatTime = nullptr; GetProfileBinary(_T("Options"), _T("BackupLastBackupDate"), (LPBYTE*)(&pDatTime), &uSize); std::unique_ptr<BYTE[]> cleanup((BYTE*)pDatTime); //automatic delete if (pDatTime && uSize == sizeof(DATE)) rBackupDate = *pDatTime; else rBackupDate = COleDateTime::GetCurrentTime(); //pDatTime = NULL; <- Error when used with unique_ptr ... //pDatTime is deleted later, when `cleanup` goes out of scope
69,428,657
69,428,749
Convert const wchar_t* to LPWSTR
I'm trying to convert a const wchar_t* to LPWSTR but I'm getting the error E0513. I'm using Visual Studio with C++17. Here is my code: int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LPWSTR* argv; int argCount; argv = CommandLineToArgvW(GetCommandLineW(), &argCount); if (argv[1] == nullptr) argv[1] = L"2048"; <-- conversion error } How to fix this?
To answer your question: You can use const_cast: argv[1] = const_cast<LPWSTR>(L"2048"); Or a local wchar_t[] array: wchar_t arg[] = L"2048"; argv[1] = arg; However, CommandLineToArgvW() will never return any array elements set to nullptr to begin with. All array elements are null-terminated string pointers, so empty parameters would have to be specified as quoted strings ("") on the command-line in order to be parsed, and as such will be returned as 0-length string pointers in the array. So, you would need to check for that condition instead, eg: if (argCount > 1 && *(argv[1]) == L'\0')
69,428,696
69,441,331
How to replace the RCData of an executable?
I'm trying to modify the RCData of a compiled AutoHotkey script: void ReplaceStringTable() { HANDLE hRes = BeginUpdateResource( _T( "C:\\Users\\CAIO\\Documents\\Github\\main\\scripts\\ahkDebug\\Novo(a) AutoHotkey Script.exe" ), FALSE ); if ( hRes != NULL ) { std::wstring data[] = { L"MsgBox Test" }; std::vector< WORD > buffer; for ( size_t index = 0; index < sizeof( data ) / sizeof( data[ 0 ] ); ++index ) { size_t pos = buffer.size(); buffer.resize( pos + data[ index ].size() + 1 ); buffer[ pos++ ] = static_cast< WORD >( data[ index ].size() ); copy( data[ index ].begin(), data[ index ].end(), buffer.begin() + pos ); } UpdateResource( hRes, RT_RCDATA, L">AUTOHOTKEY SCRIPT<", //MAKEINTRESOURCE( 1 ), 1033, //MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), reinterpret_cast< void* >( &buffer[ 0 ] ), buffer.size() * sizeof( WORD ) ); EndUpdateResource( hRes, FALSE ); } } However, this is the result after running the code: The code does add an empty blank line (line 1), this line makes the exe not work correctly, how do I get rid of it?
You need to use std::string instead of std::wstring, as AHK is expecting 8bit characters, not 16bit characters. Also, you need to get rid of your vector, as AHK does not expect each line to be prefixed by its length. Try this instead: void ReplaceStringTable() { HANDLE hRes = BeginUpdateResource( TEXT( "C:\\Users\\CAIO\\Documents\\Github\\main\\scripts\\ahkDebug\\Novo(a) AutoHotkey Script.exe" ), FALSE ); if ( hRes != NULL ) { std::string data = "MsgBox Test"; UpdateResource( hRes, RT_RCDATA, L">AUTOHOTKEY SCRIPT<", //MAKEINTRESOURCE( 1 ), 1033, //MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), const_cast<char*>(data.c_str()), data.size() ); EndUpdateResource( hRes, FALSE ); } }
69,428,979
69,429,072
my (find & replace) method is not working properly
I am actually trying to code a program to perform (find & replace) on a given string but it is not working properly (it partially works specially in the first occurrence). any idea? here is below the code: string Find_Replace(string str,string substr,string replacement){ int x = substr.length(); int i = 0; for(i = str.find(substr,0);i!=string::npos;i=str.find(substr,i)){ str.replace(i,i+x,replacement); i++; } return str; } int main(){ cout << "Please enter a text:-" << endl; string str; string substr; string replacement; getline(cin, str); cout<<"Please enter a word to find:-"<<endl; getline(cin,substr); cout<<"Please enter the replacement text:-"<<endl; getline(cin,replacement); cout<<"The text after process:-"<<endl; cout<<Find_Replace(str,substr,replacement); return 0; }
This call of the member function replace str.replace(i,i+x,replacement); is incorrect. The second argument must specify the number of characters to be replaced. The function should be defined the following way std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement ) { auto n1 = substr.length(); auto n2 = replacement.size(); for( auto pos = str.find( substr, 0 ); pos != std::string::npos; pos = str.find(substr, pos ) ) { str.replace( pos, n1, replacement ); pos += n2; } return str; } Here is a demonstrative program. #include <iostream> #include <string> std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement ) { auto n1 = substr.length(); auto n2 = replacement.size(); for( auto pos = str.find( substr, 0 ); pos != std::string::npos; pos = str.find(substr, pos ) ) { str.replace( pos, n1, replacement ); pos += n2; } return str; } int main() { std::string s( "Hello World!" ); std::cout << Find_Replace( s, "World", "C++ strings" ) << '\n'; return 0; } The program output is Hello C++ strings!
69,429,078
69,435,207
Cmake - select different c++ standard for different sources
As the title suggest, I'd like to use cmake to build a project, and depending on the source file, enforcing a different c++ standard. The reason is : I am working on a library and would like to make it c++03 compliant for compatibility, but would like to use Google test suite which requires c++11. So the unit tests would be compiled with c++11, but I'd like my library to fail at compilation if there is reference to a c++11 only feature.
So just do that - ompile your library with one standard, and your tests with the other. Nowadays, https://stackoverflow.com/a/61281312/9072753 method should be preferred. add_library(mylib lib1.cpp) set_target_properties(mylib PROPERTIES CXX_STANDARD 03 CXX_EXTENSIONS off ) add_executable(mytest main.cpp) set_target_properties(mytest PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS off ) target_link_libraries(mytest PRIVATE mylib) add_test(NAME mytest COMMAND mytest)
69,429,111
69,429,190
Why rvalue reference member would be const?
I am trying to write a move constructor for a structure but I can't understand why I fail to call the move constructor of structure member: #include <memory> struct C { std::unique_ptr<int[]> mVector; size_t mSize; C() = default; C(C &&temp) : mVector(temp.mVector) , mSize(temp.mSize) {} }; When I compile this I get: gcc -c TempTest.cpp TempTest.cpp: In constructor 'C::C(C&&)': TempTest.cpp:9:23: error: use of deleted function 'std::unique_ptr<_Tp [], _Dp>::unique_ptr(const std::unique_ptr<_Tp [], _Dp>&) [with _Tp = int; _Dp = std::default_delete<int []>]' 9 | , mSize(temp.mSize) | ^ In file included from c:/msys64/mingw64/include/c++/10.3.0/memory:83, from TempTest.cpp:1: c:/msys64/mingw64/include/c++/10.3.0/bits/unique_ptr.h:723:7: note: declared here 723 | unique_ptr(const unique_ptr&) = delete; | ^~~~~~~~~~ Because in contructor temp is a rvalue reference, it is non-const so temp.mVector should be non-const and should call the unique_ptr move constructor but instead it calls the copy constructor which is deleted. Any idea where is the error?
Why rvalue reference member would be const? Don't assume that it's const. You should assume that unique_ptr(const unique_ptr&) is merely the best match, from the available constructors. Because in constructor temp is a rvalue reference Surprise! It is not an r-value reference. The variable temp is bound to an r-value, when the constructor is called. And now that it's a named variable, it's no longer a "temporary". It has become an l-value. Since you know that the value was an r-value when the constructor was called, you can safely move the members, converting them back to an r-value. C(C &&temp) : mVector(std::move(temp.mVector)) // ^^^^^^^^^ We know that temp CAME FROM an r-value, // so it can safely be moved. , mSize(temp.mSize) {}
69,429,827
69,430,110
Providing an allocator for Boost's `cpp_dec_float_100`
I have a dataset stored in .root file format (from the CERN ROOT framework) as type cpp_dec_float_100 (from the boost::multiprecision library). This data is read into an std::vector<cpp_dec_float_100>. By default, cpp_dec_float_100 is unallocated. If I were to try to read this data into a vector as-is, an std::bad_alloc is thrown. So, I've taken the advice of the Boost docs and provided a generic allocator, which seems to solve the issue (and appears to cut the size the resulting vector in half). Ultimately, I want to pass this vector as an argument to a function that I've written, which performs binary search on a vector to find the element of that vector closest to a given value: #include <boost/multiprecision/cpp_dec_float.hpp> using Mult_t = boost::multiprecision::cpp_dec_float<100, int, allocator<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<100>>>>; std::vector<Mult_t>::iterator search(std::vector<Mult_t> &vec, Mult_t value){ auto it = lower_bound(vec.begin(), vec.end(), value); if(it != vec.begin()){ if(abs(value - *(it - 1)) < abs(value - *it)){ --it; } } return it; } I'm using the "alias" Mult_t as the alternative is a bit of a mouthful. So, given the vector vec and the value val, this finds the element in vec nearest to val. If I use the cpp_dec_float_100 type as-is (i.e. Mult_t = boost::multiprecision::cpp_dec_float_100), this works great. However, when I attempt to provide an allocator, I'm given the error: In module 'std' imported from input_line_1:1: /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../include/c++/4.8.5/bits/stl_algobase.h:965:18: error: invalid operands to binary expression ('boost::multiprecision::backends::cpp_dec_float<100, int, std::allocator<boost::multiprecision::number<boost::multiprecision::backends::cpp_dec_float<100, int, void>, boost::multiprecision::expression_template_option::et_on> > >' and 'const boost::multiprecision::backends::cpp_dec_float<100, int, std::allocator<boost::multiprecision::number<boost::multiprecision::backends::cpp_dec_float<100, int, void>, boost::multiprecision::expression_template_option::et_on> > >') if (*__middle < __val) I don't quite understand what's going on here (I doubt seriously it has anything to do with the allocator), and the error message isn't terribly insightful.
Your problem has nothing to do with allocator, just because cpp_dec_float<...> has no operator<(), only number<cpp_dec_float<...>> supports. You should redefine your Mult_t as: using namespace boost::multiprecision; using Mult_t = number< cpp_dec_float<100, int, std::allocator<number<cpp_dec_float<100>>>>>;
69,430,143
69,430,188
Returning objects constructed in lambda in transform
The following function does something different than I want, which is to return the matches. If I call it on vector<string>{"a b", "cd ef"}, the output is cd cd ef instead of a b cd ef Why? #include <regex> using namespace std; void f(const vector<string>& v) { vector<smatch> P{}; transform(begin(v), end(), back_inserter(P), [](auto s){ auto m = *new smatch; regex_match(s, m, regex{"(\\S*) (\\S*) ?(.*)"}); return m; }); for (auto s: P) cout << s[0] << endl; // debug output } It's the same if I try without new: smatch m{};. Which I believe I shouldn't do, because then the smatch is allocated on the stack and invalidated when the lambda function returns. (I even tried smatch m;, but that should create an uninitialized variable. Oddly, it works with no runtime error, giving the same wrong result.) And the following doesn't even compile, giving an error I don't understand: #include <regex> using namespace std; void f(const vector<string>& v) { vector<smatch> P{}; transform(begin(v), end(), back_inserter(P), [](auto s){ auto m = new smatch; regex_match(s, m, regex{"(\\S*) (\\S*) ?(.*)"}); cout << (*m)[0] << endl; return m; }); for (auto s: P) cout << (*s)[0] << endl; }
For std::match_results: Because std::match_results holds std::sub_matches, each of which is a pair of iterators into the original character sequence that was matched, it's undefined behavior to examine std::match_results if the original character sequence was destroyed or iterators to it were invalidated for other reasons. The parameter s of the lambda is passed by-value, it'll be destroyed when get out of the lambda. You can change it to pass-by-reference: void f(const vector<string>& v) { vector<smatch> P; transform(begin(v), end(v), back_inserter(P), [](auto& s){ // ^ smatch m; regex_match(s, m, regex{"(\\S*) (\\S*) ?(.*)"}); return m; }); for (auto s: P) cout << s[0] << endl; // debug output }
69,430,164
69,432,184
How to calculate the sum of an array in parallel using C++ and OpenMP?
my task is to parallelize the creation, doubling, and summation of the array seen in my code below using C++ and OpenMP. However, I cannot get the summation to work in parallel properly. This is my first time using OpenMP, and I am also quite new to C++ as well. I have tried what can be seen in my code below as well as other variations (having the sum outside of the for loop, defining a sum in parallel to add to the global sum, I have tried what is suggested here, etc). The sum should be 4.15362e-14, but when I use multiple threads, I get different results each time that are incorrect. What is the proper way to achieve this? P.S. We have only been taught the critical, master, barrier, and single constructs thus far so I would appreciate if answers would not include any others. Thanks! #include <iostream> #include <cmath> #include <omp.h> using namespace std; int main() { const int size = 256; double* sinTable = new double[256]; double sum = 0.0; // parallelized #pragma omp parallel { for (int n = 0; n < size; n++) { sinTable[n] = std::sin(2 * M_PI * n / size); // calculate and insert element into array sinTable[n] = sinTable[n] * 2; // double current element in array #pragma omp critical sum += sinTable[n]; // add element to total sum (one thread at a time) } } // print sum and exit cout << "Sum: " << sum << endl; return 0; }
Unfortunately your code is not OK, because you run the for loop number of thread times instead of distributing the work. You should use: #pragma omp parallel for to distribute the work among threads. Another alternative is to use reduction: int main() { const int size = 256; const double step = (2.0 * M_PI) / static_cast<double>(size); double* sinTable = new double[size]; double sum = 0.0; // parallelized #pragma omp parallel for reduction(+:sum) for (int n = 0; n < size; n++) { sinTable[n] = std::sin( static_cast<double>(n) * step); // calculate and insert element into array sinTable[n] = sinTable[n] * 2.0; // double current element in array sum += sinTable[n]; // add element to total sum (one thread at a time) } // print sum and exit cout << "Sum: " << sum << endl; delete[] sinTable; return 0; } Note that in theory the sum should be zero. The value you obtain depends on the order of additions, so slight difference can be observed due to rounding errors. size=256 sum(openmp)=2.84217e-14 sum(no openmp)= 4.15362e-14 size=512 sum(openmp)=5.68434e-14 sum(no openmp)= 5.68434e-14 size=1024 sum(openmp)=0 sum(no openmp)=-2.83332e-14 Here is the link to CodeExplorer.
69,430,274
69,430,326
How to retrieve full file path from DIR pointer?
From a DIR* variable from <dirent.h>, how do I get the full file path (e.g. "/home/ubuntu/Desktop/planning")? Note: This needs to work on Linux.
There's nothing in the DIR object that gives you the name of the directory that the DIR object is reading. There is no function in the C library that does this. You will need to implement this logic yourself. Wherever you open a DIR: save the name of the directory you opened, and consult it as needed. Or, in modern C++, you can also use the filesystem library, instead of this C API.
69,430,434
69,508,314
How would I implement this maximumGrade function?
#include <fstream> // For file handling #include <iomanip> // For formatted output #include <iostream> // For cin, cout, and system #include <string> // For string data type #include "CourseGrade.h" using namespace std; CourseGrade* maximumGrade(CourseGrade* course0, CourseGrade* course1) { } int main() { cout << "Course Grade App!" << endl; cout << "--------------------------" << endl; cout << endl; //Prompting and creating CourseGrade objects and pointer values from inputs int c1; float g1; cout << "Please enter the first course and its grade: "; cin >> c1 >> g1; CourseGrade Course0(c1, g1); CourseGrade* ptrCourse0; ptrCourse0 = &Course0; int c2; float g2; cout << "Please enter the second course and its grade: "; cin >> c2 >> g2; CourseGrade Course1(c2, g2); CourseGrade* ptrCourse1; ptrCourse1 = &Course1; int c3; float g3; cout << "Please enter the third course and its grade: "; cin >> c3 >> g3; CourseGrade Course2(c3, g3); CourseGrade* ptrCourse2; ptrCourse2 = &Course2; cout << "-----------------------------------" << endl; cout << "Course" << setw(10) << "Grade" << endl; cout << "-----------------------------------" << endl; cout << ptrCourse0->getCourse() << setw(10) << ptrCourse0->getGrade() << endl; cout << ptrCourse1->getCourse() << setw(10) << ptrCourse1->getGrade() << endl; cout << ptrCourse2->getCourse() << setw(10) << ptrCourse2->getGrade() << endl; cout << "-----------------------------------" << endl; cout << "The course with the maximum grade is: " << maximumGrade(ptrCourse0, ptrCourse1) << endl; cout << "The average grade is: " << (ptrCourse0->getGrade() + ptrCourse1->getGrade() + ptrCourse2->getGrade()) / 3 << endl; } // End of main.cpp void CourseGrade::setCourse(int c) { if (c >= 1000 && c <= 9999) { course = c; } } void CourseGrade::setGrade(float g) { if (g >= 0.00 && g <= 100.00) { grade = g; } } int CourseGrade::getCourse() const { return course; } float CourseGrade::getGrade() const { return grade; } CourseGrade::CourseGrade(int c, float g) { if (c >= 1000 && c <= 9999) { course = c; } else { course = 1000; } if (g >= 0.00 && g <= 100.00) { grade = g; } else { grade = 0.00; } } Can you guys please help me out? I have three objects due to the prompt, but it only asks for two pointers? I am completely unaware of how to get the maximumGrade to show the course with the largest grade. I have tried using if statements to compare the grades of the two pointers showing the values of the grades. It HAS to use pointers to compare the course grades. Thank you guys!
I have three objects due to the prompt, but it only asks for two pointers? The only way to make sense of two pointers passed to maximumGrade is to assume that these are the beginning and end of an array which contains the three objects. CourseGrade courses[3] = { Course0, Course1, Course2 }; cout << "The course with the maximum grade is: " << maximumGrade(courses, courses+3)->getCourse() << endl; The body of maximumGrade can then be e. g. CourseGrade *c = NULL; float g = 0; // current maximum for (; course0 < course1; ++course0) if (g <= course0->getGrade()) g = (c = course0)->getGrade(); return c;
69,430,521
69,433,278
Building simple function to inherit 3 classes in C++
I have created 3 classes - GrandMother, Mother and Daughter. I wrote a code such that the Daughter class inherits from the Mother class and the Mother class inherits from the GrandMother calss. GrandMother.h :- #ifndef GRANDMOTHER_H #define GRANDMOTHER_H class GrandMother { public: GrandMother(); ~GrandMother(); }; #endif // GRANDMOTHER_H Mother.h :- #ifndef MOTHER_H #define MOTHER_H class Mother: public GrandMother { public: Mother(); ~Mother(); }; #endif // MOTHER_H Daughter.h :- #ifndef DAUGHTER_H #define DAUGHTER_H class Daughter: public Mother { public: Daughter(); ~Daughter(); }; #endif // DAUGHTER_H GrandMother.cpp :- #include<iostream> #include "Mother.h" #include "Daughter.h" #include "GrandMother.h" using namespace std; GrandMother::GrandMother() { cout << "Grand Mother Constructor!!" << endl; } GrandMother::~GrandMother() { cout << "Grand Mother Deconstroctor" << endl; } Mother.cpp :- #include<iostream> #include "Mother.h" #include "Daughter.h" #include "GrandMother.h" using namespace std; Mother::Mother() { cout << "Mother Constructor!!" << endl; } Mother::~Mother() { cout << "Mother Deconstroctor" << endl; } Daughter.cpp:- #include<iostream> #include "Mother.h" #include "Daughter.h" #include "GrandMother.h" using namespace std; Daughter::Daughter() { cout << "Daughter Constructor!!" << endl; } Daughter::~Daughter() { cout << "Daughter Deconstroctor" << endl; } main.cpp :- #include<iostream> #include "Mother.h" #include "Daughter.h" #include "GrandMother.h" using namespace std; int main(){ //GrandMother granny; //Mother mom; Daughter baby; } When I am running the code, it's giving me the following error:- error: expected class-name before '{' token Can anyone plz tell me what part of my code is wrong.
Your header are not self-contained, so you have to include them in right order: #include "GrandMother.h" #include "Mother.h" #include "Daughter.h" but it is fragile. Right way is to make the header self contained: #ifndef GRANDMOTHER_H #define GRANDMOTHER_H class GrandMother { public: GrandMother(); ~GrandMother(); }; #endif // GRANDMOTHER_H #ifndef MOTHER_H #define MOTHER_H #include "GrandMother.h" class Mother: public GrandMother { public: Mother(); ~Mother(); }; #endif // MOTHER_H #ifndef DAUGHTER_H #define DAUGHTER_H #include "Mother.h" class Daughter: public Mother { public: Daughter(); ~Daughter(); }; #endif // DAUGHTER_H
69,430,685
69,430,788
Getting NaN value when raising double by a fractional exponent of 1/3
I'm new to C++ so if there is a quick solution to this question please let me know in the comments. I'm working on a third-degree polynomial equation solver application, and for that I need to divide a certain double value by a fractional exponent, which in this case is 1/3. Here is the code so far: #include <iostream> #include <valarray> #include <vector> #include <iomanip> using namespace std; void solveEquation(double a, double b, double c, double d); int main() { double a, b, c, d; cout << "Input a value for 'a': " << endl; cin >> a; cout << "Input a value for 'b': " << endl; cin >> b; cout << "Input a value for 'c': " << endl; cin >> c; cout << "Input a value for 'd': " << endl; cin >> d; solveEquation(a, b, c, d); return 0; } void solveEquation(double a, double b, double c, double d) { vector<double> frac_vector1{((pow(-b, 3)) / (27 * pow(a, 3))), ((b * c) / (6 * pow(a, 2))), -(d / (2 * a))}; double frac_vector1_result = 0; for (double frac : frac_vector1) { frac_vector1_result += frac; } double frac_vector1_result_pow = pow(frac_vector1_result, 2); vector<double> frac_vector2 {(c/(3 * a)), -((pow(b, 2))/(9 * pow(2, a)))}; double frac_vector2_result = 0; for (double frac : frac_vector2) { frac_vector2_result += frac; } double frac_vector2_result_pow3 = pow(frac_vector2_result, 3); double first_half = (frac_vector1_result + sqrt(frac_vector1_result_pow + frac_vector2_result_pow3)); cout << pow(first_half, 1.0/3.0); //isNan ? } When I input a = -0.71, b = -0.3, c = 2.2, and d = -1.46 I get a NaN value, which is not what I get in a calculator. When I debug this I get the following value for first_half: When I raise this value to 1/3 in Desmos I get -0.853432944643. It's not like I am square rooting a negative number (it's 1/3 not 1/2) so why am I getting this problem? Cheers, Tom
pow does not support taking roots of negative number in this fashion. cppreference on std::pow: Error handling Errors are reported as specified in math_errhandling. If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur. C++ provides a function for directly computing the cube root, std::cbrt: std::cbrt(first_half); This means you don't need to worry about what sign first_half ends up being to avoid domain errors.
69,431,523
69,431,576
Calling member function through const qualified object gives error as function is not marked as const?
Code #include <iostream> class A { public: mutable int x; mutable int y; A(int k1 = 0, int k2 = 0) :x(k1), y(k2) {} void display() { std::cout << x << "," << y << "\n"; } }; int main() { const A a1; a1.x = 3; a1.y = 8; a1.display(); return 0; } Output Error: 'this' argument to member function 'display' has type 'const A', but function is not marked const I am just calling member function A::display() through const qualified object a1. So why line a1.display() is giving an error ?
Why line a1.display() is giving an error ? The mutable variable let you modify the member variables inside a const qualified function. It does not allow you to be able to call the non-const qualified member function to be called via a const qualified instance. Therefore, you need a const member function there.
69,431,615
69,444,675
input inside of while loop without waiting for user
I am going to write a program in which there is a while loop in which the user can input the program at any time, but the while loop does not wait to receive the user input and continues to work. Whenever a user enters a new input, the program will run according to that input. The program is in C ++ and the name of the program is Snake Game. I'm sorry because my code is too long, I can show a small part of it. while(1) { Move(grid,snake,grid_rows,grid_cols,len_snake,ch); show(grid,grid_rows,grid_cols); Sleep(1000); cin>>ch; system("CLS"); }
thank you pepijn kramer.With your help, I completed my program. while (1) { system("CLS"); show(grid,grid_rows,grid_cols); if (_kbhit()) { ch = _getch(); } Move(grid,snake,grid_rows,grid_cols,len_snake,ch); check_(grid,snake,grid_rows,grid_cols,len_snake); Sleep(500); }
69,431,700
69,431,899
How does C++ "send" temporary values to functions by value?
I have a simple snippet: class Object { private: int value; public: Object(int value) : value(value) { cout << "Object::ctor\n"; } Object(const Object& obj) { cout << "Object::copy-ctor\n"; } Object(Object&& obj) { cout << "Object::move-ctor\n"; } }; Object take_and_return_obj(Object o) { return o; } int main() { Object o(5); take_and_return_obj(o); } Now, this, as expected, prints a copy and move constructor. Object::copy-ctor Object::move-ctor This is because o gets copied into the function using the copy-ctor, and then gets sent back using the move-ctor since the function is over and the return value is an xvalue. However, something happens when the initial argument to the function is also an xvalue: int main() { Object o = take_and_return_obj(Object(5)); } What happens is that somehow nothing happens when the value is sent to the function: Object::ctor Object::move-ctor I assume that the move is for the return operation, so that is not affected by this change. However there is no copy-ctor called to create the o inside the function's scope. I know its not any kind of pointer or reference since I made the function take the argument by value. So my question is: what exactly happens to the xvalue I create in main so that the argument inside the function gets its value? This is more of an educational question, so do not be afraid to go into more in-depth answers.
Yes, in take_and_return_obj(Object(5));, the copy/move operation for constructing parameter o is elided; which is guaranteed since C++17. Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible: ... ... In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type: T x = T(T(f())); // only one call to default constructor of T, to initialize x
69,431,723
69,431,894
My while loops and else if loops don't work
I am trying to have the letter show with the appropriate grade. Then I would like the program to ask me over and over my midterm and my final score. Then give the appropriate grade for that score as of now it only give me the scores of the first run. #include <iostream> #include <iomanip> using namespace std; int main() { int midterm; int final; cout << "please enter midterm grade: "; cin >> midterm; while (midterm < 0 || midterm > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. please enter grade: "; cin >> midterm; } cout << " please enter final grade: "; cin >> final; while (final < 0 || final > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. Please enter grade"; cin >> final; } int total; total = final + midterm; cout << "total"; if (total > 360 || total <=400) { cout << "your letter grade is A"; } else if (total > 320 || total < 359) { cout << "your letter grade is B"; } else if (total > 280 || total < 319) { cout << "your letter grade is C"; } else if (total > 279 || total < 241) { cout << "your letter grade is D"; } else if (total < 240) { cout << "your letter is F"; } }
Fixed few logical errors in if statements and few other errors (explanation is at the end). I hope this modified code does the required task: #include <iostream> #include <iomanip> using namespace std; int main() { int midterm=0; int final=0; cout << "please enter midterm grade: "; cin >> midterm; while (midterm < 0 || midterm > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. please enter grade: "; cin >> midterm; } cout << "please enter final grade: "; cin >> final; while (final < 0 || final > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. Please enter grade"; cin >> final; } int total; total = final + midterm; cout << "total: "<<total << endl; if (total > 360 && total <= 400) { cout << "your letter grade is A"; } else if (total > 320 && total <= 360) { cout << "your letter grade is B"; } else if (total > 280 && total <= 320) { cout << "your letter grade is C"; } else if (total > 240 && total <= 280) { cout << "your letter grade is D"; } else if (total <= 240) { cout << "your letter is F"; } } Sample Output: please enter midterm grade: 100 please enter final grade: 150 total: 250 your letter grade is D For explanation, I haven't done much, I just replaced the || inside if statements with && and also modified the values so that no value is left out and also changed cout << "total" to cout << "total: "<<total << endl; so that it shows the output and prints next output (grade) in next line and i also initialised the variables with 0
69,432,326
69,432,394
Protecting against Time-of-check to time-of-use?
I was reading: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use They showed this code to be buggy and I totally understand why it's so: if (access("file", W_OK) != 0) { exit(1); } // Attacker: symlink("/etc/passwd", "file"); fd = open("file", O_WRONLY); // Actually writing over /etc/passwd write(fd, buffer, sizeof(buffer)); But the real question is how to protect against this type of exploits?
You can use the O_NOFOLLOW flag. It will cause the open to fail if basename of the path is a symbolic link. That would solve the described attack. To cover links along the directory path, you can check whether frealpath(fd, ...) matches what you would expect. Another way to prevent a process from overwriting /etc/passwd is to run it as non-root so that it won't have permission. Or, you can use chroot - or more generally, a container - to prevent the host system's /etc/passwd being visible to the process. More generally though, filesystem TOCTOU is unsolvable at the moment on Linux. You would need transaction support either on filesystem or system call level - which are lacking.
69,432,375
69,432,395
Default constructed std::priority_queue with a lambda
I mistakenly omitted the compare argument when defining a std::priority_queue: #include <queue> int main() { constexpr auto cmp{[](int a, int b) { return a > b; }}; std::priority_queue<int, std::vector<int>, decltype(cmp)> pq; } , and it compiled successfully and worked properly when I used it to implement Dijkstra's algorithm. Then I realized that I passed only the type information of cmp when constructing pq. However, the code compiles only if --std=c++20 flag is used. I skimmed the priority_queue reference on cppreference.com but couldn't find any notice about a change that occurred since C++20. I used the following version of g++: g++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0 Is this an intended behavior since C++20, and if so, what has affected this change?
The change happened on lambdas. If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does not actually capture anything). (Since C++20) Before C++20, lambda closure types are not DefaultConstructible, the comparator object can't be default-constructed in the default constructor of std::priority_queue, then you have to pass the lambda object to the constructor of std::priority_queue taking comparator object. constexpr auto cmp{[](int a, int b) { return a > b; }}; std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);
69,432,461
69,432,530
Undeclared identifier error on using square() function given in a book
I came across the square() function in a book on C++. On implementing the function as given in the book Xcode gives an 'undeclared identifier' error. I have tried including 'cmath' and 'math.h' header files but it doesn't seem to fix the issue. I cannot find a header file for it and I am not even sure if that's the actual problem. #include <iostream> #include <cmath> using namespace std; int main() { for(int x=0; x<10; ++x) { cout<< x << '\t' << square(x) << endl; } } EDIT: The book is called principles of C++ by Bjarne (the creator of C++) And this guy wrote a whole chapter on Statements explaining it with several examples containing the undefined function square(). After 10 or so examples the next chapter starts with- "In the program above, what was square(i)?" The code that confused me Next chapter
There is no square() function in the c++ standard library, you need to implement it. Anyway, there is the function pow(number, power), it calculates the power of a number, you can use it including the cmath header.
69,432,829
69,433,323
nanopb oneof - encoding problems
I am trying to encode a message using oneof - and the size does not seem ok. Looks like this is ignoring the oneof part - and not encoding it into the stream. The encoding functions all return "TRUE" - which means that they encoded as I requested, which means I encoded wrong... I am missing something very silly. static auto encode(const pb_msgdesc_t *fields, const void *msg) -> std::vector<pb_byte_t> { size_t size = 0; bool ok; ok = pb_get_encoded_size(&size, fields, msg); printf("pb_get_encoded_size=%d, Encoding data as %lx bytes\n", ok, size); auto buff = std::vector<pb_byte_t>(size); auto stream = pb_ostream_from_buffer(buff.data(), buff.size()); ok = pb_encode(&stream, fields, msg); printf("pb_encode=%d, Encoding data as %lx bytes\n", ok, stream.bytes_written); return buff; } auto nano_pb_test() -> void { std::vector<pb_byte_t> pb_res; { WifiCredResult2 wifi_result; wifi_result.ip = (int32_t)3232235920; // https://www.browserling.com/tools/ip-to-dec -> 192.168.1.144 wifi_result.mac = { 6, { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35}}; ToAppMessage2 toAppMessage2 = ToAppMessage2_init_zero; toAppMessage2.type = ToAppMessageType_CONNECT_WIFI_RESULT; toAppMessage2.result = ToAppResultType_NETWORK_IS_LOCAL_ONLY; toAppMessage2.esp_error = 0x7002; toAppMessage2.which_payload = WifiCredResult2_ip_tag; toAppMessage2.payload.wifi = wifi_result; pb_res = encode(ToAppMessage2_fields, &toAppMessage2); } { ToAppMessage2 toAppMessage3 = ToAppMessage2_init_zero; toAppMessage3.payload.wifi.ip = 12; pb_istream_t istream = pb_istream_from_buffer((const pb_byte_t *)pb_res.data(), pb_res.size()); if (!pb_decode(&istream, ToAppMessage2_fields, &toAppMessage3)) { printf("nanopb failed parsing:\n"); } else { printf("result = %d, esp: %x, ip=%d\n", toAppMessage3.result, toAppMessage3.esp_error, toAppMessage3.payload.wifi.ip); } } } The protobuff (parts of..) enum ToAppMessageType { ... } enum ToAppResultType { ... } message Details { string project_id = 1; string url1 = 2; string url2 = 5; } message Result2 { int32 ip = 1; bytes mac = 2; } message ToAppMessage2 { ToAppMessageType type = 1; ToAppResultType result = 2; int32 error = 3; oneof payload { WifiCredResult2 wifi = 4; PairResult pair = 5; } } Options file: WifiCredResult2.mac max_size:6
I think your problem is here: toAppMessage2.which_payload = WifiCredResult2_ip_tag; This would indicate that your payload oneof contains an item of type WifiCredResult2.ip, but there is no such item in that oneof so nothing gets encoded. It appears you want instead: toAppMessage2.which_payload = ToAppMessage2_wifi_tag;
69,432,941
69,433,134
while repeat not stop after i input one time
how do i get my program to repeat non stop? i want it to keep asking me to input the same information for multiple students. and not stop after i input once. can someone help please? i really appreciate all the help thank you guys. enter code here #include <iostream> #include <iomanip> using namespace std; int main() { int midterm=0; int final=0; cout << "please enter midterm grade: "; cin >> midterm; while (midterm < 0 || midterm > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. please enter grade: "; cin >> midterm; } cout << "please enter final grade: "; cin >> final; while (final < 0 || final > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. Please enter grade"; cin >> final; } int total; total = final + midterm; if (total > 360 && total <= 400) { cout << "your letter grade is A"; } else if (total > 320 && total <= 360) { cout << "your letter grade is B"; } else if (total > 280 && total <= 320) { cout << "your letter grade is C"; } else if (total > 240 && total <= 280) { cout << "your letter grade is D"; } else if (total <= 240) { cout << "your letter is F"; } }
Put your whole code in a loop that never stops. Example: #include <iostream> #include <iomanip> using namespace std; int main() { while(true) { int midterm=0; int final=0; cout << "please enter midterm grade: "; cin >> midterm; while (midterm < 0 || midterm > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. please enter grade: "; cin >> midterm; } cout << "please enter final grade: "; cin >> final; while (final < 0 || final > 200) { cout << "Please enter valid amount must be 0 or greater or 200 or less. Please enter grade"; cin >> final; } int total; total = final + midterm; if (total > 360 && total <= 400) { cout << "your letter grade is A"; } else if (total > 320 && total <= 360) { cout << "your letter grade is B"; } else if (total > 280 && total <= 320) { cout << "your letter grade is C"; } else if (total > 240 && total <= 280) { cout << "your letter grade is D"; } else if (total <= 240) { cout << "your letter is F"; } cout << "\n"; } } This question has been asked and answered before as well: How do I make my code Repeat instead of ending in c++?
69,433,613
69,433,693
Passing template template parameters
Let's say we have a class called TypeCollection that holds a packed template of types: template<typename ...Types> class TypeCollection {}; And if we have a class that templates a TypeCollection you would need to do something a little like this: template<template<typename ...> class Collection, typename ...Types> class CollectionHandler {}; Which would be instantiated like so: CollectionHandler<TypeCollecion, A, B, C> This isn't great since we have to pass the types A B and C twice for template deduction. My question is if there is a way to do this without having to pass the types twice: CollectionHandler<TypeCollecion<A, B, C>> However I cant seem to get this to work. I tried a couple things and I realized that you cant pass a templated class as a parameter: CollectionHandler<TypeCollecion<A, B, C>> // Error: Template argument for template template parameter must be a class template or type alias template Is there a way to instantiate CollectionHandler without having to pass the types twice? I experimented with tuples to hide the parameters but I couldn't get that to work either. Thanks for your help!
Flip your CollectionHandler declaration around to dissect the TypeCollection through template specialization: template <class TypeCollection> class CollectionHandler; template <class... Types> class CollectionHandler<TypeCollection<Types...>> { };
69,433,726
69,433,842
Limitations of std::result_of for lambdas in C++14
I have a working piece of C++17 code that I would like to port to C++14 (project's constraints). The code allocates a functor on the heap, based on the lambda returned by a provider. decltype(auto) fun_provider(std::string msg) { return [msg](){ std::cout << msg << std::endl; }; } int main() { auto fun = std::make_unique< std::invoke_result_t<decltype(fun_provider), std::string> >(fun_provider("Provided functor")); (*fun.get())() } // output: "Provided functor" The point is, it avoids hardcoding lambda type as std::function<void()>. Up to my best knowledge, the closure type is unspecified and such construction would imply unnecessary copy of the closure object (hope that's correct). I would like to achieve the same goal with C++14, is it possible? I tried few constructions with std::result_of and/or decltype but didn't succeed so far.
Is this approach not viable? auto fun = std::make_unique< decltype(fun_provider(std::declval<std::string>())) >(fun_provider("Provided functor")); The use of std::declval isn't even necessary; std::string{} instead of std::declval<std::string>() is just fine.
69,434,339
69,435,540
Metadata Like Config file parser
i am trying to parse this config file ... MODEL: "modelname1" { FILEPATH = "FILEPATH1"; TEXTUREPATH = "TEXTUREPATH1"; NORMALPATH = "NORMALPATH1"; } MODEL:"modelname2"{FILEPATH = "FILEPATH2";TEXTUREPATH = "TEXTUREPATH2";NORMALPATH = "NORMALPATH2";} here is my attempt : #include <iostream> #include <map> #include <fstream> #include <vector> #include <string> using namespace std; struct ModelData { string tagName; string filePath; string texturePath; string normalPath; }; vector<ModelData> g_modelData; void GetStringValue( string _source, string _tagName, string& _outStrVal ) { size_t equalPos = _source.find_first_of('='); string tagName = _source.substr(0, equalPos); tagName.erase(remove(tagName.begin(), tagName.end(), '"'), tagName.end()); if (tagName == _tagName) { _source = _source.substr(equalPos + 1); _source.erase(remove(_source.begin(), _source.end(), '"'), _source.end()); _outStrVal = _source; } } int main() { ifstream infile("modeldata.txt", ios::in); if (!infile.good()) { cout << "Error opening file!" << endl; } string line; line.resize(1024); while (infile.getline((char*)line.data(), line.size(), '\n')) { line.erase(remove(line.begin(), line.end(), ' '), line.end()); line.erase(remove(line.begin(), line.end(), '\t'), line.end()); size_t colonPos = line.find_first_of(':'); string tagStr = line.substr(0, colonPos); if (tagStr == "MODEL") { ModelData md; string tagValueStr = line.substr(colonPos + 1); size_t tagNamePos = tagValueStr.find_first_of('{'); string tagName = tagValueStr.substr(0, tagNamePos); tagName.erase(remove(tagName.begin(), tagName.end(), '"'), tagName.end()); md.tagName = tagName; tagValueStr = tagValueStr.substr(tagNamePos + 1); size_t tagValueTerminatingPos = tagValueStr.find_first_of('}'); tagValueStr = tagValueStr.substr(0, tagValueTerminatingPos); string temp; char context[1024]; memset( context,0, 1024 ); temp = strtok_s(&tagValueStr[0], ";", (char**)&context); GetStringValue(temp, "FILEPATH", md.filePath); temp = strtok_s(nullptr, ";", (char**)&context); GetStringValue(temp, "TEXTUREPATH", md.texturePath); temp = strtok_s(nullptr, ";", (char**)&context); GetStringValue(temp, "NORMALPATH", md.normalPath); g_modelData.push_back(md); } } infile.close(); system("pause"); return 0; } but what if I format the config file to MODEL: "modelname1" { FILEPATH = "FILEPATH1"; TEXTUREPATH = "TEXTUREPATH1"; NORMALPATH = "NORMALPATH1"; } MODEL:"modelname2" { FILEPATH = "FILEPATH2"; TEXTUREPATH = "TEXTUREPATH2"; NORMALPATH = "NORMALPATH2"; } then getline wont work and I have to do character by character parsing ... so I wanted to ask what could be the faster implementation of the above change, i want to extract this data inside program and use it to load things. I am ok if you want to redesign this config file for better flow. QUERY UPDATE: Would like to know more about how to parse nested blocks and curly braces, didn't found much in google search. my config file would then should look like ... MODEL: "modelname1" { FILEPATH = "FILEPATH1"; TEXTUREPATH = "TEXTUREPATH1"; NORMALPATH = "NORMALPATH1"; PLACEHOLDER = { DATA0 = true//1 DATA1 = 1.0f, 1.0f, 1.0f; DATA2 = 1.0f, 1.0f, 1.0f; DATA3 = 1.0f, 1.0f, 1.0f; } } should read this into struct ModelData { string tagName; string filePath; string texturePath; string normalPath; bool Data0; Vec3 Data1; Vec3 Data2; Vec3 Data3; };
Since you want to learn fundamentals, I will only answer with outlines of solutions. Note that neither will work if you want to add block nesting to your language. For that you need a proper grammar like boost::spirit or similar. Use getline to extract one block at a time: std::string model_name, block_contents; getline(infile, model_name, '{'); getline(infile, block_contents, '}'); Use a regular expression to do the same: auto block_regex{ R"(MODEL\s*:\s*"(.*?)"\s*\{(.*?)\})" }; You can then apply a std::regex_iterator to get each block in sequence. Parsing the block contents Use std::regex_iterator with the regex (\S+)\s*=\s*(".*?");. Assign the results to an std::map.
69,434,424
69,435,033
Qt/C++ pass static method's argument to class method
Is there a way to pass a static method's argument to a class method? I've tried with QTimer this way: QTimer g_timer; QString g_arg; void staticMethod(QString arg) { g_arg = arg; g_timer.start(1); // It will expire after 1 millisecond and call timeout() } MyClass::MyClass() { connect(&g_timer, &QTimer::timeout, this, &MyClass::onTimerTimeout); this->moveToThread(&m_thread); m_thread.start(); } MyClass::onTimerTimeout() { emit argChanged(g_arg); } But I've got errors with threads because the staticMethod is called from a Java Activity, so the thread is not a QThread. The errors are: QObject::startTimer: QTimer can only be used with threads started with QThread if g_timer is not a pointer, or QObject::startTimer: timers cannot be started from another thread if g_timer is a pointer and I instantiate it in MyClass constructor Any suggestion? Thank you
In this specific instance you can use QMetaObject::invokeMethod to send the message over a cross-thread QueuedConnection: QMetaObject::invokeMethod(&g_timer, "start", Qt::QueuedConnection, Q_ARG(int, 1)); This will deliver an event to the owning thread from where the start method will be called, instead of the current (non-QT) thread.
69,434,848
69,434,946
Is it necessary to cast individual indices of a pointer after you cast the whole pointer in c? Why?
In the code below the address of ip is casted to uint8_t *. But below again each index of the casted pointer is casted to uint8_t. Why the programmer has done this? Does it make a difference if we remove all those casts that come after the initial cast? This code converts an IPv4 IP Address to an IP Number. Thank you uint32_t Dot2LongIP(char* ipstring) { uint32_t ip = inet_addr(ipstring); uint8_t *ptr = (uint8_t *) &ip; uint32_t a = 0; if (ipstring != NULL) { a = (uint8_t)(ptr[3]); a += (uint8_t)(ptr[2]) * 256; a += (uint8_t)(ptr[1]) * 256 * 256; a += (uint8_t)(ptr[0]) * 256 * 256 * 256; } return a; }
Why the programmer has done this? Ignorance, fear, or other incompetence. The type of ptr is uint8_t *, so the type of ptr[i] is uint8_t. Converting a uint8_t to a uint8_t has no effect. Also, putting it in parentheses has no effect. Does it make a difference if we remove all those casts that come after the initial cast? Yes, it makes the code smaller and clearer. It has no effect on the program semantics. This code converts an IPv4 IP Address to an IP Number. No, it does not, not correctly; the code is broken. When the uint8_t value is used in multiplication with 256, the usual arithmetic conversions are applied. These promote the uint8_t to int, and then the result of the * operator is an int. For ptr[0], as two more multiplications by 256 are performed, the result remains an int. Unfortunately, if the high bit (bit 7) of ptr[0] is set, these multiplications overflow a 32-bit int. Then the behavior of the program is not defined by the C standard. To avoid this, the value should have been cast to uint32_t. (This speaks only to getting the arithmetic correct; I make no assertion about the usefulness of taking apart an in_addr_t returned by inet_addr and reassembling it in this way.)
69,435,425
69,435,484
namespace myspace { int x } Now why `myspace::x=3;` gives error?
Code #include <iostream> namespace myspace { int x; } myspace::x=3; // This line is giving error. int main() { myspace::x=5; return 0; } Output Error: C++ requires a type specifier for all declarations So why line myspace::x=3; giving error that C++ requires a type specifier for all declarations ?
The statement myspace::x=3; isn't an initialization, it's a plain assignment. It's no different from the myspace::x=5; you have inside the main function. Any statement that isn't a declaration or a definition can't be outside functions. If you want to initialize the variable, do it at the definition: namespace myspace { int x = 3; }
69,435,528
69,435,594
C++ boost 1.72 reconnect on tcp::socket throwing an exception with WSAEADDRINUSE on linux, but works on Windows
Hi my code works properly on windows but on linux the reconnect feature doesn't work,it throws an exception with WSAEADDRINUSE value. pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001)); First time it works on both Windows and Linux, but when i close the socket and try to connect again, i am getting an exception as described above only on linux OS. Here is the close socket code. boost::system::error_code ec; pClientSocket->shutdown( boost::asio::socket_base::shutdown_type::shutdown_receive, ec); pClientSocket->close(eCode); delete pClientSocket; pClientSocket= nullptr;
Try using the reuse option: boost::asio::socket_base::reuse_address option(true); socket.set_option(option); Update: This usually happens we you try to bind a server socket to an address that is already in use or it has been used recently (and the socket is still waiting to be cleaned up by the OS). With client sockets this is less common, you will have to force a port -by calling bind()- in the socket in order for this to happen. Now the code: pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001)); boost::asio::socket_base::reuse_address option(true); socket.set_option(option); Calls this constructor overload. This constructor creates the socket and tries to bind it to the specified address. It fails because you didn't had the chance to specify the reuse option. On the other hand, this code: pClientSocket = new tcp::socket(*pIO_context); pClientSocket->open(boost::asio::ip::tcp::v4()); pClientSocket->set_option(socket_base::reuse_address(true)); boost::system::error_code ec; pClientSocket->bind(tcp::endpoint(make_address(127.0.0.1, 50001), ec); if (ec) { } Calls this constructor overload, which just creates the socket but doesn't open no connect it. This allows to specify any socket option before bind/connect, etc.
69,435,538
69,435,666
Extract static member type from class of local variable
Is it possible to extract a static member type from the class of a local variable? aka something in the lines of class A { public: typedef int constituent_type; constituent_type a; A(constituent_type _a) :a(_a) {}; } int main() { auto a = A(42); // ... lots ... of other code; where I have long since forgottten, what the type of a really was std::max<a::constituent_type>(a, a); //<<< }
You can do that in C++ 11 or later using decltype: decltype(a)::x Live demo: https://godbolt.org/z/cTq9zhKxe
69,436,122
69,436,399
Giving an arbitrary container, deduce a container type of a related type
Say I have a templated class Wrapper, is there a way to create a type alias template that automatically deduce a container of Wrapper <T> from a container of T, so that: alias(Wrapper, vector<int>) would become vector<Wrapper<int>> alias(Wrapper, map<int, string>) would become map<Wrapper<int>, Wrapper<string>> alias(Wrapper, array<int, 10>) would become array<Wrapper<int>, 10> So far the best attempt I've got is: template<template<typename> typename U, template<typename...> typename Container, typename ...T> using alias = std::remove_cvref_t<decltype(std::declval<Container<U<T>...>>())>; However there are two problems: It must be called with syntax like:This version need to be called like(which is not ideal): alias(vector, Type) and alias(map, Key, Value). I would love to use alias(vector<Type>) and alias(map<Key, Value>) if possible. It is not compatible with std::array since the second template parameter of array is size_t not a type. I guess I could create a second type alias and call the corresponding one based on the container type, but I would prefer not have to do that.
Not sure if this is exactly what you need, but specialization of class template can handle this nicely: #include <type_traits> #include <vector> #include <array> #include <map> #include <string> template<template<typename> typename Wrapper, typename Container> struct repack; template<template<typename> typename Wrapper, typename ValueT> struct repack<Wrapper, std::vector<ValueT>> { using type = std::vector<Wrapper<ValueT>>; }; template<template<typename> typename Wrapper, typename ValueT, std::size_t N> struct repack<Wrapper, std::array<ValueT, N>> { using type = std::array<Wrapper<ValueT>, N>; }; template<template<typename> typename Wrapper, typename Key, typename Value> struct repack<Wrapper, std::map<Key, Value>> { using type = std::map<Wrapper<Key>, Wrapper<Value>>; }; template<template<typename> typename Wrapper, typename Container> using repack_t = typename repack<Wrapper, Container>::type; https://godbolt.org/z/naz9v48vb It passes tests specified by you.
69,436,608
69,436,936
How to add several string together such as "123"+"456"?
How to achieve such operation, the Visual Studio always tells me that it was wrong. The wrong code is C2110 and E2140. Can anyone help? std::string a = "2323" + "22323" + "232332";
The expression "2323" is not a std::string, it is a const char[5]. Since C++14, you can have a literal of type std::string: using namespace std::string_literals; std::string a = "2323"s + "22323"s + "232332"s;
69,437,173
69,441,170
C++ Win32 Menubar being drawn over owner-drawn menu items
I have 2 owner-drawn menu items, when I launch the program I only see one of the owner-drawn menu items; the first one. It is being drawn except the menubar is drawn over every other menu item which is not drawn in the first position, If I mouse over the second owner-drawn menu item or update it in any other way it draws, If I then interact with the main window (i.g Resizing) in effect updating the menu bar it proceeds to draw over any other owner-drawn item that is not drawn in the first position. Question: How do I get the menubar to not drawn over menu items, // Measure Item: VOID MeasureMenuItem(LPMEASUREITEMSTRUCT ItemStruct) { ItemStruct->itemWidth = 50; ItemStruct->itemHeight = 10; return; } // Draw Item: VOID DrawMenuItem(LPDRAWITEMSTRUCT ItemStruct) { HDC hDC = ItemStruct->hDC; SelectObject(hDC, GetStockObject(DC_PEN)); SelectObject(hDC, GetStockObject(DC_BRUSH)); SetBkMode(hDC, TRANSPARENT); if (ItemStruct->itemState & ODS_HOTLIGHT) { SetDCPenColor(hDC, RGB(20, 20, 20)); SetDCBrushColor(hDC, RGB(20, 20, 20)); SetTextColor(hDC, RGB(255, 255, 255)); } else { SetDCPenColor(hDC, RGB(70, 70, 70)); SetDCBrushColor(hDC, RGB(70, 70, 70)); SetTextColor(hDC, RGB(255, 255, 255)); } Rectangle(hDC, ItemStruct->rcItem.left, ItemStruct->rcItem.top, ItemStruct->rcItem.right, ItemStruct->rcItem.bottom); DrawText(hDC, (LPCWSTR)ItemStruct->itemData, -1, &ItemStruct->rcItem, DT_SINGLELINE | DT_CENTER | DT_VCENTER); ReleaseDC(MainWindow, hDC); return; } // Menus HMENU Bar = CreateMenu(); HMENU File = CreateMenu(); HMENU Edit = CreateMenu(); AppendMenu(Bar, MF_OWNERDRAW, (UINT_PTR)File, L"File"); AppendMenu(Bar, MF_OWNERDRAW, (UINT_PTR)Edit, L"Edit"); MENUINFO Info; Info.cbSize = sizeof(Info); Info.fMask = MIM_BACKGROUND; Info.hbrBack = (HBRUSH)CreateSolidBrush(RGB(100, 100, 100)); SetMenuInfo(Bar, &Info); SetMenu(MainWindow, Bar);
Why is DrawMenuItem() calling ReleaseDC(MainWindow, hDC);? That doesn't belong there, get rid of it. You didn't obtain the HDC from Get(Window)DC() so you don't own it and shouldn't be trying to release it. Also, you are not un-selecting the objects you selected into the HDC. You need to restore the original objects you replaced. Try this instead: VOID DrawMenuItem(LPDRAWITEMSTRUCT ItemStruct) { HDC hDC = ItemStruct->hDC; HPEN oldPen = (HPEN) SelectObject(hDC, GetStockObject(DC_PEN)); HBRUSH oldBrush = (HBRUSH) SelectObject(hDC, GetStockObject(DC_BRUSH)); SetBkMode(hDC, TRANSPARENT); if (ItemStruct->itemState & ODS_HOTLIGHT) { SetDCPenColor(hDC, RGB(20, 20, 20)); SetDCBrushColor(hDC, RGB(20, 20, 20)); SetTextColor(hDC, RGB(255, 255, 255)); } else { SetDCPenColor(hDC, RGB(70, 70, 70)); SetDCBrushColor(hDC, RGB(70, 70, 70)); SetTextColor(hDC, RGB(255, 255, 255)); } Rectangle(hDC, ItemStruct->rcItem.left, ItemStruct->rcItem.top, ItemStruct->rcItem.right, ItemStruct->rcItem.bottom); DrawText(hDC, (LPCWSTR)ItemStruct->itemData, -1, &ItemStruct->rcItem, DT_SINGLELINE | DT_CENTER | DT_VCENTER); SelectObject(hDC, oldPen); SelectObject(hDC, oldBrush); }
69,437,596
69,437,775
Binary search tree algorithm crashing when passing a parameter that isn't in the tree to the search function
i tried building a binary search tree, everything worked fine when i gave it parameters that were in in the tree, but i wanted to see if it would print 0 when it couldn't find the int in the tree instead when i call search it's crashing. i tried adding a condition after the first if statement but that ruined the recursion here's the code: struct node { int data; node* left; node* right; node(int d) { data = d; left = right = NULL; } }; node* insert(node *root, int n) { if(root == NULL) { return new node(n); } else { node* y; if(n <= root->data) { y = insert(root->left, n); root->left = y; } else { y = insert(root->right, n); root->right = y; } return root; } } node* search(node *root,int n) { if(root == NULL || root->data == n) { return root; } if(root->data < n) { return search(root->right, n); } return search(root->left, n); } int treemax(node *root) { while(root->right != NULL) { root = root->right; } return root->data; } int treemin(node *root) { while(root->left != NULL) { root = root->left; } return root->data; } int main() { node *R = NULL; R = insert(R, 33); insert(R,12); insert(R, 40); insert(R, 36); insert(R, 21); cout << search(R, 65)->data << endl; }
When you run cout << search(R, 65)->data << endl; search(R, 65) returns NULL. You can't dereference NULL by doing ->data on it. You probably want: Node* result = search(R, 65); if (result) { cout << result->data << endl; } else { cout << "Not found" << endl; }
69,437,727
69,438,128
Using boost spirit expression
I have a problem with boost spirit expression.The original code is more complicated and I made a small snapshot of it. This code works as expected in debug mode and doesn't in release, parse returns false, but should return true ( I'm testing it on Visual Studio 2019) int main() { namespace qi = boost::spirit::qi; auto X19 = qi::lit(" ") | qi::lit(" 0.000000000000D+00"); auto i4 = qi::uint_; string str = "1234 1234"; auto f = str.cbegin(); auto l = str.cend(); bool ret = qi::parse(f, l, ( i4 >> X19 >> i4 )); } The next snapshot works well in both modes: int main() { namespace qi = boost::spirit::qi; auto i4 = qi::uint_; string str = "1234 1234"; auto f = str.cbegin(); auto l = str.cend(); bool ret = qi::parse(f, l, ( i4 >> (qi::lit(" ") | qi::lit(" 0.000000000000D+00")) >> i4 )); cout << ret << endl; return ret; } What I do wrong, dividing long expression this way ? Thank you
You ran headlong into the the dangling temporaries trap with Spirit's Proto expressions. The short rule is: Don't use auto with Spirit expressions Your program exhibits Undefined Behaviour: see it Live On Compiler Explorer The workarounds involve BOOST_SPIRIT_AUTO or qi::copy (which used to be available only as boost::proto::deep_copy before recent boost releases). Fixed Live On Coliru #include <boost/spirit/include/qi.hpp> int main() { namespace qi = boost::spirit::qi; auto i4 = qi::copy(qi::uint_); auto X19 = qi::copy( // qi::lit(" ") // | qi::lit(" 0.000000000000D+00")// ); std::string str = "1234 1234"; auto f = str.cbegin(), l = str.cend(); bool ret = qi::parse(f, l, (i4 >> X19 >> i4)); std::cout << std::boolalpha << ret << "\n"; } Prints true BONUS Note that Spirit X3 no longer has this restriction/problem: Live On Coliru #include <boost/spirit/home/x3.hpp> int main() { namespace x3 = boost::spirit::x3; auto i4 = x3::uint_; auto X19 = // x3::lit(" ") // | x3::lit(" 0.000000000000D+00") // ; std::string str = "1234 1234"; auto f = str.cbegin(), l = str.cend(); bool ret = parse(f, l, (i4 >> X19 >> i4)); std::cout << std::boolalpha << ret << "\n"; } You might actually want qi::uint_parser<int, 10, 4, 4> i4; // or x3::uint_parser<int, 10, 4, 4> i4; It looks a lot as if you're parsing COBOL like (fixed-width) records, in which case I think there are much better ways to organize your grammar to make it reliable.
69,437,925
69,438,074
Problem with calling C++ function that receive command line arguments from Rust
I am trying to call a C++ function from rust. The function suppose to receive the command lines arguments then print it. I used cmake to compile the C++ code to a static archive. I write a build.rs script to referee to the static library location and to make the static linking to it. // library.cpp #include "library.h" #include <iostream> extern "C"{ void print_args(int argc, char *argv[]){ std::cout << "Have " << argc << " arguments:" << std::endl; std::cout<<argv<<std::endl; for (int i = 0; i < argc; ++i) { std::cout << argv[i] << std::endl; } } } //library.h extern "C"{ void print_args(int argc, char *argv[]); } //build.rs pub fn main(){ println!("cargo:rustc-link-search=.../cmake-build-debug"); //library.a directory println!("cargo:rustc-link-lib=static=stdc++"); println!("cargo:rustc-link-lib=static=library"); } //main.rs #[link(name = "library", kind = "static")] extern "C" { pub fn print_args(args: c_int, argsv: *const c_char); } fn main() { let args = std::env::args() .map(|arg| CString::new(arg).unwrap()) .collect::<Vec<CString>>(); let args_len: c_int = args.len() as c_int; let c_args_ptr = args.as_ptr() as *const c_char; unsafe { print_args(args_len, c_args_ptr) }; } When running the rust code by the command cargo run "10" "11" . it is only able to print the first argument which is the name of the program then the error error: process didn't exit successfully: target\debug\static_library_binding_test.exe 10 11 (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION) appears. it is the output rust main.rs Have 3 arguments: target\debug\static_library_binding_test.exe error: process didn't exit successfully: `target\debug\static_library_binding_test.exe 10 11` (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION) So, I need to know how can I pass the command line argument from rust to the c++ function.
The problem is in this code: let args = std::env::args() .map(|arg| CString::new(arg).unwrap()) .collect::<Vec<CString>>(); // ... let c_args_ptr = args.as_ptr() as *const c_char; That creates a vector of CString objects, which you then proceed to cast into an array of pointers. But a CString consists of two word-sized values, a pointer and a length, and cannot be reinterpreted as a single pointer. To get an actual array of pointers which print_args() expects, you need to collect them into a separate vector: let args = std::env::args() .map(|arg| CString::new(arg).unwrap()) .collect::<Vec<CString>>(); let arg_ptrs: Vec<*const c_char> = args.iter().map(|s| s.as_ptr()).collect(); let args_len: c_int = args.len() as c_int; unsafe { print_args(args_len, arg_ptrs.as_ptr()) }; Note that you'll need to declare print_args as taking pointer to pointer, as it does in C++ (const char *argv[] is just sugar for const char **argv): #[link(name = "library", kind = "static")] extern "C" { pub fn print_args(args: c_int, argsv: *const *const c_char); }
69,438,184
69,438,625
Including a header in multiple headers in my C++ code
I am trying to include a header file from the book Numerical Recipes in my code. The header files I have to include are the nr3.hpp and the interp_1d.hpp. The interp_1d needs the definitions of nr3 in order to work. I will write some of the code that appears on interp_1d.hpp so that you get an idea of what I am dealing with with the interp_1d code: struct Base_interp{ ... }; Int Base_interp::locate(const Doub x){ ... } ... Doub BaryRat_interp::interp(Doub x){ ... } There are no header guards in this header file. As a result when I try to input it in multiple other header files I get the error "66 duplicate symbols for architecture x86_64". The structure of my code is the following: myPulse.hpp: #include "nr3.hpp" #include "interp_1d.hpp" calc1.hpp: #include "myPulse.hpp" calc2.hpp: #include "myPulse.hpp" main.cpp: #include "myPulse.hpp" #include "calc1.hpp" #include "calc2.hpp" #include "nr3.hpp" #include "interp_1d.hpp" I don't know how to overcome this issue. I want to be able to use the interp_1d.hpp functions in more than one part of the code. I tried including header guards, but this didn't work: #ifndef Interp_1d #define Interp_1d #endif Does anyone know how I use the interp_1d header in multiple other headers without this error occurring?
When working with a single file (or for brevity for books), some code can be simplified, but making multi-file case wrong. In your case, header guards are missing, and inline are missing (or a cpp file to put definition). So you cannot use them as-is. You have either: split code for header/cpp file: // interp_1d.hpp #pragma once // or include guards struct Base_interp{ //... }; //interp_1d.cpp #include "interp_1d.hpp" Int Base_interp::locate(const Doub x){ //... } Doub BaryRat_interp::interp(Doub x){ //... } or put extra inline/static (not always enough/possible though (globals for example)) and header guard. // interp_1d.hpp #pragma once // or include guards struct Base_interp{ //... }; inline Int Base_interp::locate(const Doub x){ //... } inline Doub BaryRat_interp::interp(Doub x){ //... }
69,438,255
69,448,568
Should the suspended coroutine handle be always destroyed before program ends?
Look at this simplified example: std::coroutine_handle<> logger; const char* next_msg = nullptr; void log(const char* msg) { next_msg = msg; if (logger) logger.resume(); } struct wait_msg { bool await_ready() { return next_msg != nullptr; } void await_suspend(std::coroutine_handle<> h) { logger = h; } auto await_resume() { const char* msg = next_msg; next_msg = nullptr; return msg; } }; struct procedure { struct promise_type; using handle_type = std::coroutine_handle<promise_type>; handle_type handle; struct promise_type { procedure get_return_object() { return { handle_type::from_promise(*this)}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() { std::terminate(); } }; }; procedure log_messages() { int c = 1; for (;;) { const char* msg = co_await wait_msg{}; std::cout << c++ << ": " << msg << std::endl; } } Assuming I have no suspension at initial or final points and coroutine is suspended on co_await, should the coroutine handle be destroyed before the program ends? Or: can line p.handle.destroy(); be removed from main? int main() { log("Hello World!"); auto p = log_messages(); log("Hello World, again!"); log("Hello World, and again!"); // is the next line needed? p.handle.destroy(); } See full demo. Previous version of code in question here.
Should the suspended coroutine handle be always destroyed before program ends? No, there are cases when destroy() is not needed nor even possible. Yes, in the code from question, destroy() on coroutine handle is needed. This quote from the standard explains the thing: The coroutine state is destroyed when control flows off the end of the coroutine or the destroy member function ([coroutine.handle.resumption]) of a coroutine handle ([coroutine.handle]) that refers to the coroutine is invoked. Since this coroutine never go out of infinite loop (for(;;)) - it has to be destroyed via its handle. procedure log_messages() { int c = 1; for (;;) { const char* msg = co_await wait_msg{}; std::cout << c++ << ": " << msg << std::endl; } } However, the code could be slightly modified - like - returns nullptr when there is no more lines to print, and breaks the loop on nullptr: procedure log_messages() { int c = 1; for (;;) { const char* msg = co_await wait_msg{}; if (!msg) break; // !!! std::cout << c++ << ": " << msg << std::endl; } } In that case - destroy() is not needed nor even possible, as it would cause UB. It is because destroy() can only be called on suspended coroutine, and we have no suspensions in final point in the code in question: struct promise_type { //... std::suspend_never final_suspend() noexcept { return {}; } //... }; };
69,438,388
70,050,483
Converting RGB8 to to NV12 with libav/ffmpeg
I am trying to convert an input RGB8 image into NV12 using libav, but sws_scale raises a reading access violation. I must have the planes or the stride wrong, but I can't see why. At this point I believe I'd benefit from a fresh pair of eyes. What am I missing? void convertRGB2NV12(unsigned char *rgb_in, width, height) { struct SwsContext* sws_context = nullptr; const int in_linesize[1] = {3 * width}; // RGB stride int out_linesize[2] = {width, width}; // NV12 stride // NV12 data is separated in two // planes, one for the intensity (Y) and another one for // the colours(UV) interleaved, both with // the same width as the frame but the UV plane with // half of its height. uint8_t* out_planes[2]; out_planes[0] = new uint8_t[width * height]; out_planes[1] = new uint8_t[width * height/2]; sws_context = sws_getCachedContext(sws_context, width, height, AV_PIX_FMT_RGB8, width, height, AV_PIX_FMT_NV12, 0, 0, 0, 0); sws_scale(sws_context, (const uint8_t* const*)rgb_in, in_linesize, 0, height, out_planes, out_linesize); // (.....) }
There are two main issues: Replace AV_PIX_FMT_RGB8 with AV_PIX_FMT_RGB24. rgb_in should be "wrapped" with array of pointers: const uint8_t* in_planes[1] = {rgb_in}; sws_scale(sws_context, in_planes, ...) Testing: Use FFmpeg command line tool for creating binary input in RGB24 pixel format: ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1 -vcodec rawvideo -pix_fmt rgb24 -frames 1 -f rawvideo rgb_image.bin Read the input image using C code: const int width = 192; const int height = 108; unsigned char* rgb_in = new uint8_t[width * height * 3]; FILE* f = fopen("rgb_image.bin", "rb"); fread(rgb_in, 1, width * height * 3, f); fclose(f); Execute convertRGB2NV12(rgb_in, width, height);. Before the end of the function, add temporary code for writing the output to binary file: FILE* f = fopen("nv12_image.bin", "wb"); fwrite(out_planes[0], 1, width * height, f); fwrite(out_planes[1], 1, width * height/2, f); fclose(f); Convert nv12_image.bin as gray scale input to PNG image file (for viewing the result): ffmpeg -y -f rawvideo -s 192x162 -pix_fmt gray -i nv12_image.bin -pix_fmt rgb24 nv12_image.png Complete code sample: #include <stdio.h> #include <string.h> #include <stdint.h> extern "C" { #include <libswscale/swscale.h> } void convertRGB2NV12(const unsigned char *rgb_in, int width, int height) { struct SwsContext* sws_context = nullptr; const int in_linesize[1] = {3 * width}; // RGB stride const int out_linesize[2] = {width, width}; // NV12 stride // NV12 data is separated in two // planes, one for the intensity (Y) and another one for // the colours(UV) interleaved, both with // the same width as the frame but the UV plane with // half of its height. uint8_t* out_planes[2]; out_planes[0] = new uint8_t[width * height]; out_planes[1] = new uint8_t[width * height/2]; sws_context = sws_getCachedContext(sws_context, width, height, AV_PIX_FMT_RGB24, width, height, AV_PIX_FMT_NV12, SWS_BILINEAR, nullptr, nullptr, nullptr); const uint8_t* in_planes[1] = {rgb_in}; int response = sws_scale(sws_context, in_planes, in_linesize, 0, height, out_planes, out_linesize); if (response < 0) { printf("Error: sws_scale response = %d\n", response); return; } // (.....) //Write NV12 output image to binary file (for testing) //////////////////////////////////////////////////////////////////////////// FILE* f = fopen("nv12_image.bin", "wb"); fwrite(out_planes[0], 1, width * height, f); fwrite(out_planes[1], 1, width * height/2, f); fclose(f); //////////////////////////////////////////////////////////////////////////// delete[] out_planes[0]; delete[] out_planes[1]; sws_freeContext(sws_context); } int main() { //Use ffmpeg for building raw RGB image (used as input). //ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1 -vcodec rawvideo -pix_fmt rgb24 -frames 1 -f rawvideo rgb_image.bin const int width = 192; const int height = 108; unsigned char* rgb_in = new uint8_t[width * height * 3]; //Read input image for binary file (for testing) //////////////////////////////////////////////////////////////////////////// FILE* f = fopen("rgb_image.bin", "rb"); fread(rgb_in, 1, width * height * 3, f); fclose(f); //////////////////////////////////////////////////////////////////////////// convertRGB2NV12(rgb_in, width, height); delete[] rgb_in; return 0; } Input (RGB): Output (NV12 displayed as gray scale): Converting NV12 to RGB: ffmpeg -y -f rawvideo -s 192x108 -pix_fmt nv12 -i nv12_image.bin -pix_fmt rgb24 rgb_output_image.png Result:
69,438,583
69,438,808
Missing bytes when reading from file
I am writing some code to combine two .txt files containing test data captured for the same equipment, but taken on separate occasions. The data is stored in a .csv format. EDIT: (As in while they are saved as .txt (UTF8 with BOM encoding), they are formatted to appear like a csv file) Without worrying about the combining part, I was sorting out some issues with reading the files due to my relative inexperience with C++ when I noticed a mismatch of several thousand bytes between the file size reported by a couple methods and what was actually capable of being read in before reaching the EOF. Does anyone know what may be causing this? Methods used to check file size before reading in: Constructing a std::filesystem::directory_entry object for the file in question. Then, calling it's .file_size() method. Returns 733435 bytes. Constructing fstream object for the file then the following code: #include <iostream> #include <fstream> int main() { std::fstream data_file(path_to_file, std::ios::in); int file_size; \\ EDIT: Was in the wrong scope if (data_file.is_open()) { data_file.seekg(0, std::ios_base::end); file_size = data_file.tellg(); data_file.seekg(0, std::ios_base::beg); } std::cout << file_size << std::endl; \\ --> 733435 bytes } Checking the properties of the file in file explorer. File size = 733435 bytes, size on disc = 737280 bytes. Then when I read in the file as follows: #include <iostream> #include <fstream> int main() { std::fstream data_file(path_to_file, std::ios::in); if (data_file.is_open()) { int file_size, chars_read; data_file.seekg(0, std::ios_base::end); file_size = data_file.tellg(); data_file.seekg(0, std::ios_base::beg); std::cout << "File size: " << file_size << std::endl; // |--> "File size: 733425" char* buffer = new char[file_size]; // This sets both the eofbit & failbit flags for the stream // As is expected if the stream runs out of characters to read in // Before n characters are read in. (istream::read(char* s, streamsize n)) data_file.read(buffer, file_size); // We can check the number of chars read in using istream::gcount() chars_read = data_file.gcount(); std::cout << "Chars read: " << chars_read << std::endl; // |--> "Chars read: 716153" delete[] buffer; data_file.close(); } } The mystery deepens somewhat when you look at the contents that are read in. The file is read in using three slightly different methods. Reading in the data line-by-line to a std::vectorstd::string directly from the filestream. std::fstream stream(path_to_file, std::ios::in); std::vector<std::string> v; std::string s; while (getline(stream, s, '\n')) { v.push_back(s); } Read in the data using fstream::read(...) as above, then convert to lines using a stringstream object. //... data read into char* buffer; std::stringstream ss(buffer, std::ios::in); std::vector<std::string> v2; while (getline(ss, s, '\n')) { v2.push_back(s); } As far as I can tell, these should have the same contents. But... std::cout << v.size() << std::endl; // --> 17283 std::cout << v2.size() << std::endl; // --> 17688 EDIT: The file itself has 17283 lines, the last of which is empty In conclusion, a mismatch of just over 17000 bytes of the expected & measured file size, and a mismatch between the number of lines outputted by two different methods of processing mean that I have no idea what's going on. Any suggestions are helpful, including more ways to test what's going on.
fstream opens the file in "text" mode by default. On many platforms, this makes no difference, but specifically on Windows systems, text mode will automatically perform character conversion. \r\n on the filesystem will be read as simply \n. See Difference between opening a file in binary vs text for more discussion. In one of the answers, there is a discussion about the allowable use of seek() and tell(). An easy thing to try is open in binary mode: OR this flag std::ios::binary with your ::in flag.
69,439,030
69,439,176
Only allow further inheritance from child class
Context: I'm doing some internal cleanup to move away from large & unwieldy data structures to more well-defined data structures. Current I have a class that does something like this: class Base { public: virtual int DoStuff(BigType input); }; Calling code: std::vector<Base*> bases; BigType input; for (const auto& base : bases) { base.DoStuff(input); } Child classes currently look like this: class Child : public Base { int DoStuff(BigType input) const override { // do stuff } }; Attempted I added an intermediate interface: template <typename SmallType> class FocusedBase : public Base { public: int DoStuff(BigType input) const override { return DoStuff(SmallType(input)); } virtual int DoStuff(SmallType input); }; Child classes now look like this. Note that SmallType may differ across child classes: class Child : public FocusedBase<SmallType> { int DoStuff(SmallType input) { // do stuff } }; Calling code remains the same. Issue I'd like to have new classes inherit from FocusedBase only, not Base. Any thoughts on how to do so?
If you want to disallow inheriting from Base directly you can make Base::Base() private and make FocusedBase a friend: struct Base { private: Base() = default; friend class FocusedBase; }; struct FocusedBase : Base {}; struct Foo : Base {}; struct Bar : FocusedBase {}; int main() { //Foo f; // error Bar b; // ok }
69,439,350
69,439,623
What would cause a C++ object's type information to change after it is returned from a function?
Introduction I have C++17 code of the following form: Base& makeDerived(int val) { std::shared_ptr<Derived> derived = secondLayer(val); std::cout << typeid(derived).name() << std::endl; return *derived; } int main(void) { Base& derived = makeDerived(7); std::cout << typeid(derived).name() << std::endl; return 0; } I can get this code to either print: Derived Derived or Derived Base with different implementations of Derived and Base, but I don't understand why this would happen. Supplemental Notes The actual code I am basing this question on prints: Derived, Base but it would be much too long to paste, and I wouldn't be authorized to do so. I can't figure out how to distill it down to a characteristic example, all efforts seem to print Derived, Derived, and the fact that I can't distill it down is basically what my problem is because I don't understand why it would be different. In all implementations I care about, Derived is a descendant of Base. Question What would cause a descendant of a base class to change its type information to the base class itself after exiting a function?
It is not clear how you can get output of Derived Derived or Derived Base, because derived is a std::shared_ptr<Derived>. Anyhow, here is a minimal example with the same issue as your code (most likely): #include <iostream> #include <memory> struct Base { virtual ~Base() = default; }; struct Derived : Base {}; std::shared_ptr<Derived> secondLayer(int) { return std::make_shared<Derived>(); } Base& makeDerived(int val) { std::shared_ptr<Derived> derived = secondLayer(val); std::cout << typeid(derived).name() << std::endl; return *derived; } int main(void) { Base& derived = makeDerived(7); std::cout << typeid(derived).name() << std::endl; } possible output: St10shared_ptrI7DerivedE 4Base I was planning to put a disclaimer here on how you should pay attention to warnings and use the compilers instrumentation capabilities. However, gcc silently swallows this code with -Wall -Werror and neither -fsanitize-address nor -fsanitize-undefined do help. I would consider this as a bug. However, return *derived is returning a reference to an object that gets destroyed once the function returns. Using that reference in main causes undefined behavior.
69,439,920
69,440,118
C++ conditional template member function
I am trying to understand how to use std::enable_if to choose between 2 functions implementation. In this case, if the type TupleOfCallback doesn't contains all the type, it will not compile because std::get<...> will throw an error. For exemple: Executor<Entity1*, Entity2*> task([](Entity1 *e){}, [](Entity2 *2){}); This will not compile because Entity3* is not part of the tuple. It seem that we can choose between two functions with the same prototype, void Exec(Entity3 *entity) { //enabled when Entity3* is **not** in the tuple } OR void Exec(Entity3 *entity) { //enabled when Entity3 is in the tuple std::get<std::function<void(Entity3*)>>(m_Callbacks)(entity); } But i dont understand how to achieve this goal. C++ template mechanism is still hard for me, any help is welcome. template<typename ...T> class Executor { typedef std::tuple<std::function<void(T)>...> TupleOfCallback; public: Executor(const std::function<void(T)> &...func) { } void Exec(Entity1 *entity) { std::get<std::function<void(Entity1*)>>(m_Callbacks)(entity); } void Exec(Entity2 *entity) { std::get<std::function<void(Entity2*)>>(m_Callbacks)(entity); } void Exec(Entity3 *entity) { std::get<std::function<void(Entity3*)>>(m_Callbacks)(entity); } public: TupleOfCallback m_Callbacks; };
If you can guarantee that all types appear only once, then the following should work: template<typename... Ts> class Executor { using TupleOfCallback = std::tuple<std::function<void(Ts)>...>; public: Executor(const std::function<void(Ts)>&... func); template<class E> std::enable_if_t<(std::is_same_v<Ts, E*> || ...)> Exec(E* entity) { std::get<std::function<void(E*)>>(m_Callbacks)(entity); } template<class E> std::enable_if_t<!(std::is_same_v<Ts, E*> || ...)> Exec(E* entity) { } public: TupleOfCallback m_Callbacks; }; The basic idea is to use fold-expression to detect whether E* is included in Ts..., thereby enabling the corresponding function. Demo.
69,440,017
69,447,925
Using the same object instance in several classes
I want to be able to instantiate and use the same object instance in several .h files so that: a) that object can be instantiated once and then re-used in several places b) the value for one of the variables of that object instance is to be updated later in the code and thus available to all of the functions which are set to use it Example: Let's say the object is called: AdressHelper and it is defined in AdressHelper.h. Like this: class AddressHelper { private: uint32_t pid; DWORD_PTR baseAddressPtr; public: AddressHelper(uint32_t pid) { this->pid = pid; this->baseAddressPtr = this->GetProcessBaseAddress(pid); } DWORD_PTR GetProcessBaseAddress(DWORD processID) { DWORD_PTR base_address = 0; //... initialize base_address with something return base_address; } DWORD_PTR GetBaseAddress() { if (this != NULL) { return this->baseAddressPtr; } } void SetBaseAddress() { if (this != NULL) { this->baseAddressPtr = GetProcessBaseAddress(pid); } } }; Now, I have Globals.h which describes this object like this: #pragma once #include "AdressHelper.h" #include <cstddef> extern AddressHelper* addressHelper; If I instantiate addressHelper in file gui.h #pragma once #include "world.h" #include <array> #include "Globals.h" AddressHelper* addressHelper = new AddressHelper(GetCurrentProcessId()); I can then use addressHelper in gui.cpp addressHelper->GetBaseAddress() + 0xb81074; But how do I now refer to the same instance of addressHelper in world.h for example? I can't do #include "Globals.h" for example in world.h as compiler starts to complain that addressHelper is already instantiated in gui.obj. The reason is probably as world.h is already included to gui.h and there is cycle dependency. But I can't drop that link for now and still want to do what I have stated above. Any way to achieve this?
Solved in the following way: class AddressHelper { private: uint32_t pid; DWORD_PTR baseAddressPtr; public: AddressHelper() { } static AddressHelper& getInstance() { static AddressHelper instance; // Guaranteed to be destroyed. // Instantiated on first use. return instance; } DWORD_PTR GetProcessBaseAddress(DWORD processID) { DWORD_PTR base_address = 0; HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID); HMODULE* moduleArray; LPBYTE moduleArrayBytes; DWORD bytesRequired; if (processHandle) { if (EnumProcessModules(processHandle, NULL, 0, &bytesRequired)) { if (bytesRequired) { moduleArrayBytes = (LPBYTE)LocalAlloc(LPTR, bytesRequired); if (moduleArrayBytes) { unsigned int moduleCount; moduleCount = bytesRequired / sizeof(HMODULE); moduleArray = (HMODULE*)moduleArrayBytes; if (EnumProcessModules(processHandle, moduleArray, bytesRequired, &bytesRequired)) { base_address = (DWORD_PTR)moduleArray[0]; } LocalFree(moduleArrayBytes); } } } // base_address = (DWORD_PTR)GetModuleHandle(NULL); CloseHandle(processHandle); } return base_address; } DWORD_PTR& GetBaseAddress() { return baseAddressPtr; } void SetBaseAddress(uint32_t pid = GetCurrentProcessId()) { baseAddressPtr = GetProcessBaseAddress(pid); } }; and now everywhere the &AddressHelper::getInstance().GetBaseAddress() is called which can be (re)set with AddressHelper::getInstance().SetBaseAddress();
69,440,238
69,440,621
Cmake how to set a global definition?
I have a simple structure in my project that includes several subfolders/subprojects. The structure is as following: main |- CmakeLists.txt |- include |- src |- library |- CmakeLists.txt |- include |- src The main CmakeLists.txt project(main) file(GLOB SRC . src/*.cpp) file(GLOB INC . include/*.h) add_executable(${PROJECT_NAME} ${SRC} ${INC}) target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include option(ADDS, "", ON) add_subdirectory(library) target_link_libraries(${PROJECT_NAME} PRIVATE library) and the library's CmakeLists.txt project(library) file(GLOB SRC . src/*.cpp) file(GLOB INC . include/*.h) add_library(${PROJECT_NAME} SHARED ${SRC} ${INC}) option(ADDS, "Some additional classes", OFF) if(ADDS) message(STATUS "Configure with some extra classes") add_definitions(-DWITH_ADDS) endif() Actually I need the option to optionally add/compile several additional classes that usually I don't plan to use/compile. In these additional classes I do something like this: library/add.h #ifdef WITH_ADDS class Adds { public: void doSomething(); } #endif and the same in *.cpp file But now I want to use these additional classes in my main project. main.cpp #include "adds.h" Adds adds; adds.doSomething(); So I turned the option ON in the main CMakeFiles.txt but unfortunately I get error: error: ‘Adds ’ does not name a type After researching I've found that add_definitions() works only in the project where it was defined. So although I've turned the option in my main file the definition WITH_ADDS still hasn't defined on the main project but in the subproject only. So my question - is there a way to define a preprocessor variable globally. So once defined in a subproject it will be accessible in all other projects/subprojects? Or maybe there is another solution for that?
The "modern cmake" approach is that all flags are encapsulated in the subprojects, and when you link to the subproject with target_link_library(MYEXE libsubproject), all necessary paths, flags, and definitions are propagated to the main project. To do this, use target_compile_definitions(library PUBLIC ADDS) in the subproject, which will propagate the setting to any users of this target. If your toplevel is manually adding an include path for this subproject, remove it and use the same strategy for include paths: in the subproject, target_include_directories(library PUBLIC ./include), so that any users of the target will inherit this path. The PUBLIC keyword is what makes the propagation work: it means the setting applies both to building the library, and to users. INTERFACE means only for users, and PRIVATE means only for building the library.
69,440,892
69,441,084
Finding a specific template from just one template parameter. Is it possible?
Suppose I have something like this: template <typename T, typename ...args> static std::map<T, std::tuple<args...>> MyMaps; Every type is known on compile time. So for every configuration of types added to the map, a new map is created. Is there a way to search in all instances of map that matches the T parameter with just the key (and the key type)? EDIT: Sorry for super simplifying my question. I was afraid to make it too big and in the end it missed my intent. But I guess the what I was trying to achieve is impossible in the way I wanted as @Quimby explained. What I really was trying to do was a debbug helper (actually to Unreal), to track object values something like this for a includable .h (debbughelper.h): #include <tuple> #include <vector> #include <type_traits> #define WATCHMYOBJECT(object, ...) //TO DO #define RESCANMYOBJECT(object) //TO DO template <typename ...T> void Expand(T...args) { return; } template <typename T, typename ...args> class MyWatcherClass { public: static void WatchMyObject(T &object, args& ...b); static void RescanMyObject(T& MyObject); static std::vector<MyWatcherClass*> Instaces; private: std::tuple<args...> MyTuple = std::tuple<args...>(); std::vector<void*> VoidPointerStorage; T* MyObjectPointer; private: MyWatcherClass(); ~MyWatcherClass(); }; template <typename T, typename ...args> void MyWatcherClass<T, args...>::WatchMyObject(T &MyObject, args& ...b) { MyWatcherClass<T, args...>* MyClassPointer = new MyWatcherClass; InstacedObjects.push_back(MyClassPointer); MyObjectPointer = &MyObject; int helpint = 0; MyClassPointer->MyTuple = std::make_tuple(b...); Expand((MyClassPointer->PointerStorage.push_back((void*)&b),1)...); } template <typename T, typename ...args> void MyWatcherClass<T, args...>::RescanMyObject(T &MyObject) { // I have yet to implement, but impossible to call this // Compare Instaces[i].MyObjectPointer with &MyObject to find the matching one // cast all the void pointers in std::vector<void*> VoidPointerStorage back to typed pointers using the tuple types // Get the values derefing the pointers and update on the screen, log, etc } And then, with help of some macro magic, some one could do: // #include <"debbughelper.h"> class MyNormalClass { public: MyNormalClass(int _MyInt, float _MyFloat, std::string _MyString); int MyInt; float MyFloat; std::string MyString; }; MyNormalClass::MyNormalClass(int _MyInt, float _MyFloat, std::string _MyString) : MyInt(_MyInt), MyFloat(_MyFloat), MyString(_MyString) { } int main() { MyNormalClass MyObject = MyNormalClass(1, 5.2f, std::string("hello")); WATCHMYOBJECT(MyObject, MyObject.MyInt, MyObject.MyFloat, MyObject.MyString); // do other stuff RESCANMYOBJECT(MyObject); //easy, without the need to retype all the members } But there is no way to call RescanMyObject without the types of the members.
No. The underlying problem one would have to solve is determining whether a template variable has been instantiated or not. Otherwise have fun searching through infinitely many possible instantiations. C++ provides no tools for answering such questions because implementation would be near impossible. Mainly due to separated compilation and linking processes. TL;DR; would be that a translation unit(TU) does not contain enough information yet and the linker is too late as the code has already been generated. Each translation unit is compiled separately into an object file. Each TU saw (hopefully the same) template definition from which it instantiated all variables used in this TU. But it does not and cannot know about any instantiated variables in other TUs. Job of the linker is to collect all those object files, resolve the exported and missing symbols, including de-duplication of inline definitions, and finally to create the executable/library. Only just before the final step, the question could be answered. But at this point, the code has already been generated and cannot be changed. And even if it could involve the compiler to create new code again, what if the new code generates even more instantiations, should the linker try again? That borders on runtime-reflection.
69,441,285
69,441,429
Copy assignment operator with non-copyable members
Say I have a class A with only a constructor: struct A { A() = default; A(const A&) = delete; A& operator=(const A&) = delete; }; I also have a class B which contains an instance of A and defines the copy constructor as follows: struct B { B() = default; B(const B& other) : _a{} {} A _a; }; The constructor of B here simply initializes _a with a new instance of A. But, how could I write the assignment operator for B (since I can't "reinitialize" _a)?
If you want operator= to create a fresh new A similar to the copy constructor and if dynamic allocation is feasible you can use a std::unique_ptr<A> as member: struct A { A() = default; A(const A&) = delete; A& operator=(const A&) = delete; }; struct B { B() : _a{std::make_unique<A>()} {} B(const B& other) : _a{std::make_unique<A>()} {} B& operator=(const B& other) { _a = std::make_unique<A>(); return *this; } std::unique_ptr<A> _a; }; Though, if B has a non-copyable (non-movable) member, then the least surprise would be if B is also non-copyable (non-moveable).
69,441,476
69,441,770
Tcl convertion to double not working with large examples
I have a list of dicts and I want to retrieve some values of these dicts. Here is the code: void Get_Dict_Value(Tcl_Interp *interp, Tcl_Obj *dict, const char* key, std::function<void(Tcl_Obj*)> data_handler) { Tcl_Obj* val_ptr; Tcl_Obj* key_ptr = Tcl_NewStringObj(key, -1); Tcl_IncrRefCount(key_ptr); Tcl_DictObjGet(interp, dict, key_ptr, &val_ptr); Tcl_IncrRefCount(val_ptr); data_handler(val_ptr); Tcl_DecrRefCount(val_ptr); Tcl_DecrRefCount(key_ptr); } void Write_Float_Dict(Tcl_Interp *interp, Tcl_Obj *dict, const char* key) { Get_Dict_Value(interp, dict, key, [&interp](Tcl_Obj *val_ptr) { double double_value; Tcl_GetDoubleFromObj(interp, val_ptr, &double_value); //crashing here std::cout << "the value: " << double_value << std::endl; }); } static int Dict_Test(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) { const char* script = R"__( proc my_ns::bla {} { set my_list "" set my_dict [dict create] dict set my_dict my_key 123789 dict set my_dict my_key_2 456 lappend my_list $my_dict return $my_list; } )__"; Tcl_Eval(interp, script); Tcl_Eval(interp, "my_ns::bla"); Tcl_Obj* my_list = Tcl_GetObjResult(interp); Tcl_IncrRefCount(my_list); Tcl_Obj* my_dict; Tcl_ListObjIndex(interp, my_list, 0, &my_dict); Tcl_IncrRefCount(my_dict); Write_Float_Dict(interp, my_dict, "my_key"); //prints: the value: 123789 Write_Float_Dict(interp, my_dict, "my_key_2"); //prints: the value: 456 Tcl_DecrRefCount(my_dict); Tcl_DecrRefCount(my_list); return TCL_OK; } If I just run the example as is, this is going to work. But when I try with a specific big example, I got a crash in the first Tcl_GetDoubleFromObj occurrence. Am I missing something regarding reference counting? Also, I didn't find good examples regarding Tcl_DictObjGet usage, am I using it right?
You should (well, must really) test the result of Tcl_DictObjGet to see if it is TCL_OK or TCL_ERROR. It's a C API, so it returns result codes instead of throwing C++ exceptions. void Get_Dict_Value(Tcl_Interp *interp, Tcl_Obj *dict, const char* key, std::function<void(Tcl_Obj*)> data_handler) { Tcl_Obj* val_ptr = NULL; Tcl_Obj* key_ptr = Tcl_NewStringObj(key, -1); Tcl_IncrRefCount(key_ptr); if (Tcl_DictObjGet(interp, dict, key_ptr, &val_ptr) == TCL_OK) { Tcl_IncrRefCount(val_ptr); data_handler(val_ptr); Tcl_DecrRefCount(val_ptr); } Tcl_DecrRefCount(key_ptr); } (The other alternative is to throw an exception if the Tcl_DictObjGet returns TCL_ERROR.) Similarly with Tcl_GetDoubleFromObj; that uses the same pattern (but produces a double via its out argument on success, not a Tcl_Obj*). You don't need to increment the reference count of the value if the dict is holding the reference, but that should be fine; it's definitely legal to do what you've done there (and depending on what you do with it, it might be necessary; details matter).
69,441,566
69,442,095
How to declare a class member that may be one of two classes
I am working with a project that is largely not of my creation, but am tasked with adding in some functionality to it. Currently, there is a device class that has a member variable that is responsible for storing information about a storage location, setup like this: device.hpp class device { public: // Stuff private: // Stuff StorageInfo storage_info_; // Even more stuff } StorageInfo.hpp class StorageInfo { public: void initializeStorage(); void updateStorageInfo(); int popLocation(); int peakLocation(); uint16_t totalSize(); uint16_t remainingSize(); // More declarations here private: //Even more stuff here } I am tasked with implementing a different storage option so that the two can be switched between. The information functions that this new storage option has would be the same as the initial storage option, but the implementation in retrieving that information is vastly different. In order to keep things clean and make it easier to maintain this application for years to come, they really need to be defined in two different files. However, this creates an issue inside of device.cpp, and in every single other file that calls the StorageInfo class. If I create two separate member variables, one for each type of storage, then not only will I need to insert a million different ifelse statements, but I have the potential to run into initialization issues in the constructors. What I would instead like to do is have one member variable that has the potential to hold either storage option class. Something like this: StorageInfoA.hpp class StorageInfoA: StorageInfo { public: void initializeStorage(); void updateStorageInfo(); int popLocation(); int peakLocation(); uint16_t totalSize(); uint16_t remainingSize(); // More declarations here private: //Even more stuff here } StorageInfoB.hpp class StorageInfoB: StorageInfo { public: void initializeStorage(); void updateStorageInfo(); int popLocation(); int peakLocation(); uint16_t totalSize(); uint16_t remainingSize(); // More declarations here private: //Even more stuff here } device.hpp class device { public: // Stuff private: // Stuff StorageInfo storage_info_; // Even more stuff } device.cpp //Somewhere in the constructor of device.cpp if(save_to_cache){ storage_info_ = StorageInfoA(); } else { storage_info_ = StorageInfoB(); } // Then, these types of calls would return the correct implementation without further ifelse calls storage_info_.updateStorageInfo(); However, I know that cpp absolutely hates anything with dynamic typing, so I don't really know how to implement this. Is this kind of thing even possible? If not, does anyone know of a similar way to implement this that does work with cpp's typing rules?
You are on the right track, but you have to learn how to use polymorphism. In your example, you need the following fixes: In the base class, make all functions virtual, and add a virtual destructor: class StorageInfo { public: virtual ~StorageInfo(){} virtual void initializeStorage(); //... }; Make your inheritance public: class StorageInfoA: public StorageInfo { Instead of holding StorageInfo by value, hold it in a smart pointer: class device { private: std::unique_ptr<StorageInfo> storage_info_; }; device constructor will look like //Somewhere in the constructor of device.cpp if(save_to_cache){ storage_info_ = std::make_unique<StorageInfoA>(); } else { storage_info_ = std::make_unique<StorageInfoB>(); } Finally, you will use it like an ordinary pointer: storage_info_->updateStorageInfo();
69,441,597
69,443,142
c++ issue with variables not being declared in scope error and mismatched types warning
I have run into an issue with my program. The basis of the program, in the grand scheme of things, is to read input about a student from files. This includes their name, ID, homework scores and test scores. It is then supposed to calculate all the scores and produce a letter grade. I'm currently only working on printing out the name and ID. My issue is i get errors for all my variables saying they are not declared in this scope. I also get a warning about mismatched types for my string (no idea what that means). Example of not declared in scope error: part1.cpp:38:2: error: ‘infile’ was not declared in this scope infile.open (out); ^ part1.cpp:38:15: error: ‘out’ was not declared in this scope infile.open (out); mismatched types warning: part1.cpp:11:15: note: mismatched types ‘std::basic_ostream<_CharT, _Traits>’ and ‘int’ outfile << name << " " ^ In file included from /usr/include/c++/4.8.2/string:52:0, from /usr/include/c++/4.8.2/bits/locale_classes.h:40, from /usr/include/c++/4.8.2/bits/ios_base.h:41, from /usr/include/c++/4.8.2/ios:42, from /usr/include/c++/4.8.2/ostream:38, from /usr/include/c++/4.8.2/iostream:39, from part1.cpp:1: here is the overall code: #include <iostream> #include <fstream> #include <string> void printOutput (std::string name, std::string Id, float HPfinalscore, float testFinalscore, float overallScore, string LetterGrade, ostream& outfile) { outfile << name << " " << Id << " "; /* << HPfinalscore << " " << testFinalscore << " " << overallScore << " " << LetterGrade; */ } int main() { ofstream outfile; ifstream infile; int num; std::string file_name; std::string name; std::string Id; std::string LetterGrade; float HPfinalscore = 0, testFinalscore=0, overallScore=0; std::cout<<"How many files are you processing: "; cin>>num; infile.open (out); for(int i=0;i<num;i++) { int count[10]; for(int i=0;i<10;i++) count[i]=0; char c,s[1000]; std::cout<<"Please input the name of the file: "; cin>>file_name; infile.open(file_name.c_str()); if ( !infile) { continue; return 0; } outfile.open("Result"); if ( !outfile) { std::cout << "Could not open output file \n"; return 0; } infile >> name; while(!infile.eof()) { infile >> Id; /* HPfinalscore = getHPScores(infile); testFinalscore = getTestscores(infile); overallScore = EndingScore(HPfinalscore, testFinalscore); LetterGrade= Grade(overallScore); */ printOutput (name, Id, HPfinalscore, testFinalscore, overallScore, LetterGrade, outfile); infile >> name; //try to read another name } infile.close(); outfile.close(); return 0; } } So my question is how do I get my variables to be declared correctly? Also any info on the warning and how to handle it would be greatly appreciated.
Change ifstream, ostream, and ofstream to std::ifstream, std::ostream, and std::ofstream. Also, get rid of this line: infile.open(out);
69,442,488
69,442,545
How can I divide two Eigen::Vector3f by the corresponding elements
I need to divide two vectors by the corresponding elements. How can I accomplish this? I couldn't find any good sources. Something like Eigen::Vector3f v1 = { 10.0f, 10.0f, 10.0f }; Eigen::Vector3f v2 = { 5.0f, 2.0f, 2.0f }; Eigen::Vector3f v3 = v1 / v2; Expected result: { 2.0f, 5.0f, 5.0f } It says "no operator / matches the operands" for division.
While the builtin matrix (expression) types support common linear algebra operations through overloaded operators (e.g. matrix-vector multiplication), Eigen provides distinct types for component-wise operations; the are called "arrays" and subsume Eigen::Array<...> instantiations as well as array expressions. You can always wrap a matrix into an array expression and vice-versa by the .array() and .matrix() member functions - they don't copy anything, but repackage the underlying data such that array-associated operations can be used for matrices, or matrix-associated operations for arrays. In your case, this would be const Eigen::Vector3f v1 = { 10.0f, 10.0f, 10.0f }; const Eigen::Vector3f v2 = { 5.0f, 2.0f, 2.0f }; const Eigen::Vector3f v3 = v1.array() / v2.array(); If you don't need the matrix interface at all, you can also use Eigen::Array<...> directly: const Eigen::Array3f a1 = { 10.0f, 10.0f, 10.0f }; const Eigen::Array3f a2 = { 5.0f, 2.0f, 2.0f }; const Eigen::Array3f a3 = a1 / a2;
69,442,554
69,454,708
How to find all the available filter for CPPLINT.cfg file?
I'm using EditConfig to enforce 2 spaces indentation. root = true [*] indent_style = space indent_size = 2 continuation_indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true I start using cpplint for static analysis, everything worked well until I found that some rules makes conflicts with my EditorConfig configurarion, I'm trying to disable this cpplint rules" private: should be indented +1 space inside class public: should be indented +1 space inside class The help says I can use filters to disable specific check, but I can find a list of all filters available. Example file: filter=-build/include_order,+build/include_alpha Do you know the names of the filters I need?
The solution was so easy, I just need to look carefully on the error message, it shows the name at the end of the message between "[]" LinuxFilesManager.hpp:7: private: should be indented +1 space inside class LinuxFilesManager [whitespace/indent] [3] The solution was creating the CPPLINT.cfg file like this: set noparent filter=-whitespace/indent
69,442,663
69,443,472
Is it possible to convert a UTexture2D to an OpenCV::Mat
I am an developer that works with plugin development for unreal (C++), and I have been tasked with integrating openCV into unreal engine for a project. I was able to handle getting the std:: issues solved, but I am stuck and frustrated with trying to get a UTexture2D to be converted into an opencv::Mat. I have a C++ function that takes in a UTexture2D* and needs to use openCV to manipulate it. To do this, it must be converted to an opencv::Mat. I tried doing pixel-to-pixel conversion, but it crashes every time or hangs. Any guide on how to do this necessary conversion is greatly appreciated, thanks! I have tried a few versions of this code with no success, but this is my latest failure: //obtain all the pixel information from the mipmaps FTexture2DMipMap* MyMipMap = &MyTexture2D->PlatformData->Mips[0]; FByteBulkData* RawImageData = &MyMipMap->BulkData; //store in fcolor array uint8* Pixels = static_cast<uint8*>(RawImageData->Lock(LOCK_READ_ONLY)); //trying via constructor cv::Mat myImg = cv::Mat( 3000, 1100, CV_8UC3); //trying to map the pixels individually for (int32 y = 0; y < height; y++) { for (int32 x = 0; x < width; x++) { int32 curPixelIndex = ((y * width) + x); myImg.at<cv::Vec3b>(x, y)[0] = Pixels[4 * curPixelIndex]; myImg.at<cv::Vec3b>(x, y)[1] = Pixels[4 * curPixelIndex + 1]; myImg.at<cv::Vec3b>(x, y)[2] = Pixels[4 * curPixelIndex + 2]; } }; //unlock thread RawImageData->Unlock();
Use correct constructor of cv::Mat that takes a data pointer. That Mat object will not allocate or free its own memory. It will use the memory it was given. Such a Mat will not be resizable and it will only be valid as long as the given memory is okay to access. https://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#a51615ebf17a64c968df0bf49b4de6a3a ... uint8* Pixels = ...; cv::Mat myImg { height, width, CV_8UC4, Pixels }; // myImg is now usable // access pixels like so: myImg.at<Vec4b>(y,x) ... This example uses uniform initialization. "Old" styles are okay too.
69,442,698
69,442,769
why does the "If GetAsyncKeyState" sends Button infinitely?
I wanted to make a macro that sends space infinitely only if I press it, the problem is that it's sending it even after I left my finger of the button. DWORD WINAPI BhopThread(LPVOID lp) { while (true) { if (bhop) { if (GetAsyncKeyState(VK_SPACE)) { Sleep(10); keybd_event(0x20, 0, 0, 0); Sleep(1); keybd_event(0x20, 0, KEYEVENTF_KEYUP, 0); Sleep(10); } } } } what did I wrong?
You have to check the most signifcant bit of the return value of the GetAsyncKeyState() function to determine if they key is currently pressed or not. GetAsyncKeyState() function If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior; Simply, it means that GetAsyncKeyState() returns not just true or false, but a wide range of values. To determine if the key really is currently held down, aka pressed, you need to use a bit-wise operator with the value 0x8000. Example to check if the Space key is currently held down: if(GetAsyncKeyState(VK_SPACE) & 0x8000) { // high bit is set. Space is currently held down. } What is a bit-wise operator? This is too broad to explain in this answer. I recommend you to have some basic C++ books/docs/tutorials to read. https://en.wikipedia.org/wiki/Bitwise_operation#AND
69,442,953
69,443,000
How to include <numbers> header file and use std::numbers
running on version 11.1.0 of gcc and g++. Every time I run this code I run into issues it says std::numbers was not declared. I tried running g++ randomCodeWhileReading.cpp -o main-std=c++20 within my terminal (im running ubuntu linux) and still no change. Here is the code in question: #include <iostream> #include <numbers> int main() { const long double pi {0}; const long double pi2 {0}; pi = std::numbers::pi_v<long double>; pi2 = std::numbers::pi_v<long double>; std::cout << pi << std::endl << pi2; } Just wanted to see the numbers module in action nothing else. (is it even called a module or is it a header file?) EDIT 10/6/21: The modifying a constant variable has been fixed. However, this code still wont run on my computer. Namely, the #include <numbers> does not seem to work on my machine it throws an error even when using -std=c++20. I am running gcc and g++ version 11.1 See error below: gcc ex2_03.cpp -o -std=c++20 ex2_03.cpp: In function ‘int main()’: ex2_03.cpp:22:65: error: ‘std::numbers’ has not been declared 22 | const double pond_diameter {2.0 * std::sqrt(pond_area/ std::numbers::pi)}; //find diameter by finding radius & multiplying by 2 | however I was unable to replicate using godbolt.org (similar program not the same but uses as well). Clearly, it seems that this is an issue with my machine. How would I go about fixing this? EDIT 10/8/21: I ran the code again using more flags and changing -std=c++20 to -std=c++2a this was what was returned: chris@chris-Aspire-E5-576G:~/Desktop/programming/c++/Learning$ ls ex2_02 HelloWorld randomCodeWhileReading textbookExample1 ex2_02.cpp HelloWorld.cpp randomCodeWhileReading.cpp textbookExample1.cpp ex2_02.o HelloWorld.o randomCodeWhileReading.o textbookExample1.o ex2_03 main textbookDebug textbookOutputNameAndAge.cpp ex2_03.cpp outputNameAndAge textbookDebug.cpp ex2_03.o outputNameAndAge.o textbookDebug.o chris@chris-Aspire-E5-576G:~/Desktop/programming/c++/Learning$ g++ -g -Wall -pedantic -std=c++2a -o randomCodeWhileReading.cpp g++: fatal error: no input files compilation terminated. added the ls output to show I was in the correct directory. EDIT 10/8/21 v2: I used the following command and did not receive an error. g++ randomCodeWhileReading.cpp -o main -std=c++20 Now just confused where the output went. By @nate's responses I assume it was sent to main? Just wanted to see a cout using std::numbers::pi EDIT 10/8/21 v3: All clear nate explained program can be ran by using ./main EDIT 10/8/21 v4: ... I repeated the earlier command and got a error: g++ randomCodeWhileReading.cpp -o main -std=c++20 cc1plus: fatal error: randomCodeWhileReading.cpp: No such file or directory compilation terminated. can someone explain what went wrong this time? (I am still in the same directory). After using ls it seems that the file is no longer in the directory seems to be deleted? EDIT 10/8/21 v5: I think the file got deleted when I was explaining the error to a friend and the wrong ways I was running the command lol. All good :D !
You need to compile with the extra flag -std=c++20. Moreover, there is an error in your code: pi and pi2 are declared const, hence you cannot modify them after they are initialized. Use this instead: #include <iostream> #include <numbers> int main() { const long double pi = std::numbers::pi_v<long double>; const long double pi2 = std::numbers::pi_v<long double>; std::cout << pi << std::endl << pi2; }
69,443,156
69,443,305
Subtracting 1 vs decrementing an iterator
In the accepted answer to "Iterator to last element of std::vector using end()--" @barry states: Note that if vector::iterator is just T* (which would be valid), the first form above is ill-formed. The second two work regardless, so are preferable. referring to his code: std::vector<int>::iterator it = --container.end(); std::vector<int>::iterator it = container.end() - 1; std::vector<int>::iterator it = std::prev(container.end()); This opinion is disputed in the comments, however without a clear resolution. So that's my question: what exactly is the semantic difference between the first and the second? And would the answer be different for iterators over structures other than vector?
For any standard library container, the member function end() returns an r-value. It's a "temporary" until you assign it to a variable. The decrement operator -- is not required to work on r-value iterators. You would be modifying a temporary, which C++ historically has taken measures to avoid. Therefore, --container.end() might compile on your standard-conforming C++compiler. But it might not. std::prev(container.end()) will work on every standard-conforming compiler. To review: --container.end() may not compile. It is up to the implementation. container.end() - 1 will only compile if the container uses random-access iterators. std::prev(container.end()) will always compile. All three forms will produce the same result, if they compile.
69,443,252
70,283,588
Problem with QT QGraphicsView on Jetson Xavier
I am having a weird issue, and I'm not really sure where to start on figuring out the issue or even what to search for this. Hopefully someone will have seen this before and can help! I have created a QT application in QTCreator/C++. I developed the app on a Ubuntu 20.04 machine which has QT version 5.12.8 (the default from apt). The application runs and behaves as expected on my development machine. For deployment, we are running the application on a Jetson Xavier, which is an ARM machine. It is running Ubuntu 18.04 which has QT version 5.9.5 installed (also the default for the OS). When I run the application there, everything works fine apart from one QGraphicsView, which shows a blank white screen instead of the intended display. GraphicsView A works, it shows a QPixMap on a Graphics Scene. GraphicsView B displays only white, it is supposed to show a series of points and lines on a black background (displayed in vector form as QObjects). Again this works fine on my machine. The difference between these two QGraphicsViews is that the one that doesn't work has a number of mouse input event functions enabled so you can pan and zoom the QGraphicsScene. I have discovered that if I comment out the following three lines in my QGraphicsView B setup, then I can see the points and lines again: m_graphicsView->setDragMode(QGraphicsView::ScrollHandDrag); m_graphicsView->viewport()->installEventFilter(this); m_graphicsView->setMouseTracking(true); The event filter handles scroll wheel events for zooming. It seems like any one of these three lines disables the view, I've tried several combinations of some commented out or not. Obviously when I remove these I can no longer pan/zoom the QGrapicsScene, which I need to able to do. I can't figure out why these functions might be affecting the QGraphicsView showing on the Jetson. I did find that the QMenu at the top of the application didn't work on the Jetson at first until I disabled the 'NativeMenuBar' attribute (presumably forcing a QT thing instead of native). I had a look through QGraphicsView and mouse things for something like this and came up blank.
This isn't a strict answer, but I eventually found a workaround that mitigates this issue. After a bit more investigation I found the problem to be specifically related to the Event Filter, and 'installEventFilter'. I'm not sure what the problem is still. The workaround I found was rather than using an event filter, I sub classed the QGraphicsView and handled the mouse events with customised versions of QGraphicsView::mouseReleaseEvent etc.
69,443,360
69,443,412
how is the address changed when passing a pointer to a pointer in function
I am a beginner to c++ and I've written this example code to help myself understand pointer to pointer as well as call by reference. I understood pretty much everything except for myFunc: cout << &ptr << endl; // 0x7ffeefbff4d8 I was hoping to get some clarification on this line. Since we are treating the address passed in as the value of a pointer to pointer, aka int** ptr. How is the address of ptr generated? Is ptr somehow implicitly intialized? Thanks in advance! void myFunc(int** ptr) { cout << ptr << endl; // 0x7ffeefbff520 int b = 20; *ptr = &b; cout << &ptr << endl; // 0x7ffeefbff4d8 cout << &b << endl; // 0x7ffeefbff4d4 cout << *ptr << endl; // 0x7ffeefbff4d4 return; } int main() { int *p; int a = 10; p = &a; cout << &a << endl; // 0x7ffeefbff51c cout << p << endl; // 0x7ffeefbff51c cout << *p << endl; // 10 cout << &p << endl; // 0x7ffeefbff520 myFunc(&p); cout << *p << endl; // 20 return 0; }
When you declare a function such as void myFunc(int** ptr) …you actually declare an argument which, even being a pointer to pointer to an int, remains passed by value. Consequently, it's treated like a local variable that would be declared at top of your function. This variable is therefore declared in the stack, and this is the address you get when using "&".
69,443,433
69,443,748
identifier "numIDs" is undefined while inside of scope
I am coding a small app thats supposed to take a string of numbers from a text file then save them into an array, and finally print the array through iteration, the file should be in this format: 10 0 1 2 3 4 5 6 7 8 9 The first number being the amount of numbers or "IDs" that should be in the array, the rest being the elements of this. #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream test; test.open("test.txt"); string s; getline(test, s); int numtest = s[0]; for (int i = 0; i < numtest; i++) { string currLine; getline(test, currLine); int numIDs = currLine[0]; int arrayIDs[numIDs]; for (int j = 2, k = 0; j < numIDs; j += 2, k++) { arrayIDs[k] = currLine[j]; } } test.close(); for (int i = 0; i <= numIDs; i++) { cout << arrayIDs[i]; } } However, i get the errors identifier "numIDs" is undefined identifier "arrayIDs" is undefined On lines 22 and 23 respectively, though i dont know why, to my understanding since these 2 are variables there shouldnt be any problems with an #include, and are both inside the main() function, so i dont get why they would be undefined.
Variables placed inside a loop will not be visible outside the loop. So to fix your problem, declare numIDs outside the loop instead of in it. Also, from the looks of it, you would want to put the second loop in the first. Original: int numtest = s[0]; for (int i = 0; i < numtest; i++) { string currLine; getline(test, currLine); int numIDs = currLine[0]; int arrayIDs[numIDs]; for (int j = 2, k = 0; j < numIDs; j += 2, k++) { arrayIDs[k] = currLine[j]; } } Revised: int numtest = s[0]; int numIDs = 0; for (int i = 0; i < numtest; i++) { string currLine; getline(test, currLine); numIDs = currLine[0]; int arrayIDs[numIDs]; for (int j = 2, k = 0; j < numIDs; j += 2, k++) { arrayIDs[k] = currLine[j]; } for (int i = 0; i <= numIDs; i++) { cout << arrayIDs[i] << ' '; } }
69,443,809
69,451,827
"Downcasting" a std::atomic_ref<T>
Is it possible to downcast between std::atomic_ref<T> and std::atomic_ref<U> where U is a subclass of T? I tried the following code which didn't work. template<typename T> std::atomic_ref<T> World::getComponentByID(componentInstanceId uuid) const { static componentTypeId key = stringHash(typeid(T).name()); return components.at(uuid); } The template parameter T was position (a subclass of Component). components is a map of componentInstanceIds to Components . error C2440: 'return': cannot convert from 'const std::atomic_ref<Component>' to 'std::atomic_ref<Position>
Usage of atomic_ref this way does not make sense. (Even in lock_free cases that make sense in assembly language, the ISO C++ standard doesn't expose that functionality.) As @Igor Tandetnik pointed out, "No subobject of an object referenced by an atomic_ref object may be concurrently referenced by any other atomic_ref object." One of reasons this rule exists is that for non-lock-free atomic_ref it implements pool of mutexes, so having sub-object with different pointer value will get you into a different mutex for a subobject, or even a mutex from a different pool, or it may happen that sub-object is lock-free, but the bigger object is lock-based. Additionally, possible pointer adjustments may defeat alignment, and it is mandatory for value referenced by atomic_ref to respect atomic_ref<T>::required_alignment. atomic_ref is not a general purpose facility. Perhaps you just need to protect your objects with std::mutex or std::shared_mutex instead.
69,444,901
69,444,959
Value not updating in class C++
I'm writing an assignment program which implements OOP principle which is meant to simulate an election. I have a class Party: class Party{ public: Party(){}; ~Party(){}; Party(std::string name, int budget){partyName = name; electionBudget = budget;} std::string getPartyName(){return partyName;} std::string getLeaderName(){return leaderName;} std::string getManagerName(){return managerName;} int getElectionBudget(){return electionBudget;} void setElectionBudget(int budget){electionBudget = budget;} void setLeaderName(std::string lName){leaderName = lName;} void setManagerName(std::string mName){managerName = mName;} std::vector<Stance> getPartyStances(){return partyStance;} void setPartyStances(std::vector<Stance> pStance){partyStance = pStance;} void *leaderPtr; void *managerPtr; void setLeader(void *a){leaderPtr = a; } void setManager(void *a){managerPtr = a;} void spendMoneyOnEvent(int cost){ int currentBudget = getElectionBudget(); setElectionBudget(currentBudget - cost); } void print(); private: std::string partyName; std::string leaderName; std::string managerName; std::vector<Stance> partyStance; int electionBudget; }; In a big for loop, every day I update the budget each party has left like this: for(Party p : partiesVector){ std::cout << p.getPartyName() << " budget remaining: " << "$" << p.getElectionBudget() << std::endl; } I also have the code implemented in my main.cpp to update the budget every time an event happens. For example: case 0: std::cout << debate.getEventName() << std::endl; std::cout << debate.getEventDecription() << std::endl; party1.spendMoneyOnEvent(500); std::cout << party1.debate.haveDebate(party1, party2, party3); break; However, no matter what I try with setting of things or trying to update the variable, it always remains the same (what I declared it as). Is there something I'm not understanding or missing here? Any help would be greatly appreciated, since I'm still relatively new to C++ Thanks!
for(Party p : partiesVector) is receiving the Party object by value, thus a copy made. Any updates to p will update the copy, not the original. Make sure such loops receive the Party by reference instead: for(Party &p : partiesVector) You should do this anyway, even for read-only loops. More importantly, your display loop is iteration through a vector of Party objects, but your update code is directly updating a Party object that is not in the vector. Likely you made another copy when you added the Party to the vector. So you should change your update code to refer to the Party in the vector. partiesVector[someIndex].spendMoneyOnEvent(500); Or else change the vector to hold pointers to Party objects you have created external to the vector. vector<Party*> partiesVector; ... Party party1; ... partiesVector.push_back(&party1); ... party1.spendMoneyOnEvent(500); ... for(Party *p : partiesVector) {...}
69,445,747
69,449,681
What is "int (*arr)[cols]" where "cols" is a variable, in C++?
I am reading this to consider about how to dynamically allocate memory for a two-dimensional array. I notice that a variable value cols can be used as size to define int (*arr)[cols], as C language has variable-length arrays(VLA) feature, then I try modifying the code into C++ like: #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> void* allocate(size_t rows, size_t cols) { int (*arr)[cols] = (int (*)[cols])malloc(rows *sizeof(*arr)); memset(arr, 0, rows *sizeof(*arr)); return arr; } int main() { size_t rows, cols; scanf("%zu %zu", &rows, &cols); int (*arr)[cols] = (int (*)[cols])allocate(rows, cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%3d", arr[i][j]); } printf("\n"); } } compile with gcc 11.2 -std=c++11 To my surprise, this works well and compiler does not report any warning. AFAIK C++ has no VLA feature, I used to think this code should be forbidden. So why could this work?
-std=c++11 doesn't mean "compile strictly according to C++11" but "enable C++11 features." Just as -std=gnu++11 (the default setting) means enable gnu++11 features, which is a superset of C++11. To get strictly compliant behavior, you must use -std=c++11 -pedantic-errors. And then you get this: error: ISO C++ forbids variable length array 'arr' [-Wvla] See What compiler options are recommended for beginners learning C? for details. It was written for C but applies identically to g++ as well.
69,446,555
69,446,660
Is reading a variable outside its lifetime during constant evaluation diagnosable?
Shall one expect a reliable failure of in constant evaluation if it reads a variable outside of its lifetime? For example: constexpr bool g() { int * p = nullptr; { int c = 0; p = &c; } return *p == 0; }; int main() { static_assert( g() ); } Here Clang stops with the error read of object outside its lifetime is not allowed in a constant expression But GCC accepts the program silently (Demo). Are both compilers within their rights, or GCC must fail the compilation as well?
GCC dropped the ball. [expr.const] 5 An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following: ... an operation that would have undefined behavior as specified in [intro] through [cpp]; ... Indirection via dangling pointer has undefined behavior. [basic.stc.general] 4 When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values. Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior. So the invocation of g() may not be a constant expression, and may not appear in the condition of a static_assert which must be constant evaluated. The program is ill-formed. The above quotes are from the C++20 standard draft, but C++17 has them too.
69,447,075
69,447,138
Assignment operator is not calling parameterized constructor while copy constructor present in code
CASE 1: When I create a object of class with an assignment operator , it calls parameterized constructor if there in no copy constructor in code. Below code is without copy constructor: class Test{ public: int a; Test(int a){ this->a = a; } }; int main(){ Test x = 6; cout<<x.a; return 0; } CASE 2: But if there is copy constructor present in class then it gives error if I use assignment operator while declaring class object. Error : cannot bind non-const lvalue reference of type ‘Test&’ to an rvalue of type ‘Test’ Below code is with copy constructor class Test{ public: int a; Test(int a){ this->a = a; } Test(Test &b){ this->a = b.a; } }; int main(){ Test x = 6; cout<<x.a; return 0; } My question is how just presence of copy constructor is result ending up with error ? . With presence of copy constructor also my program should call Parameterize constructer when I assign a parameter to object of class.
I think this: Test(Test &b){ this->a = b.a; } Should actually be this: Test(Test const &b){ this->a = b.a; } Copy constructor should get a const reference, and they should copy the parameter content into the current object content, not the other way around..
69,447,591
69,447,827
Write calculation output in a txt file
This a very beginner question. I'm trying to create a simple c++ switch case based console calculator that creates a txt file and writes the output to it. I have very little experience with OOPS or C++ so I have no clue on how to make this work. This snippet creates a text file and writes to it: #include <iostream> #include <fstream> using namespace std; int main() { ofstream MyFile("filename.txt"); MyFile << "Lorem ipsum dolor amet"; MyFile.close(); } When I try to add this to my calculator code, it gives me a bunch of errors: #include <iostream> #include <fstream> using namespace std; int main() { char op; float num1, num2; cout << "Enter Operator: +, -, *, / : "; cin >> op; cout << "Enter two Operands: "; cin >> num1 >> num2; switch(op) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; ofstream MyFile("filename.txt"); MyFile << num1 << " + " << num2 << " = " << num1 + num2; MyFile.close(); break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; ofstream MyFile("filename.txt"); MyFile << num1 << " - " << num2 << " = " << num1 - num2; MyFile.close(); break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; ofstream MyFile("filename.txt"); MyFile << num1 << " * " << num2 << " = " << num1 * num2; MyFile.close(); break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; ofstream MyFile("filename.txt"); MyFile << num1 << " / " << num2 << " = " << num1 / num2; MyFile.close(); break; default: cout << "Error! Operator is not correct"; break; } return 0; } The error messages in the console: calctext.cpp: In function 'int main()': calctext.cpp:25:14: error: jump to case label 25 | case '-': | ^~~ calctext.cpp:20:18: note: crosses initialization of 'std::ofstream MyFile' 20 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:27:18: error: redeclaration of 'std::ofstream MyFile' 27 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:20:18: note: 'std::ofstream MyFile' previously declared here 20 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:32:14: error: jump to case label 32 | case '*': | ^~~ calctext.cpp:20:18: note: crosses initialization of 'std::ofstream MyFile' 20 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:34:18: error: redeclaration of 'std::ofstream MyFile' 34 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:20:18: note: 'std::ofstream MyFile' previously declared here 20 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:39:14: error: jump to case label 39 | case '/': | ^~~ calctext.cpp:20:18: note: crosses initialization of 'std::ofstream MyFile' 20 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:41:18: error: redeclaration of 'std::ofstream MyFile' 41 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:20:18: note: 'std::ofstream MyFile' previously declared here 20 | ofstream MyFile("filename.txt"); | ^~~~~~ calctext.cpp:46:9: error: jump to case label 46 | default: | ^~~~~~~ calctext.cpp:20:18: note: crosses initialization of 'std::ofstream MyFile' 20 | ofstream MyFile("filename.txt");
The scope of a variable declared inside a switch is the entire switch-block - a case is not a separate scope. This leads to two problems: Multiple declarations of the same variable name, and Jumping across a variable initialization, which you're not allowed to do. The trivial fix is to wrap each case in a pair of curly braces, adding a new scope: case '+': { ofstream MyFile("filename.txt"); cout << num1 << " + " << num2 << " = " << num1 + num2; MyFile << num1 << " + " << num2 << " = " << num1 + num2; // You don't need to explicitly close a file, its destruction takes care of it. break; } but I would remove the code duplication instead: bool valid_op = true; float result = 0; switch(op) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: cout << "Error! Operator is not correct"; valid_op = false; break; } if (valid_op) { ofstream MyFile("filename.txt"); cout << num1 << ' ' << op << ' ' << num2 << " = " << result; MyFile << num1 << ' ' << op << ' ' << num2 << " = " << result; }
69,447,701
69,448,017
How do I find same lines in two files C++?
I need to write a program for my school project, which compares lines from two large files, one approx. 1.5G(40kk lines), and other one is approx. 5gb(100kk lines) to find duplicate lines and write those lines to new file. I've already tried writing those programs in NodeJs and Python, however, they weren't able to compare those files, on Python it look like 30 minutes only to compare one line. Perhaps I was doing something wrong. I wonder if C++ would be able to handle this task with ease, what's the fastest way to compare those files, any suggestions?
You have multiple options to go about this and none of them are pretty. I believe, one of the more efficient options goes about something like this: #include <iostream> #include <fstream> #include <map> int main() { std::ifstream firstFile("firstFile"); std::ifstream secondFile("secondFile"); if (firstFile.is_open() && secondFile.is_open()) { std::string line; while(!secondFile.eof()) { std::map<std::string, bool> stringMap; for (int i = 0; i < 500000 && !std::getline(secondFile, line).eof(); ++i ) stringMap[line] = false; while (!std::getline(firstFile, line).eof()) { std::map<std::string, bool>::iterator it = stringMap.find(line); if (it != stringMap.end()) it->second = true; } firstFile.clear(); //Clears the eof Flag. firstFile.seekg(0); //Rewinds to the beginning of the list. //Iterate over map and write all matches to the result file } } return 0; } This (kinda pseudo) code will read the second file in chunks of 500k lines, performs a check against all lines of the first file and gives you a list of all lines that are in both files. Completely untested though.
69,447,778
69,451,722
Fastest way to draw filled quad/triangle with the SDL2 renderer?
I have a game written using SDL2, and the SDL2 renderer (hardware accelerated) for drawing. Is there a trick to draw filled quads or triangles? At the moment I'm filling them by just drawing lots of lines (SDL_Drawlines), but the performance stinks. I don't want to go into OpenGL.
SDL_RenderGeometry()/SDL_RenderGeometryRaw() were added in SDL 2.0.18: Added SDL_RenderGeometry() and SDL_RenderGeometryRaw() to allow rendering of arbitrary shapes using the SDL 2D render API Example: // g++ main.cpp `pkg-config --cflags --libs sdl2` #include <SDL.h> #include <vector> int main( int argc, char** argv ) { SDL_Init( SDL_INIT_EVERYTHING ); SDL_Window* window = SDL_CreateWindow("SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN ); SDL_Renderer* renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); const std::vector< SDL_Vertex > verts = { { SDL_FPoint{ 400, 150 }, SDL_Color{ 255, 0, 0, 255 }, SDL_FPoint{ 0 }, }, { SDL_FPoint{ 200, 450 }, SDL_Color{ 0, 0, 255, 255 }, SDL_FPoint{ 0 }, }, { SDL_FPoint{ 600, 450 }, SDL_Color{ 0, 255, 0, 255 }, SDL_FPoint{ 0 }, }, }; bool running = true; while( running ) { SDL_Event ev; while( SDL_PollEvent( &ev ) ) { if( ( SDL_QUIT == ev.type ) || ( SDL_KEYDOWN == ev.type && SDL_SCANCODE_ESCAPE == ev.key.keysym.scancode ) ) { running = false; break; } } SDL_SetRenderDrawColor( renderer, 0, 0, 0, SDL_ALPHA_OPAQUE ); SDL_RenderClear( renderer ); SDL_RenderGeometry( renderer, nullptr, verts.data(), verts.size(), nullptr, 0 ); SDL_RenderPresent( renderer ); } SDL_DestroyRenderer( renderer ); SDL_DestroyWindow( window ); SDL_Quit(); return 0; } Note that due to the API lacking a data channel for Z coordinates only affine texturing is achievable.
69,447,813
69,447,847
Returning objects created within the called function's context
I remember reading somewhere that we should avoid returning objects that are created locally within the called function (i.e. only dynamically allocated objects may be returned). However, I am not sure if that is sound advice because when dealing, for example, with overloaded operators we may have code like the following (taken from Object-Oriented Programming in C++ by Lafore, 4e) : // Distance operator+ (Distance d1, Distance d2) //add d1 to d2 { int f = d1.feet + d2.feet; //add the feet float i = d1.inches + d2.inches; //add the inches if(i >= 12.0) //if inches exceeds 12.0, { i -= 12.0; f++; } //less 12 inches, plus 1 foot return Distance(f,i); //return new Distance with sum } //-------------------------------------------------------------- Question: What are the dos and don'ts for returning automatically allocated objects from a function?
I remember reading somewhere that we should avoid returning objects that are created locally within the called function (i.e. only dynamically allocated objects may be returned). You remember wrong. You should not return pointers or references to local objects: int& foo() { int x = 42; return x; // DONT DO THIS } The returned reference is dangling. It refers to an int whose lifetime ended when the function returned. The function itself is kind of "ok", but the caller cannot read from the returned reference without invoking undefined behavior. There is no problem with returning a copy of a local variable, other than a copy that you maybe can avoid, but that doesn't apply to operator+. Also there is RVO and copy elision (see What are copy elision and return value optimization?). In the code you posted the operator should take its parameters by const& to avoid a copy, but you cannot avoid creating a new instance, because the result needs to be stored somewhere.
69,447,994
69,450,073
Getting wrong answer for sorting linked list using merge sort
I tried writing a custom version of merge sort in which the sortList function is recursive but the merging function is iterative. I have tried dry running but unable to figure out the problem. This one is a custom testcase which is also resulting in Wrong Answer. Your input: 5 4 3 1 2 6 Your function returned the following: 1 -> 2 -> 3 -> 6 Link of the question : https://www.interviewbit.com/problems/sort-list/ The entire code : /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ ListNode* Solution::sortList(ListNode* A) { ListNode * head = A; if(!(head) || !(head->next)) { return head; } ListNode * slow = head, * fast = head; while((fast->next) && (fast->next->next)) { fast = fast->next->next; slow = slow->next; } ListNode * temp = slow->next; slow->next = NULL; head = sortList(head); temp = sortList(temp); ListNode * ptr; ListNode * ans; ans = head->val > temp->val ? temp : head; while(head!=NULL && temp!=NULL) { if(head->val > temp->val){ ptr = temp; temp = temp->next; ptr->next = head; }else { ptr = head; head = head -> next; ptr->next = temp; } } return ans; }
The merge function I was trying to implement was wrong. Here is the correct code. ListNode* Solution::sortList(ListNode* A) { ListNode * head = A; if(!(head) || !(head->next)) { return head; } ListNode * slow = head, * fast = head; while((fast->next) && (fast->next->next)) { fast = fast->next->next; slow = slow->next; } ListNode * temp = slow->next; slow->next = NULL; head = sortList(head); temp = sortList(temp); ListNode * ans = new ListNode(0); ListNode * realAns = ans; while(head!=NULL && temp!=NULL) { if(head->val > temp->val) { ans->next = temp; temp = temp->next; }else{ ans->next = head; head = head->next; } ans = ans->next; } if(temp==NULL && head!=NULL) { ans->next = head; }else if(temp!=NULL && head==NULL) { ans->next = temp; } return realAns->next; }
69,448,172
70,651,010
Can we run the openGL project from server using node.js child process?
I have been trying to automate the launching of OpenGL Project from server using node.js The problem is like whenever new client join in (create a window in browser) I want to launch the .exe file. .exe file is an OpenGL Project which renders different shapes using openGL and then send’s rendered data to the browser to display Shape on canvas. I am currently using child process to launch the exe whenever new client join in, but the thing is I am not able to render data in openGL Context whenever I launch exe (OpenGL Project) through the child process of node.js (though I am able to render if I launch exe without child process i.e. Manually). Here I am not able to conclude things like, Is it even possible to run an openGL Project from node.js child Process, will there be any openGL limitation specifically for node.js ? Is there any other way to launch the .exe when new browser window is created ?
Yes we can definitely run the openGL standalone application/project from node server using node's child process. The mistake in my application was, directory of the shader program was not relative with the child process directory.
69,448,623
69,448,794
Executing a generic function every N times with a static variable
I am trying to write a wrapper function that executes a given function every N times (something similar to Google logging's LOG_EVERY_N). What I have done so far is: #include <cstddef> #include <functional> #include <utility> template<size_t N, typename Callable, typename... Args> void call_every_n(Callable&& c, Args... args) { static size_t __counter = 0; if(__counter == N - 1) { std::invoke(std::forward<Callable>(c), std::forward<Args>(args)...); __counter = 0; } else ++__counter; } #define CALL_EVERY_N(N, FUNC, ...) call_every_n<N, decltype(&FUNC), decltype(__VA_ARGS__)>(FUNC, __VA_ARGS__) The problem is with the usage of the static variable for the internal counter but I cannot figure out how to achieve this differently. In fact, this code works as expected until I call the same function with the same N. This is an example which demonstrates the issue: #include <iostream> void test(int a, int num) { std::cout << num << " = " << a << "\n"; } int main() { for(int i = 1; i < 20; ++i) { CALL_EVERY_N(3, test, i, 1); CALL_EVERY_N(3, test, i, 2); } return 0; } This code outputs: 1 = 2 2 = 3 1 = 5 2 = 6 1 = 8 2 = 9 1 = 11 2 = 12 1 = 14 2 = 15 1 = 17 2 = 18 i.e. the exact same static variable is used (and then modified) by the two different functions. I also would like to enforce the fact that Callable must be a function returning void, how could I do it?
Every lambda expression is of different type, hence you can use it as a tag: #include <cstddef> #include <functional> #include <iostream> template<size_t N, typename Callable,typename Dummy, typename... Args> void call_every_n(Dummy,Callable&& c,Args&&... args) { static size_t counter = 0; if(counter == N - 1) { std::invoke(std::forward<Callable>(c), std::forward<Args>(args)...); counter = 0; } else ++counter; } #define CALL_EVERY_N(N, FUNC, ...) call_every_n<N>([]{},FUNC, __VA_ARGS__) // in each expansion, this is of different type ^^ void test(int a, int num) { std::cout << num << " = " << a << "\n"; } int main() { for(int i = 1; i < 20; ++i) { CALL_EVERY_N(3, test, i, 1); CALL_EVERY_N(3, test, i, 2); } return 0; } Output: 1 = 3 2 = 3 1 = 6 2 = 6 1 = 9 2 = 9 1 = 12 2 = 12 1 = 15 2 = 15 1 = 18 2 = 18 Only since C++20 the lambda expression can appear in unevaluated context (decltype), before a dummy parameter needs to be passed to deduce its type. You don't need to use decltype for the others, the template parameters can be deduced from the functions parameters. Perfect forwarding via std::forward requires universal references (ie Args&&). Note that names starting with __ are reserved for the implementation. Don't use them.
69,449,383
69,449,415
Adding new item in C++ array
I am pretty new to c++ and was trying to add a new string in C++ array. In Python we can add new items by .append(). Is there any function like this in C++?
in C++ arrays are of a static size. I would recommend including the vector header and replacing the array with a std::vector. vector has a function to add a new entry
69,449,781
69,552,515
<utility> not necessarily included when swap() is performed - How can this become a problem?
Reading C++ named requirements: Swappable I've come across the following note It is unspecified whether <utility> is actually included when the standard library functions perform the swap, so the user-provided swap() should not expect it to be included. Suppose I have a user-defined type class Foo with a user-provided swap(). I'd like to use a Standard Library algorithm for my class Foo that performs a swap with using std::swap; swap(arg1, arg2); as described in the above-mentioned cppreference article, and the file that I have to #include to use this algorithm does NOT #include <utility>. If I relied on functionality provided by <utility> in my swap(), how could this lead to a problem? I'd have to #include <utility> myself in the file that defines my swap(). The scenario should be similar to the following: I have a file that #includes my class Foo with my user-provided swap() and the header for the algorithm that I use. Consequently, there should never be an issue regarding whether the algorithm does #include <utility> or not. I might have misunderstandings revolving around how #include and compilation could interact with each other in some different scenarios. Which situation could potentially lead to compilation issues here?
Let's try to understand the note you quoted from cppreference. It is unspecified whether <utility> is actually included when the standard library functions perform the swap, so the user-provided swap() should not expect it to be included. E.g., std::sort may perform the swap. To use std::sort, you need to include <algorithm>. The statement basically says, despite this, <algorithm> may not have <utility> included. It follows that below code may be problematic. #include <algorithm> int main() { int arr[] = { 4, 1, 7 }; std::sort(arr, arr + 3); std::swap(arr[0], arr[1]); // may error out here } This is counter-intuitive, for std::sort performs std::swap internally itself. To stay on the safe side, always explicitly include <utility> if you need std::swap. Don't assume that some other standard library headers that use std::swap themselves have <utility> included for you. Following code should always work, while #include <utility> seems unnecessary at first sight. #include <algorithm> #include <utility> int main() { int arr[] = { 4, 1, 7 }; std::sort(arr, arr + 3); std::swap(arr[0], arr[1]); }
69,449,788
69,451,505
Get path of a known HWND
I'm trying to make an app that will run something only if in the moment that the dll is called, the window that is focused in that moment has the same path as a values that is given. That being said, the following code will be added in a dll which will have a function with the path value as it parameter that returns true if the condition is met, or false otherwise. The problem I have is that I can't seem to find a way to get the path of the focused window, the following code always returns an empty string. And I can't simply use the title of the windows because there are apps that yes, the title is static like Task Manager, but there are others that the title is changed, like Windows Explorer changes it's title depending where the user is in. What do I have to change? The following code is used only as a test, because later on that is the base for what I need, and I will only have to add a comparison on path variable, and based on that to return true or false: #include "Windows.h"; #include <iostream> #include <chrono> #include <thread> using namespace std; int main() { // 2 seconds delay to have time to switch windows std::this_thread::sleep_for(std::chrono::milliseconds(2000)); HWND hWnd = GetForegroundWindow(); int length = GetWindowTextLength(hWnd); wchar_t* title = new wchar_t[length]; GetWindowTextW(hWnd, title, length); DWORD id; GetWindowThreadProcessId(hWnd, &id); wchar_t* path = new wchar_t[MAX_PATH]; HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id); GetModuleFileNameW((HMODULE)hProc, path, MAX_PATH); CloseHandle(hProc); wcout << "ID: " << id << " | Title: " << title << " | Path: " << path << endl << endl; return 1; } Output example: ID: 2536 | Title: Task Manage | Path:
To get the result I wanted, I switched to QueryFullProcessImageName (like CherryDT suggested to take a look at), but you have to be careful, you need to run it with Admin rights to get the path for some apps like I encountered with Task Manager, maybe because it is an Windows app, not sure and you'll have to do some research on that if you need more details. Here is a little example: #include "Windows.h"; #include <iostream> #include <chrono> #include <thread> using namespace std; int main() { // 2 seconds delay to have time to switch windows std::this_thread::sleep_for(std::chrono::milliseconds(2000)); HWND hWnd = GetForegroundWindow(); int lgth = GetWindowTextLength(hWnd) + 1; wchar_t* title = new wchar_t[lgth]; GetWindowTextW(hWnd, title, lgth); DWORD id; GetWindowThreadProcessId(hWnd, &id); wchar_t* path = new wchar_t[MAX_PATH]; DWORD size = MAX_PATH; HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, id); QueryFullProcessImageNameW(hProc, 0, path, &size); CloseHandle(hProc); wcout << "ID: " << id << " | Title: " << title << " | Path: " << path << endl << endl; return 1; } Output example: ID: 12580 | Title: Task Manage | Path: C:\Windows\System32\Taskmgr.exe
69,449,981
69,450,190
What is the relation between C storage-class and C++ destructor
I am very new to C/C++ programming. Storage class in C signifies the visibility and life cycle of a variable. In C++, Constructor and Destructor are used to initialize & release-resources the object occupied. Yes, constructor helps reducing much of repetitive code but destructors are used to release and/or free resources (once an object goes out of scope). Are these concepts coupled in some way in their implementation?
For C Storage classes see: https://stackoverflow.com/a/2661411/8740349 Let's not talk about implementions, as each compiler works differently, but if you ask about C++ spec, most keywords mean the same. Except that: register keyword was removed since C++17 (after being deprecated in C++11), without any alternative. auto means to auto-detect type, like: auto myVariable = myFunction("blablabla (how old are you, in Chinese)"); Is destructor related to storage-class? No, C++ Class and/or Struct is destructed before it's storage is deallocated. As mentioned in comments: Handling deallocation of storage isn't the subject of the destructor but the subject of the respective "deallocator" (provided by the compiler e.g. for global and local variables or the delete for memory allocated with new).
69,450,046
69,450,757
How to call function that use part of template parameter pack in c++?
I have following problem: I want to create variadic template class, that must call lambda, that may take first N parameters of template parameter pack (N may vary from 0 to the size of parameters pack and differs for different lambda). I think, that recursive template helper function, that will check if lambda is invokable, starting with all parameters, should be the best variant, but how can I pass all but last parameters from parameters pack to it and is it possible at all? At the moment I see it as something like this: template< typename Callable, typename ...Args > void Call( Callable& cb, Args... args ) { using Function = std::remove_reference_t< Callable >; if constexpr( std::is_invocable_v< Function, Args... > ) cb( args... ); else if constexpr( sizeof...( args ) == 0 ) cb(); else { // Here I want to create shortened_args, that are all args but last one. // Call( cb, shortened_args... ); } } UPD: I didn't mention it first, but I need C++17 solution.
You might use std::index_sequence as helper: template <typename Callable, typename Tuple, std::size_t... Is> constexpr std::size_t is_invocable_args(std::index_sequence<Is...>) { return std::is_invocable_v<Callable, std::tuple_element_t<Is, Tuple>...>; } // Helper to know max number of args to take from tuple template <typename Callable, typename Tuple, std::size_t... Is> constexpr std::size_t max_invocable_args(std::index_sequence<Is...>) { std::array<bool, sizeof...(Is)> a = { is_invocable_args<Callable, Tuple>(std::make_index_sequence<Is>{})... }; auto rit = std::find(a.rbegin(), a.rend(), true); if (rit == a.rend()) throw "no valid call"; return std::distance(a.begin(), rit.base()) - 1; } template <std::size_t N, typename Callable, typename Tuple> constexpr std::size_t max_invocable_args() { return max_invocable_args<Callable, Tuple>(std::make_index_sequence<N + 1{}); } // Call taking some element from tuple template< typename Callable, std::size_t... Is, typename Tuple > void Call_Tuple_impl(Callable cb, std::index_sequence<Is...>, Tuple&& args ) { std::invoke(cb, std::get<Is>(std::forward<Tuple>(args))...); } template< typename Callable, typename ...Args > void Call( Callable cb, Args... args ) { constexpr std::size_t max_arg_count = max_invocable_args<sizeof...(Args), Callable, std::tuple<Args...>>(); Call_Tuple_impl(cb, std::make_index_sequence<max_arg_count>{}, std::forward_as_tuple(std::forward<Args>(args)...)); } C++20 Demo C++17 Demo with rewritten constexpr find.
69,450,122
69,450,308
I want to make a static library for other programs to use, but I don't know why it failed
This is the source code of the file: fileselector.h: #ifndef FILE_SELECTOR #define FILE_SELECTOR const char *open_file_dialog(); const char *save_file_dialog(); #endif linux/fileselector.cpp: #include <cstring> #include "../fileselector.h" #include <iostream> const char *open_file_dialog() { ... } const char *save_file_dialog() { ... } This is my static library production steps: $ gcc linux/fileselector.cpp fileselector.h -c $ ar rs libfileselector.a fileselector.o This is a test using a static library: main.c #include "fileselector.h" int main() { open_file_dialog(); return 0; } $ gcc main.c -L. -lfileselector -o main /usr/bin/ld: /tmp/ccOTrMR8.o: in function `main': main.c:(.text+0xa): undefined reference to `open_file_dialog' collect2: error:ld return 1 Where is the problem?
You defined a set of C++ functions but are using them from a C program. Function names in C++ are mangled during the compilation phase to allow for multiple functions with the same name but different signatures to exist. C programs don't do name mangling, so the compiled name of the library functions don't match the plain function name that the C program expects. If you want C++ functions to be usable by a C program, you need to disable name mangling by adding extern "C" around the definitions and declarations. So your C++ source file would look like this: extern "C" { const char *open_file_dialog() { ... } const char *save_file_dialog() { ... } } And your header would look like this: #ifdef __cplusplus extern "C" { #endif const char *open_file_dialog(); const char *save_file_dialog(); #ifdef __cplusplus } #endif The #ifdef's in the header are needed because extern "C" is a C++ only feature. Also, it's not necessary to list the header file when compiling. Because it is included in the source file it is already being compiled.
69,450,136
69,562,210
Different behaviours when initializing differently
When trying to initialize a Vector using the result of some operation in Eigen, the result seems to be different depending on what syntax is used, i.e., on my machine, the assertion at the end of the following code fails: const unsigned int n = 25; Eigen::MatrixXd R = Eigen::MatrixXd::Random(n,n); Eigen::VectorXd b = Eigen::VectorXd::Random(n); Eigen::VectorXd x = Eigen::VectorXd::Zero(n); Eigen::VectorXd y = Eigen::VectorXd::Zero(n); y = R.triangularView<Eigen::Upper>().solve(b); x << R.triangularView<Eigen::Upper>().solve(b); assert((x-y).norm() < std::numeric_limits<double>::epsilon()*10E6); I am aware of potential rounding errors, but in my understanding, the two evaluations of R.triangularView<Eigen::Upper>().solve(b) should have the exact same precision errors, and therefore the same result. This also only happens when initializing one variable with <<and the other withoperator=, but not if both variables are assigned to the same way. When not using only backwards substitution on the upper triangular part but evaluating R.lu().solve(b)on both and comparing the result, the difference is far smaller, but still exists. Why are the two vectors different if assigned in nearly the same, deterministic way? I tried this code on Arch Linux and Debian with a x86-64 architecture, using Eigen Version 3.4.0, with C++11, C++17, C++20, compiled with both clang and gcc.
The "official" answer by Eigen maintainer Antonio Sànchez is the following: [...] In this case, the triangular solver itself is taking slightly different code paths: the comma-initializer version is using a path where the RHS could be a matrix the assignment version is using an optimized path where the RHS is known to be a compile-time vector Some order of operations here is causing slight variations, though the end results should be within a reasonable tolerance. This also reproduces the same issue: Eigen::VectorXd xa = R.triangularView<Eigen::Upper>().solve(b); Eigen::MatrixXd xb = R.triangularView<Eigen::Upper>().solve(b); https://godbolt.org/z/hf3nE8Prq This is happening because these code-path selections are made at compile-time. The solver does an in-place solve, so ends up copying b to the output first, then solves. Because of this, the matrix/vector determination actually ends up using the LHS type. In the case of the comma initializer (<<), the expression fed into the << operator is treated as a general expression, which could be a matrix. If you add .evaluate() to that, it first evaluates the solve into a temporary compile-time vector (since the vector b is a compile-time vector), so we get the vector path again. In the end, I don't think this is a bug, and I wouldn't necessarily call it "intended".[...] It goes into the same direction as H.Rittich theorizes in their answer: operator<< and operator= simply lead to different code paths, which in turn allow for different optimizations.
69,450,317
70,093,969
Group .ui files in project tree when using CMake
I have a simple gui project in QtCreator, which consists of several .cpp .h and .ui files and using CMake as a build system. The problem i face is that .ui files, as oposed to .cpp and .h files, aren't grouped under corresponding header in project tree. They are just shown on the same level as .cpp and .h headers (see picture below). I had no such problem when i was using qmake as a build system. I can totally live with that, but it can get really annoying as the project grows. Is there a way in QtCreator to customize appearance of a project tree?
You can use source_group in your CMakeLists.txt to group *.ui files as a source group in QtCreator or another IDE file(GLOB_RECURSE UI_SRC "*.ui") source_group("Ui Files" FILES ${UI_SRC}) This also works for .qml files for example.
69,450,456
69,450,501
sscanf converting from octal: How does it know?
I have this code which converts a string to an int unsigned int formatInt(char *ptr) { int res; if (sscanf(ptr, "%i", &res) == -1) exit(-1); return res; } I fed it a char * pointing to the first char of "00000000041". Conversion to int returns me 33 (Implicit Octal to Decimal conversion) "00000000041" is actually a string (char[12]), but it's the size of a file in octal. How did the compiler know it was in octal ? 00000000041 could perfectly be a decimal (41)
Recognizing the string as octal is a function of the %i format specifier to scanf. From the man page: i Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used. So because the string begins with a 0 and %i was used, it is interpreted as an octal string.
69,450,645
69,450,701
How to provide a default parameter argument when the type of that parameter is a template type?
template <class V, class K> class Pair { public: Pair(const K& key, const V& value = initial) { // what should "initial" be here? // ... } } For example if I use the class like this: int main() { Pair<int, std::string> p1(21); // p1 should be {21, ""} as the default value of a string is "". Pair<int, double> p2(20); // p2 should be {20, 0.0} assuming the default value of a double is 0.0 } How can I achieve this?
Try V() like: template <class K, class V> class Pair { public: Pair(const K& key, const V& value = V()) { } }; Or: template <class K, class V> class Pair { public: Pair(const K& key, const V& value = {}) { } }; Note that a default constructor is required (which is callable without arguments).
69,450,654
69,469,099
Iterating C array-type container class from Lua using LuaBridge
This may be a newbie question, but I have not been able to find an answer with web searching that will even help me get started. I have a container class that at heart is a C-style array. For simplicity, let's depict it as this: int *myArray = new int[mySize]; With LuaBridge we can assume I have successfully registered it as my_array in the global namespace. I would like to iterate over it from Lua like this: for n in each(my_array) do ... -- do something with n end I'm guessing I probably need to register a function each in the global namespace. The problem is, I don't know what that function should look like in C++. <return-type> DoForEach (<function-signature that includes luabridge::LuaRef>) { // execute callback using luabridge::LuaRef, which I think I know how to do return <return-type>; //what do I return here? } This would perhaps have been easier if the code had used std::vector but I am trying to create a Lua interface to an existing code base that is complicated to change.
I'm answering my own question, because I have figured out that the question makes some incorrect assumptions. The existing code I was working with was a true iterator class (which is what it is called in the Lua docs) implemented in c++. These cannot be used with for loops, but that's how you get a callback function in c++. To do what I was originally asking, we'll assume we've made myArray available as table my_array in lua using LuaBridge or whichever interface you prefer. (This may require a wrapper class.) You implement what I was asking entirely in Lua as follows. (This is almost exactly an example in the Lua documentation, but somehow I missed it earlier.) function each (t) local i = 0 local n = table.getn(t) return function () i = i + 1 if i <= n then return t[i] end end end --my_array is a table linked to C++ myArray --this can be done with a wrapper class if necessary for n in each(my_array) do ... -- do something with n end If you want to provide the each function to every script you run, you add it directly from C++ as follows, before executing the script. luaL_dostring(l, "function each (t)" "\n" "local i = 0" "\n" "local n = table.getn(t)" "\n" "return function ()" "\n" " i = i + 1" "\n" " if i <= n then return t[i] end" "\n" "end" "\n" "end" );
69,450,682
69,452,567
Flatten nested for loops with C++20 ranges
Sometimes I need to "double for loop" and since I do nothing in outer for loop for first loop variable beside passing it to inner for loop I wonder if it can be done elegantly with C++20 ranges. Example of nested for loops I would like to "flatten". struct Person{ std::string name = "Bjarne"; }; std::vector persons{Person{}, Person{}}; int main() { for (const auto& person: persons) { for (const auto& ch: person.name) { std::cout << ch << std::endl; } } } Best what I can think of is: std::ranges::for_each(persons | std::views::transform(&Person::name) | std::views::join, [](const char& ch){ std::cout << ch << std::endl; }); but I wonder if there is a simpler way.
Yeah, what you propose is correct. Except it can still be a range-based for statement, you don't have to switch to an algorithm: for (const auto& ch : persons | std::views::transform(&Person::name) | std::views::join) { // ... } Most languages use the name map instead of transform, and flatten instead of join (indeed your question title asks about flattening). And then it's common to put these two together with a new algorithm called flat_map which does both of these things together. We can do that too: inline constexpr auto flat_map = [](auto f){ return std::views::transform(f) | std::views::join; }; for (const auto& ch : persons | flat_map(&Person::name)) { // ... } Although in C++ I suppose this would be called transform_join? Meh. flat_map all the way. Pro-tip: use fmt::print to print ranges, less to write and it already comes out formatted.
69,450,804
69,450,951
what does variable != 0xFF mean in C++?
I have the following if function that has a condition on an array of a data buffer, which stores data of a wav file bool BFoundEnd = FALSE; if (UCBuffer[ICount] != 0xFF){ BFoundEnd = TRUE; break; } I was just confused on how 0xFF defines the condition inside the if function.
what does variable != 0xFF mean in C++? variable is presumably an identifier that names a variable. != is the inequality operator. It results in false when left and right hand operands are equal and true otherwise. 0xFF is an integer literal. The 0x prefix means that the literal uses hexadecimal system (base 16). The value is 255 in decimal system (base 10) and 1111'1111 in binary system (base 2). For more information about the base i.e. the radix of numeral systems, see wikipedia: Radix
69,450,988
69,451,032
Vector elements to a string
I'm trying to turn a vector<int> into a string, with a '[' at the beginning, and a ',' between each element of the vector, and a ']' at the end. But my output is [,,,,] (wanted output [6,4,3,2,1]). Can you explain to me what i'm doing wrong? Here's what I tried: int main() { std::vector<int> elements = {1,2,3,4,6}; std::string outputString = "["; for(int i = elements.size() - 1; i >= 0; i--) { if (i > 0) { outputString.push_back(elements.at(i)); outputString.push_back(','); } else { outputString.push_back(elements.at(i)); } } outputString.push_back(']'); std::cout << std::endl << outputString << std::endl; }
std::string::push_back adds a single char to the string and you tripped over the implicit conversion of int to char. The low values correspond to non-printable characters, thats why you don't see them in the output. You can use operator+= and std::to_string: #include <vector> #include <string> #include <iostream> int main() { std::vector<int> elements = {1,2,3,4,6}; std::string outputString = "["; for(int i = elements.size() - 1; i >= 0; i--) { if (i > 0) { outputString += std::to_string(elements.at(i)); outputString.push_back(','); } else { outputString += std::to_string(elements.at(i)); } } outputString.push_back(']'); std::cout << std::endl << outputString << std::endl; } PS: I didn't even know that std::string::push_back exists. You can also use operator+= to add a single character to the string.
69,451,487
69,452,392
How to control implicit conversion from long to int?
I am working on this LeetCode problem to take an integer and reverse it, given that the reversed in is within the signed 32-bit range, in which case we should return 0. and this code is doing just that, even with numbers like 1534236469/-1534236469. Except when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0. I know this is not the cleanest code, but can you help me recognise what I'm missing? #include<iostream> #include<limits> using namespace std; class Solution { public: int reverse(int x) { int a, r, y; string num, fnum; a = abs(x); try{ while(a != 0){ r = a % 10; a = a / 10; num = to_string(r); fnum = fnum + num; y = stoi(fnum); } } catch(out_of_range& oor){ return 0; } if(x==0){ return 0; } else if (x<0){ return -y; } else { return y; } } }; int main(){ Solution mine; cout << mine.reverse(-2147483648); }
[...] when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0. That number is "tricky" because it's equal to std::numeric_limits<int>::min() in your environment and given a two's complement representation of type int, it happens that std::abs(-2147483648) == -2147483648. Next in your (contrived, I must say, there's no need to use a string here) code, the line num = to_string(r); would result in num = "-8", so that the loop would compose a string like "-8-4-6-3-8-4-7-4-1-2". When applyed to strings like that, stoi doesn't throw an exception, it just stops parsing (you would have noticed it by passing and inspecting its other parameters). If you want to check if the result is outside the range of an int, you could use locally a wider type (e.g. long long) and check the boundaries after the calculations or keep using int, but compare all the intermediate values with the limits before any calculation.
69,451,793
69,452,137
Explicit template instantiation example
I am currently reading a book and it has the following example: //ch4_4_class_template_explicit.cpp #include <iostream> using namespace std; template < typename T > //line A struct A { A(T init): val(init) {} virtual T foo(); T val; }; //line B //line C template < class T > //T in this line is template parameter T A < T > ::foo() { //the 1st T refers to function return type, //the T in <> specifies that this function's template //parameter is also the class template parameter return val; } //line D extern template struct A < int > ; //line E #if 0 //line F int A < int > ::foo() { return val + 1; } #endif //line G int main(void) { A < double > x(5); A < int > y(5); cout << "fD=" << x.foo() << ",fI=" << y.foo() << endl; return 0; //output: fD=5,fI=6 } Can someone explain to me what the line extern template struct A < int > ; does and why the second definition for foo()? I understand what explicit template instantiation is and why it is sometimes useful, but the use of extern is not really clear to me. The book has the following explanation for this line: Using the extern keyword prevents implicit instantiations of that function template (see the next section for more details). So extern prevents us from doing the following?: auto obj = A<int>; The second definition then negates the extern? I really can't understand this example. Edit 1: added commented code. Edit 2: I am almost sure that my understanding is correct. But thanks for answering. Explanation from the book: In the preceding code block, we defined a class template between lines A and B, and then we implemented its member function, foo(), from lines C to line D. Next, we explicitly instantiated it for the int type at line E. Since the code block between lines F and line G is commented out (which means that there is no corresponding definition of foo() for this explicit int type instantiation), we have a linkage error. To fix this, we need to replace #if 0 with #if 1 at line F.
Maybe this help you to unsderstand. From the C++ 20 (13.9.2 Explicit instantiation) 2 The syntax for explicit instantiation is: explicit-instantiation: externopt template declaration There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An explicit instantiation declaration begins with the extern keyword. So this line extern template struct A < int > ; is an explicit instantiation declaration of the class specialization struct A<int>.
69,452,280
69,452,781
Win32 unicode swprintf_s call generates buffer overrun warning
I'm writing a small application to target Win32 using C++. The compiler is set to support unicode and I'm compiling in x64 mode. I'm using Visual Studio 2019. Everytime I call swprintf_s, like below: wchar_t buff[500] = { 0 }; swprintf_s(buff, sizeof(buff), L"Could not free DLL handle: 0x%X\n", GetLastError()); OutputDebugString(buff); ...I receive the following C6386 compiler warning: C6386: Buffer overrun while writing to 'buff': the writable size is '1000' bytes, but '2000' bytes might be written. As an experiment, if I doubled the size of the buffer... wchar_t buff[1000] = { 0 }; swprintf_s(buff, sizeof(buff), L"Could not free DLL handle: 0x%X\n", GetLastError()); OutputDebugString(buff); ...the ranges within the warning simply shift up in accordance: C6386: Buffer overrun while writing to 'buff': the writable size is '2000' bytes, but '4000' bytes might be written. I'm wondering if someone might be able to help me understand why the above code (when explicitly passing the size of the buffer) generates a buffer overrun warning and, how I might go about fixing this.
As commented by van dench, the second parameter is the number of chars, not the size of the buffer in bytes. Correct code: wchar_t buff[500] = { 0 }; swprintf_s(buff, 500, L"Could not free DLL handle: 0x%X\n", GetLastError()); OutputDebugString(buff);
69,453,193
69,453,307
Remove '+' after the last output
I have a C++ code that calculates change. It takes input, and returns output by how change will be received. I need to remove the + sign after last change output. Is there a way to do this? My code: if (n500 > 0) { cout << n500 << " x 500 + "; } if (n200 > 0) { cout << n200 << " x 200 + "; } if (n100 > 0) { cout << n100 << " x 100 + "; } if (n50 > 0) { cout << n50 << " x 50 + "; } if (n20 > 0) { cout << n20 << " x 20 + "; } if (n10 > 0) { cout << n10 << " x 10 + "; } if (n5 > 0) { cout << n5 << " x 5 + "; } if (n2 > 0) { cout << n2 << " x 2 + "; } if (n1 > 0) { cout << n1 << " x 1 + "; } return 0; }
I would do the other way: put the separator " + " when previous display has already be done: const char* sep = ""; if (n500 > 0) { std::cout << sep << n500 << " x 500"; sep = " + "; } if (n200 > 0) { std::cout << sep << n200 << " x 200"; sep = " + "; } if (n100 > 0) { std::cout << sep << n100 << " x 100 + "; sep = " + "; } if (n50 > 0) { std::cout << sep << n50 << " x 50 + "; sep = " + "; } if (n20 > 0) { std::cout << sep << n20 << " x 20 + "; sep = " + "; } if (n10 > 0) { std::cout << sep << n10 << " x 10 + "; sep = " + "; } if (n5 > 0) { std::cout << sep << n5 << " x 5 + "; sep = " + "; } if (n2 > 0) { std::cout << sep << n2 << " x 2 + "; sep = " + "; } if (n1 > 0) { std::cout << sep << n1 << " x 1 + "; sep = " + "; } BTW, you might probably use loop instead: const int ns[9] = { n500, n200, n100, n50, n20, n10, n5, n2, n1 }; const char* texts[9] = { " x 500", " x 200", " x 100", " x 50", " x 20", " x 10", " x 5", " x 2", " x 1" }; const char* sep = ""; for (int i = 0; i != 9; ++i) { if (ns[i] > 0) { std::cout << sep << ns[i] << texts[i]; sep = " + "; } }
69,453,247
69,453,490
How to properly call destructors when exiting within a thread?
Context: I'm working with with a project composed simplistically of three layers, an application layer, an interface layer, and a middleware layer. The interface layer provides additional functionality on top of the middleware layer, and is responsible for managing threads running the middleware application. My issue is that to exit the program, interrupt signals are used, the handler for these signals is defined at the lowest, middleware layer. When an interrupt signal is sent, the handler eventually calls exit(0), which results in an interface-layer destructor being called by the same thread calling exit(0). Within this destructor, middlewareAppThread.join()is called, resulting in a deadlock as the thread is trying to join itself. This is a simplified representation, sorry if it's messy: What confuses me is seeing how the Proxy object is referenced in the global namespace, I thought the destructor would be called by the main thread, but when debugging it's apparent the destructor is called by middlewareAppThread. The solution I've thought of so far is to remove the signal handler from the middleware stack, and create one in the app/interface layer. This is a little problematic as the middleware is third-party. Is there a way to keep the exit(0) call at the lowest level, with the destructors being called from the main thread? Or: What could be causing the destructor to be called from the middlewareAppThread?
It is the thread that calls exit that does all of the cleanup. Several cleanup steps are performed: The destructors of objects with thread local storage duration that are associated with the current thread, the destructors of objects with static storage duration, and the functions registered with std::atexit are executed concurrently (emphasis added) I thought the destructor would be called by the main thread What makes you think that? C++ does not associate objects with threads. Even a thread local object can be interacted with on another thread through a pointer or reference. Is there a way to keep the exit(0) call at the lowest level Yes, don't have static duration std::thread (sub-)objects, especially those which can call exit. with the destructors being called from the main thread? Co-ordinate such that the main thread is the one to call exit. Or just return from main
69,453,363
69,454,312
C++11 Simple Producer Consumer Multithreading
I am trying to teach myself multithreading and I followed this tutorial here: https://www.classes.cs.uchicago.edu/archive/2013/spring/12300-1/labs/lab6/ If you scroll all the way to the bottom there is a sample snippet of a producer-consumer and it asks us to solve the race conditions found in this code: #include <iostream> #include <thread> #include <condition_variable> #include <mutex> #include <chrono> #include <queue> using namespace std; int main() { int c = 0; bool done = false; queue<int> goods; thread producer([&]() { for (int i = 0; i < 500; ++i) { goods.push(i); c++; } done = true; }); thread consumer([&]() { while (!done) { while (!goods.empty()) { goods.pop(); c--; } } }); producer.join(); consumer.join(); cout << "Net: " << c << endl; } The Net value at the end should be 0, here is my attempt at it: #include <iostream> #include <thread> #include <condition_variable> #include <mutex> #include <chrono> #include <queue> #include <atomic> using namespace std; int main() { int c = 0; bool done = false; queue<int> goods; mutex mtx; condition_variable cond_var; // thread to produce 500 elements thread producer([&]() { for (int i = 0; i < 500; ++i) { // lock critical secion unique_lock<mutex> lock(mtx); goods.push(i); c++; lock.unlock(); // notify consumer that data has been produced cond_var.notify_one(); } // notify the consumer that it is done done = true; cond_var.notify_one(); }); // thread to consume all elements thread consumer([&]() { while (!done) { unique_lock<mutex> lock(mtx); while (!goods.empty()) { goods.pop(); c--; } // unlocks lock and wait until something in producer gets put cond_var.wait(lock); } }); producer.join(); consumer.join(); cout << "Net: " << c << endl; } I feel like I am fundamentally missing something. I believe the biggest problem I am having is in the consumer with the cond_var.wait() because if the producer sets "done" to true then the consumer won't go back into the while(!goods.empty()). I am not sure how to fix it though. Any hints, explanations or even different approaches would be appreciated!
Producer: thread producer([&]() { for (int i = 0; i < 500; ++i) { { // Just have a lock while interacting with shared items. unique_lock<mutex> lock(mtx); goods.push(i); c++; } cond_var.notify_one(); } // Lock to update shared state. unique_lock<mutex> lock(mtx); done = true; cond_var.notify_one(); }); Consumer thread consumer([&]() { // This loop exits when // done => true // AND goods.empty() => true // Acquire lock before checking shared state. unique_lock<mutex> lock(mtx); while (!(done && goods.empty())) { // Wait until there is something in the queue to processes // releasing lock while we wait. // Break out if we are done or goods is not empty. cond_var.wait(lock, [&](){return done || !goods.empty();}); // You now have the lock again, so modify shared state is allowed // But there is a possibility of no goods being available. // So let's check before doing work. if (!goods.empty()) { goods.pop(); c--; } } }); Alternatively if we are simply solving for race condition. We can simply check on the state of done and make sure no other variables have interactions. Producer: thread producer([&]() { // The consumer is not allowed to touch goods // until you are finished. So just use with // no locks. for (int i = 0; i < 500; ++i) { goods.push(i); c++; } // Lock to update shared state. // Tell consumer we are ready for processing. unique_lock<mutex> lock(mtx); done = true; cond_var.notify_one(); }); Consumer thread consumer([&]() { // Acquire lock before checking shared state. unique_lock<mutex> lock(mtx); cond_var.wait(lock, [&](){return done;}); // We now know the consumer has finished all updates. // So we can simply loop over the goods and processes them while (!goods.empty()) { goods.pop(); c--; } });
69,453,511
69,493,622
Can't QOverload private signal, using Qt docs example
Here in the Qt documentation is written: Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user. Note: Signal activated is overloaded in this class. To connect to this signal by using the function pointer syntax, Qt provides a convenient helper for obtaining the function pointer as shown in this example: connect(socketNotifier, QOverload<QSocketDescriptor, QSocketNotifier::Type>::of(&QSocketNotifier::activated), [=](QSocketDescriptor socket, QSocketNotifier::Type type){ /* ... */ }); When I use it, I'm getting this issue: error: no matching function for call to 'of' /usr/include/qt5/QtCore/qglobal.h:1224: candidate template ignored: could not match 'type-parameter-0-0 (QSocketDescriptor, QSocketNotifier::Type) const' against 'void (QSocketDescriptor, QSocketNotifier::Type, QSocketNotifier::QPrivateSignal)' /usr/include/qt5/QtCore/qglobal.h:1212: candidate template ignored: failed template argument deduction /usr/include/qt5/QtCore/qglobal.h:1241: candidate template ignored: could not match 'R (*)(QSocketDescriptor, QSocketNotifier::Type)' against 'void (QSocketNotifier::*)(QSocketDescriptor, QSocketNotifier::Type, QSocketNotifier::QPrivateSignal)' I just copy-pasted the example and have <QSocketDescriptor> and <QSocketNotifier> headers both included. What am I missing?
If you can use C++14 you can use a helper function: template<class T> auto privateOverload(void ( QSocketNotifier::* s)( QSocketDescriptor,QSocketNotifier::Type,T ) ){return s;} and then you can use QObject::connect(socketNotifier, privateOverload(&QSocketNotifier::activated),/*...*/); If you can use C++20 you can also use a lambda directly in the connect statement: QObject::connect(socketNotifier, []<class T>(void ( QSocketNotifier::* s)( QSocketDescriptor,QSocketNotifier::Type,T ) ){return s;}(&QSocketNotifier::activated),/*...*/);
69,453,770
69,454,188
How to invoke cmd.exe /c cls from within VS Code tasks.json?
I have a simple HelloWorld.cpp file and I want to run it with the following steps, each is run one after the other as follows. Compile Clear Integrated Terminal Run the produced executable. Unfortunately I fails to setup the second step (clearing the console window). What is the correct setup? { "version": "2.0.0", "tasks": [ { "label": "COMPILE", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/nologo", "/Fe:", "${fileBasenameNoExtension}.exe", "${file}", "/std:c++latest" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$msCompile" ] }, { "label": "CLEAN", "command": "cmd.exe /c cls", "dependsOn": "COMPILE" }, { "label": "RUN", "command": "${fileBasenameNoExtension}.exe", "dependsOn": "CLEAN", "options": { "cwd": "${fileDirname}" }, "group": { "kind": "build", "isDefault": true } } ] }
Aha. I found the solution: Add "type": "shell" to the CLEAN step as follows. { "type": "shell", "label": "CLEAN", "command": "cls", "dependsOn": "COMPILE" } The complete tasks.json. { "version": "2.0.0", "tasks": [ { "label": "COMPILE", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/nologo", "/Fe:", "${fileBasenameNoExtension}.exe", "${file}", "/std:c++latest" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$msCompile" ] }, { "type": "shell", "label": "CLEAN", "command": "cls", "dependsOn": "COMPILE" }, { "label": "RUN", "command": "${fileBasenameNoExtension}.exe", "dependsOn": "CLEAN", "options": { "cwd": "${fileDirname}" }, "group": { "kind": "build", "isDefault": true } } ] }
69,453,972
69,453,973
Get all non-zero values of a dense Eigen::Matrix object
Asuming you have a dynamic size Eigen::Matrix object and want to do some computation on only non-zero values, how can you get a vector or list representation of all non-zero values? Matrix3f m; m << 1, 0, 0, 0, 5, 6, 0, 0, 9; VectorXf v = get_non_zero_values(m); cout << v; should give you 1 5 6 9 How can this be done with Eigen (most efficiently)?
After a lot of research in the web and inspired by this stackoverflow post I came up with my own solution template <typename T> Eigen::Matrix<T, Eigen::Dynamic, 1> get_non_zeros(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& _input) { Eigen::Matrix<T, Eigen::Dynamic, 1> reduced(Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>>(_input.data(), _input.size())); Eigen::Matrix<bool, Eigen::Dynamic, 1> empty = (reduced.array() == 0).rowwise().all(); size_t last = reduced.rows() - 1; for ( size_t i = 0; i < last + 1;) { if ( empty(i) ) { reduced.row(i).swap(reduced.row(last)); empty.segment<1>(i).swap(empty.segment<1>(last)); --last; } else { ++i; } } reduced.conservativeResize(last + 1, reduced.cols()); return reduced; }
69,454,584
69,454,726
How to read from file in c++ and insert data from file into vector thats is type of an class?
Like the title says I need to insert data from file into vector that is a type of class I created. Here is my code: #include <iostream> #include <fstream> #include "Film.h" #include "Comedy.h" #include <string> #include <vector> using namespace std; Comedy k; Film f; int main() { vector <Comedy> comedy; ifstream Comedies("Comedy.txt", ios::in); int number = 0; string line; while (getline(Comedies, line)) { br++; komedija.push_back(line); // this is where I get the error } This is Comedy class: #pragma once #include "Film.h" #include "Actor.h" #include <vector> #include <string> #include <fstream> using namespace std; enum Type2 {black = 1, romantic, child}; class Comedy : public Film { private: vector<Actor>actors; Type2 typeComedy; public: void setActors(); vector<Actors>& getActors(); void setType(); Type2 getType(); void insert(); }; Anyone know what is the issue, I assume it is because the line variable is a type of string, and I am trying to insert into a vector that is not type of string, how do I then insert data from file into a vector that is not string? This is a Film class: #pragma once class Film { private: char name[25]; int timeOfDuration; char startMovieTime[7]; public: Film(); void setName(); char* getName(); void setTimeOfDuration(); int getTimeOfDuratiion(); void setStartMovieTime(); char* getStartMovieTime(); ~Film() {}; };
Assuming Film has a constructor that takes a std::string, I suggest adding it to the derived classes: Example with Comedy: class Comedy : public Film { public: using Film::Film; // add the `Film` constructor(s) // ... }; Then adding a new Comedy can be done using std::vector::emplace_back: komedija.emplace_back(line); Demo If you for some reason want to store the film name in a char[], you can still use a constructor that accepts a std::string and stores it in your char[]. Example: #include <algorithm> // std::copy_n, std::min class Film { private: char name[25]; public: Film() : name{} {} // initialize name // added constructor: Film(const std::string& Name) : Film() { std::copy_n(Name.c_str(), std::min(sizeof name - 1, Name.size()), name); } }; Note: Unless Comedy has some special member variables/functions I suggest adding a category member to Film instead of inheriting from Film.
69,454,621
69,454,787
Why does x have an unexpected value after trying to initialize it with x, y = a, b?
#include <iostream> int main() { int x, y; x, y = 10, 20; std::cout << x; return 0; } I expect 10 as output but 16 is coming. What's the reason? Can someone explain that behavior in c++ please?
x, y = 10, 20; is interpreted as (x), (y = 10), (20);. The three expressions are just executed sequentally. x and 20 do nothing, and y = 10 does what it says on the tin. x remains uninitialzied, and reading it is undefined behavior. There is a way to do what you want, but it's a part of the standard library (#include <tuple>), not built into the language. It's also quite verbose, so it might be a better idea to just assign to each variable separately. If you want to assign to existing variables: int x, y; std::tie(x, y) = std::forward_as_tuple(10, 20); Or, if you want to create new variables: auto [x, y] = std::forward_as_tuple(10, 20); (the auto [...] syntax is called a structured binding, and is available since C++17) If the rhs are variables (lvalues), you can use less verbose std::tie instead of std::forward_as_tuple. In some cases you need std::tuple instead of std::forward_as_tuple, it will copy/move the rhs before assigning them. This is required e.g. when returning the tuple from a function, or if you want to do std::tie(x, y) = std::tuple(y, x);. You can also use std::tuple instead of std::forward_as_tuple for brevity, is the rhs is inexpensive to copy/move.
69,454,875
69,455,048
C++ how to input by word and count how much word i input
i did try using this program #include <iostream> using namespace std; int main() { string x; string a = "black"; string b = "red"; string c = "white"; int e, f, g = 0; //e = black; f = red; h = white; cout << "input car color :"; cin >> x; if (x == a) { cout << "continue input car color?" << endl; } else if (x == b) { cout << "continue input car color?" << endl; } return 0; } but i dont know to make the last one that show how much color did user input this is the result for my program, how do i make it? and its in c++ btw input car color: black //black,red,white=user input continue input car color? (y/n)? y input car color: black continue input car color? (y/n)? y input car color: black continue input car color? (y/n)? y input car color: red continue input car color? (y/n)? y input car color: white continue input car color? (y/n)? n detail car color black 3 car red 1 car white 1 car
You need to use a loop to continue prompting the user for more inputs. And you need to increment your integers on each matching input you detect. Try something like this: #include <iostream> #include <iomanip> using namespace std; int main() { string input; int num_black = 0, num_red = 0, num_white = 0; do { cout << "input car color :"; cin >> input; if (input == "black") { ++num_black; } else if (input == "red") { ++num_red; } else if (input == "white") { ++num_white; } cout << "continue input car color?" << endl; cin >> input; } while (input == "y"); cout << endl; cout << "detail car color" << endl; cout << setw(11) << left << "black" << num_black << " car" << (num_black != 1 ? "s" : "") << endl; cout << setw(11) << left << "red" << num_red << " car" << (num_red != 1 ? "s" : "") << endl; cout << setw(11) << left << "white" << num_white << " car" << (num_white != 1 ? "s" : "") << endl; return 0; } Online Demo
69,455,254
69,691,399
Writing a unit test in gtest for a function returning an nlohmann::json object
This is my function that I would like to create a test for: static nlohmann::json parse_json(const std::string& file_path) { std::ifstream i(file_path); nlohmann::json j = nlohmann::json::parse(i); return j; } I understand this type of test: TEST(FactorialTest, HandlesZeroInput) { EXPECT_EQ(Factorial(0), 1); } But when my function is returning an object I'm not exactly sure how to accomplish this. Is this where mocking comes into play? Where I would need to write something like this: class fakeJsonObject { public: MOCK_METHOD(nlohmann::json, parse_json, std::string& file_path); }; Then create a test with my mocked object and compare it to an object created from my parse_json function?
General answer : a good unit test follow the rule AAA Arrange : place where you prepare things that will be tested Act : function call under test Assert : Assert that the function call gives you the right result. So in your case you have to prepare / or better generate a file containing json data. (Arrange). Call the function. (Act) Assert you got a nlhohmann::json object which is related to the json data contained in the file.(Assert)
69,455,319
69,456,438
how to detect atomic types using enable_if
Is it possible to detect my atomic type is being detected a if a type is atomic using enable_if ? Currently, my atomic type is anyway to distinguish being detected as a class type is there anyway to distinguish it as an atomic type
You don't even need enable_if in this case, specialization is enough: // By default, types are not atomic, template<typename T> auto constexpr is_atomic = false; // but std::atomic<T> types are, template<typename T> auto constexpr is_atomic<std::atomic<T>> = true; // as well as std::atomic_flag. template<> auto constexpr is_atomic<std::atomic_flag> = true; // Tests: static_assert(!is_atomic<int>); static_assert(is_atomic<std::atomic<int>>); static_assert(is_atomic<std::atomic_flag>); If you want to branch your compile-time logic based on this attribute, you can use C++17 if constexpr: template<typename T> auto foo(T& t) { if constexpr (is_atomic<T>) /* T is atomic */; else /* T is not atomic */; }