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
72,754,258
72,754,312
reinterpret_cast usage to manipulate bytes
I was reading here how to use the byteswap function. I don't understand why bit_cast is actually needed instead of using reinterpret_cast to char*. What I understand is that using this cast we are not violating the strict aliasing rule. I read that the second version below could be wrong because we access to unaligned memory. It could but at this point I'm a bit confused because if the access is UB due to unaligned memory, when is it possible to manipulate bytes with reinterpret_cast? According to the standard the cast should allow to access (read/write) the memory. template<std::integral T> constexpr T byteswap(T value) noexcept { static_assert(std::has_unique_object_representations_v<T>, "T may not have padding bits"); auto value_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value); std::ranges::reverse(value_representation); return std::bit_cast<T>(value_representation); } template<std::integral T> void byteswap(T& value) noexcept { static_assert(std::has_unique_object_representations_v<T>, "T may not have padding bits"); char* value_representation = reinterpret_cast<char*>(value); std::reverse(value_representation, value_representation+sizeof(T)); }
The primary reason is that reinterpret_cast can not be used in constant expression evaluation, while std::bit_cast can. And std::byteswap is specified to be constexpr. If you added constexpr to the declaration in your implementation, it would be ill-formed, no diagnostic required, because there is no specialization of it that could be called as subexpression of a constant expression. Without the constexpr it is not ill-formed, but cannot be called as subexpression of a constant expression, which std::byteswap is supposed to allow. Furthermore, there is a defect in the standard: The standard technically does not allow doing pointer arithmetic on the reinterpret_cast<char*>(value) pointer (and also doesn't really specify a meaning for reading and writing through such a pointer). The intention is that the char* pointer should be a pointer into the object representation of the object, considered as an array of characters. But currently the standard just says that the reinterpret_cast<char*>(value) pointer still points to the original object, not its object representation. See P1839 for a paper proposing to correct the specification to be more in line with the usual assumptions. The implementation from cppreference is also making an assumption that might not be guaranteed to be true: Whether std::array<std::byte, sizeof(T)> is guaranteed to have the same size as T. Of course that should hold in practice and std::bit_cast will fail to compile if it doesn't. If you want to read some discussion on whether or not it is guaranteed in theory, see the questions std::bit_cast with std::array, Is the size of std::array defined by standard and What is the sizeof std::array<char, N>?
72,754,339
72,754,358
static variable in variadic template function
I want to use a static variable in a function which accept variadic template to accept variable number of arguments. Since the function gets called recursively I expect the value of i to be incremented for each call. But the static variable is incremented only once rather than for each function call. Here is the program which demonstrate this behavior. #include <iostream> #include <string> using namespace std::string_literals; void printArgs() {} template<typename T, typename... Ts> void printArgs(T first, Ts... rest) { static int32_t i{}; ++i; std::cout << i << ". " << first << std::endl; printArgs(rest...); } int main() { printArgs("hello cpp"s, "c++11", 'x', 1234, 0xab45, 0b010101); } Output 1. hello cpp 1. c++11 1. x 1. 1234 1. 43845 1. 21 If I make the static variable global by moving it outside the function definition, it gets incremented for each function invocation. static int32_t i{}; template<typename T, typename... Ts> void printArgs(T first, Ts... rest) { ++i; std::cout << i << ". " << first << std::endl; printArgs(rest...); } output 1. hello cpp 2. c++11 3. x 4. 1234 5. 43845 6. 21 How the variadic templates function behave in this scenario? Does the compiler create a separate function for each function invocation?
Each specialization of the function gets its own copy of the static variable. Does the compiler create a separate function for each function invocation? Rather, for each used set of template arguments.
72,754,623
72,759,723
How to benchmark fmt::format API on https://quick-bench.com
I am trying to understand and benchmark fmt::format API ( https://fmt.dev/latest/api.html ). I wrote a simple test in compiler explorer i.e, https://godbolt.org/z/fMcf3nczE. #include <benchmark/benchmark.h> #include <fmt/core.h> static void BM_format(benchmark::State& state) { // Perform setup here for (auto _ : state) { std::string s = fmt::format( "{}", "testing fmt::format in benchmark"); } } // Register the function as a benchmark BENCHMARK(BM_format); // Run the benchmark BENCHMARK_MAIN(); Then, I launched quick-bench from compile explorer. In quick-bench, it gives an error as Error or timeout bench-file.cpp:2:10: fatal error: fmt/core.h: No such file or directory 2 | #include <fmt/core.h> | ^~~~~~~~~~~~ compilation terminated. Is the c++ fmt library supported in quick-bench so that it compiles and executes? if not, any alternative.
Unfortunately, quick-bench does not support external libraries which require separate compilation (as fmt does). As a side note, it does not support the inclusion of header-only libraries via URLs, either. I would have said that in this specific case you could use C++20 std::format instead, if you are not tied to fmt lib specifically. But unfortunately, neither clang 14 nor gcc 11 (or rather, libc++ and libstdc++) have implemented it yet. So I fear what you ask is simply impossible right now. You need to benchmark on your own computer.
72,754,634
72,756,396
Inheriting singals from child widgets
I created a Custom widget in QT, i use it in my main program but i cant use the signals from a QLineEdit, how can i do it?, this is mi code: search = new Search_browser(ui->widget); connect(search, SIGNAL(returnPressed()), this, SLOT(set_page())); Search_browser has a QLineEdit, that is why im trying to use returnPressed() signal, this should call a function in my MainWaindow to set a page but i get this error: QObject::connect: No such signal Search_browser::returnPressed() Header file of the custom widget: class Search_browser : public QWidget { Q_OBJECT public: Search_browser(QWidget *parent = nullptr); ~Search_browser(); QString get_url(); public slots: void replyFinished(QNetworkReply *reply); void get_request(); private: QLineEdit *lineEdit; QCompleter *completer; QStringList wordList; }; i think that i have to implement myself the signal but i dont know how.
You aggregate QLineEdit in Search_browser so now it's incapsulated (private), to make it accessable from outside world (from MainWindow) you can do one of two things: add accessor to it and connect to returned value. class Search_browser : public QWidget { ... QLineEdit *getLineEdit() {return lineEdit;} }; connect(search->getLineEdit(), SIGNAL(returnPressed()), this, SLOT(set_page())); Or add signal to Search_browser and forward it. class Search_browser : public QWidget { signals: void returnPressed(); }; Search_browser::Search_browser() { ... connect(lineEdit,SIGNAL(returnPressed()),this,SIGNAL(returnPressed())); }
72,754,755
72,755,095
Signed int not being converted into unsigned int
I am reading the book C++ Primer, by Lippman and Lajoie. On page 65 they say: If we use both unsigned and int values in an arithmetic expression, the int value ordinarily is converted to unsigned. If I try out their example, things work as expected, that is: unsigned u = 10; int i = -42; std::cout << u + i << std::endl; // if 32-bit ints, prints 4294967264 However, if I change i to -10, the result I get is 0 instead of the expected 4294967296, with 32-bit ints: unsigned u = 10; int i = -10; std::cout << u + i << std::endl; // prins 0 instead of 4294967296. Why? Shouldn't this expression print 10 + (-10 mod 2^32) ?
Both unsigned int and int take up 32 bits in the memory, let's consider their bit representations: unsigned int u = 10; 00000000000000000000000000001010 int i = -42; 11111111111111111111111111010110 u + i: 11111111111111111111111111100000 If we treat 11111111111111111111111111100000 as a signed number (int), then it is -32: If we treat it as an unsigned number (unsigned), then it is 4294967264: The difference lies in the highest bit, whether it represents -2^31, or +2^31. Now let's take a look at (10u) + (-10): unsigned int u = 10; 00000000000000000000000000001010 int i = -10; 11111111111111111111111111110110 u + i: (1)00000000000000000000000000000000 Since u + i will be over 32 bits limit, the highest bit 1 will be discarded. Since the remaining 32 bits are all zero, the result will be 0. Similarly, if i = -9, then the result will be 1.
72,755,246
72,772,839
ASN.1 REAL binary base 2 encoding mantissa normalization
I am trying to DER encode REAL data in binary 2 base form using C++. I calculate the mantissa and exponent with the following algorithm. sample data = 32.3125 using C++ std::frexp function, extract double mantissa and int exponent. mantissa 0.5048828125 exponent 6 Convert the mantissa to integer by multiplying by 2 and decreasing exponent by 1 till integer mantissa is got. mantissa 517 exponent -4 Finally the data is encoded as 09 04 80(binary 2 base) FC(exp) 02 05(mantissa) Is this encoding correct? In the standard(X.690-0207), it talks about mantissa representation in a different form. 8.5.6 When binary encoding is used (bit 8 = 1), then if the mantissa M is non-zero, it shall be represented by a sign S, a positive integer value N and a binary scaling factor F, such that: M = S × N × 2F In the Canonical Encoding Rules and the Distinguished Encoding Rules normalization is specified and the mantissa (unless it is 0) needs to be repeatedly shifted until the least significant bit is a 1. Is this necessary to convert the mantissa in this format and encode N and F, or is it ok to keep the F as '0' as in my example?
Your encoding is correct. Note that the requirements for DER are covered in X.690 11.3, and you have met them (you are using base 2, your mantissa is odd, and F = 0). F != 0 is only ever needed when encoding using base 8 or 16.
72,755,304
72,755,388
Function which copies an array of integers from one array to another using pointers in C++
The purpose of the Copy function in the following code is to copy an array of integers from one array to another using C++ but the output seems wrong. What could be the problem here? #include <iostream> using namespace std; void Copy(int old_array[],int new_array[],int length) { int *ptr1 = old_array; int *ptr2 = new_array; int i = 0; for(int i=0 ; i<length ; i++) { *(ptr2++) = *(ptr1++); } for (int i = 0; i <2; i++) { cout<<*(ptr2 + i)<<endl; } } int main() { int a[2]={0,1}; int b[2]; Copy(a,b,2); } This is the output:
ptr2 is one past the end of the array when your print loop runs. Try this: void Copy(int old_array[], int new_array[], int length) { int* ptr1 = old_array; int* ptr2 = new_array; int i = 0; for (int i = 0; i < length; i++) { *(ptr2++) = *(ptr1++); } ptr2 = new_array; for (int i = 0; i < 2; i++) { cout << *(ptr2 + i) << endl; } }
72,755,568
72,755,612
Need a better solution to a hackerrank challenge
So I am new to competitive programming and I have been trying to solve this challenge for the past hour or so. I'm pretty sure my solution is overly complicated so can someone give me a better solution please? My code is pretty bad so if you can pls provide me with some feedback. The challenge You are given the day of the week for the first day of a month (M) (e.g. 1-Monday, 2-Tuesday, 3- Wednesday ...) and a date (D). You need to find the day of the week for the date given. Constraints: 1<=M<=7 1<=D<=31 e.g. Input: 1 30 Output: 2 My (bad) code: #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int find_answer_for_more_than_7_days(int start,int day){ cout<<day%7 + start - 1; return 0; } int find_answer_for_less_than_7_days(int start,int day){ if ((start + day - 1)>7) cout<<start+day - 8; else cout<< start + day - 1; return 0; } int find_answer(int start, int day){ if (day>7) find_answer_for_more_than_7_days(start, day); else if (day<7) find_answer_for_less_than_7_days(start,day); return 0; } int main() { int m,d; cin>>m>>d; if (d!=1){ if (d%7 == 0){ if (m != 1) cout<<m-1; else cout<<7; } else{ if (m == 1){ if (d>7) cout<<d%7; else if (d<7) cout<< d; } else if (m == 7){ if (d > 7) cout<<d - 7*(d/7) - 1; else if (d< 7) cout<< d - 1; } else{ find_answer(m,d); } } } else cout<< m; return 0; }
For a start it would help if the code would actually be correct: int find_answer_for_more_than_7_days(int start,int day){ cout<<day%7 + start - 1; return 0; } start = 7 and day = 6 produces 12. All those special cases in main are unlikely and costing you far more time then simply doing the general math. Just do cout << ((m + d - 2) % 7) + 1
72,755,744
72,756,072
Use of std::uninitialized_copy to an initialized memory
If std::uninitialized_copy is used to an initialized memory, does this use cause a memory leak or an undefined behavior? For example: std::vector<std::string> u = {"1", "2", "3"}; std::vector<std::string> v = {"4", "5", "6"}; // What happens to the original elements in v? std::uninitialized_copy(u.begin(), u.end(), v.begin());
Base on specialized.algorithms.general and uninitialized.copy I don't find any formal requirements that the destination range must be uninitialized. As such, we can consider the effect of std::uninitialized_copy which is defined as equivalent to the follow (excluding the implied exception safety boilerplate code) : for (; first != last; ++result, (void) ++first) ::new (voidify(*result)) typename iterator_traits<NoThrowForwardIterator>::value_type(*first); We can conclude that std::uninitialized_copy does not call any destructor or otherwise cares about what was previously located in the destination range. It simply overwrites it, assuming it is uninitialized. To figure out what this means in terms of correctness, we can refer to basic.life A program may end the lifetime of an object of class type without invoking the destructor, by reusing or releasing the storage as described above. In this case, the destructor is not implicitly invoked and any program that depends on the side effects produced by the destructor has undefined behavior. This however uses the loosely defined notion of "any program that depends on the side effects of". What does it mean to "depend on the side effects of"? If your question was about overwriting vectors of char or int there would be no problem, as these are not class types and do not have destructors so there can be no side effects to depend on. However std::string's destructor may have the effect of releasing resources. std::basic_string may have addition, more directly observable side effects if a user defined allocator is used. Note that in the case of a range containing non-class type elements std::uninitialized_copy is not required. These elements allow for vacuous initialization and simply copying them to uninitialized storage with std::copy is fine. Since I don't believe it is possible for the behavior of a program to depend on the release of std::string's resources, I believe the code above is correct in terms of having well defined behavior, though it may leak resources. An argument could be made that the behavior might rely on std::bad_alloc eventually being thrown, but std::string isn't strictly speaking required to dynamically allocate. However, if the type of element used had side effects which could influence the behavior, and the program depended on those effects, then it would be UB. In general, while it may be well defined in some cases, the code shown violates assumptions on which RAII is based, which is a fundamental feature most real programs depend on. On these grounds std::uninitialized_copy should not be used to copy to a range which already contains objects of class type.
72,755,784
72,756,073
Visual Studio 2022: MSB8036 since upgrading to VS2022
I've been unable to build C++ projects since upgrading to VS2022. No matter what I do, it cannot programmatically find the Windows SDK files it needs, always claiming MSB8036 (the extremely generic "it can't find the Windows SDK" error). To be absolutely clear, the version of the Windows SDK that it is looking for (10.0.19041.0) is the one that is installed. At various times, it has been installed using both the Visual Studio installer and the standalone installer (the latter of which apparently fixed this issue for some people). I had even tried installing an older SDK several times, which still failed, even when solutions were specifically retargeted. EDIT: To be even more clear, I've also tried simple solutions like the one outlined here. So far, I have tried: uninstalling and reinstalling (after a recent reinstall, the VS IDE won't load anymore, so I'm stuck with Build Tools) installing a different edition (Build Tools vs Community) running sfc /scannow (it found and fixed some errors, but none fixed the issue with MSBuild) removing the symlinks I had and allowing Visual Studio to install directly to my system drive (to be clear, the symlinks did not cause issues with VS2019, but I was unsure whether VS2022 had issues with them) running InstallCleanup.exe -f installing VS2019 again (despite working before, it won't anymore) checking the environment variables manually (everything points to where the files are located) checking the registry manually (couldn't find anything, not sure what I'd be looking for) I was able to get it to pass the check for the Windows SDK by hardcoding the (x64) paths (which were literally the same) into the Microsoft.Cpp.WindowsSDK.targets file, but it would then fail to find windows.h at build time (this is also untenable for non-x64 targets). I am out of ideas. Has anyone else had this issue? Are there any fixes that don't involve reinstalling Windows?
@john's comment here provided the answer. I then was able to grab the proper SDKManifest.xml from here, which is basically the same as the version given in the video with the Windows SDK version swapped out.
72,756,420
72,796,737
Winui 3 winrt C++ reference counting
Using WinUI 3, Winrt C++ in the following code: Is myRectangle reference counted? Or is it copied? namespace winrt::MyProject::implementation{ void MyProjectClass::fnc(){ winrt::Microsoft::UI::Xaml::Controls::Canvas myCanvas = CanvasElementFromXAML(); winrt::Microsoft::UI::Xaml::Shapes::Rectangle myRectangle; myCanvas.Children.Append(myRectangle); } } I see this type of code in examples. In C++ (without MS extensions) this would lead to a dangling reference/pointer if not copied, since myRectangle is a local var which will go out of scope. myCanvas.Children.Append() receives UIElement const& value void Append(UIElement const& value) here the const reference would communicate that the argument cannot be changed, therefore ref count cannot be modified.
WinRT is COM-based, so the Canvas instance and the Rectangle instance are both COM-objects. So, Append implementation will call AddRef on myRectangle. In this case, there's no specific MS extension involved.
72,756,435
72,756,568
c++ primer plus Partial Specializations question
In the "Partial Specializations" section of chapter 14 of C++ Primer Plus: Without the partial specialization, the second declaration would use the general template, interpreting T as type char *.With the partial specialization, it uses the specialized template, interpreting T as char. The partial specialization feature allows for making a variety of restrictions. For example, you can use the following: // general template template <class T1, class T2, class T3> class Trio{...}; // specialization with T3 set to T2 template <class T1, class T2> class Trio<T1, T2, T2> {...}; // specialization with T3 and T2 set to T1* template class Trio<T1, T1*, T1*> {...}; Given these declarations, the compiler would make the following choices: Trio<int, short, char *> t1; // use general template Trio<int, short> t2; // use Trio<T1, T2, T2> Trio<char, char *, char *> t3; // use Trio<T1, T1*, T1*> But when I try this: template <typename T1, typename T2, typename T3> class Base { public: Base() { cout << "general definition" << endl; } }; template <typename T1, typename T2> class Base<T1, T2, T2> { public: Base() { cout << "T1 and T2 definition" << endl; } }; template <typename T1> class Base<T1, T1, T1> { public: Base() { cout << "T1 definition" << endl; } }; int main() { Base<int, char, double> b1; Base<int, char, char> b2; Base<int, char> b3; Base<int, int, int> b4; Base<int> b5; return 0; } I get errors in Base<int, char> b3 and Base<int> b5: wrong number of template arguments (2, should be 3) wrong number of template arguments (1, should be 3) My question is: When we use partial specializations, if we use a type parameter to initialize another, can we omitting the repetitive part? My compiler parameters: D:\MinGw-x64\mingw64\bin\g++.exe 'c:\Users\33065\Desktop\study\C++ Primer Plus source code\*.cpp', '-o', 'c:\Users\33065\Desktop\study\C++ Primer Plus source code/main.exe', '-std=c++11', '-g', '-m64', '-Wall', '-static-libgcc', '-fexec-charset=GBK', '-D__USE_MINGW_ANSI_STDIO'
A partial specialization will expect as many template arguments as the base template mandates ("base" meaning the unspecialized declaration of your class template, NOT the type named Base). A solution to your problem would be to define the base template as: template <typename T1, typename T2 = T1, typename T3 = T2> class Base { public: Base() { cout << "general defination" << endl; } }; Since specializations can't have defaulted template arguments, this makes the base template trickle down non-defined parameters to the rest of the typelist. Hence you can write things like: Base<T1> b1; // this will be Base<T1, T1, T1> and have each undefined type equate to the previous type. Demo
72,756,636
72,757,110
Eclipse installation issue
It is possible to install Eclipse for Java and C++ in the same time for same Pc? Thanks ☺️ I’m Java Developer but also I need eclipse even for C++ projects. It is that possible ?
You have options: install Eclipse/Java and Eclipse/C++ in different folders on the same computer Install either Eclipse/Java or Eclipse/C++, then further install the plugins for the missing language The first one is trivial as it is just two downloads. For the second, check out https://stackoverflow.com/a/39283723/4222206
72,756,717
72,793,806
How to deal with possible errors that arise from dereferencing a nullptr?
I have a question regarding some guidelines to write better code. Suppose that I have a class like this: class A { private: T *m_data; public: A(T *data) : m_data(data) {} void doSomething() { //accessing m_data } }; Since it's possible to call A constructor passing a nullptr, what is the correct way to handle this problem in optic to be helpful to someone who want to re-use my code ? A comment with a precondition is enough ? //precondition : m_data != nullptr void doSomething() { //accessing m_data } Or is it better to check if m_data==nullptr and throw an exception with an error message giving the possibility to handle it or to let the program abort?
The short answer is always: there is no single correct way, or rule that always applies. For example, suppose your class is the start of a custom iterator definition. Dereferencing default-constructed or end() iterators is usually undefined behaviour, even if they don't represent null values. The non-default constructor could be similar to yours, but since users aren't supposed to call it directly and the behaviour is documented, that's not really a problem. But still, the iterator simply assumes that it's in a valid state and will let you violate these rules. It provides a default constructor (and would therefore avoid having reference members) just to be "regular", which is a convenient and intuitive property. So in that case, it doesn't really matter whether the constructor accepts a pointer or a reference, as long as the class does not do anything surprising with the referenced object, such as destroying it. However, your case may be different and so your design may end up being different. In general your code should be unsurprising and self-documenting as much as possible. What is surprising is of course subjective, but I personally find a class that is not (semi)regular more surprising than one whose default-constructed state is invalid in some sense. You could look at resources like the ISO C++ guidelines, especially interfaces and functions for many well-documented examples, both good and bad ones!
72,756,950
72,756,988
C++ change base's member variable and print it from derived class
The idea is: I've 2 classes, one named Print with only one method called printName, and other class named Human with variable name. I want printName to print whatever the name variable in the Human class is. Example: class Print { public: char name[255]; // name will be overridden from Human class. void print() { std::cout << name << std::endl; } // `this.name` should be from Human class. }; class Human : public Print { public: char name[255]; }; int main() { Human h; h.name = "Somename"; h.print(); // Should outputs: Somename }
One of the solutions: Curiously Recurring Template Pattern 1, 2. template <typename T> class Print { public: char name[255]; void print() { std::cout << static_cast<T*>(this)->name << std::endl; } }; class Human : public Print<Human> { public: char name[255]; }; int main() { Human h; h.name = "Somename"; h.print(); // Outputs: Somename } h.name = "Somename" will not compile.
72,757,374
72,757,730
Problem creating abstract class with no virtual pure methods C++
I want to create a class that is a subclass of two classes that have a common virtual base class. Furthermore, I want this class to be abstract (not be able to create instances of it, but also not needing to call the ctor of the virtual base class). Sample code: #include <cstdio> class CommonBaseClass { public: virtual void DoSomething() = 0; virtual void DoSomethingElse() = 0; CommonBaseClass(int a) {} }; class ClassA : public virtual CommonBaseClass { public: virtual void DoSomething() override { printf("SOMETHING\n"); } ClassA() {}; }; class ClassB : public virtual CommonBaseClass { public: virtual void DoSomethingElse() override { printf("SOMETHING ELSE\n"); } ClassB() {}; }; class TargetClass : //I will never instantiate this class public ClassA, public ClassB { public: TargetClass() : ClassA(), ClassB() {} //I don't want to call the CommonBaseClass ctor }; class SubclassOfTarget : public TargetClass { public: SubclassOfTarget(int a) : CommonBaseClass(a), TargetClass() {} }; int main() { SubclassOfTarget c(15); c.DoSomething(); c.DoSomethingElse(); } If you try to compile this program, you will see that the compiler complains that TargetClass does not call the ctor of CommonBaseClass.
You can use a pure virtual destructor as follows. Even although it is pure virtual, you still need to implement it. You do not need to declare destructors in the derived classes. class TargetClass : //I will never instantiate this class public ClassA, public ClassB { public: TargetClass() : ClassA(), ClassB() {} //I don't want to call the CommonBaseClass ctor virtual ~TargetClass() = 0; }; class SubclassOfTarget : public TargetClass { public: SubclassOfTarget(int a) : CommonBaseClass(a), TargetClass() {} }; TargetClass::~TargetClass() {} int main() { SubclassOfTarget c(15); c.DoSomething(); c.DoSomethingElse(); }
72,757,461
72,757,551
How to run new instance of qt application programmatically
Im trying to clone notepad. Im getting some trouble with the "new window"(ctrl+shift+n) button. is there a way for me to run a new instance of the application programmatically?(that is also not a child of the first instance, meaning if i close the first instance the second instance will continue to live) (I already read about the fact that you cant call main from inside ur program so thats -1 idea) Qt6 Windows 11
I think https://doc.qt.io/qt-6/qprocess.html is what you are looking for. Expecially the startDetached method might do the trick, see: https://doc.qt.io/qt-6/qprocess.html#startDetached-1
72,757,835
72,757,877
Loop compiles but Range does not
OrderProcessor::ProcessRange function in the code below accepts a range as an argument and iterates over it. When I try to call it with a range constructed with std::views::filter it does not compile, but when I copy and paste OrderProcessor::ProcessRange function implementation into the code it compiles: #include <iostream> #include <ranges> #include <vector> namespace data { struct Order { }; } namespace app { template <class R, class Value> concept range_over = std::ranges::range<R> && std::same_as<std::ranges::range_value_t<R>, Value>; class OrderProcessor { public: void Process(const data::Order&) {} template <range_over<data::Order> Range> void ProcessRange(const Range& range) { for (const data::Order& order : range) { Process(order); } } }; } int main() { using namespace app; std::vector<data::Order> sample_orders; auto range = sample_orders | std::views::filter([](const data::Order&) -> bool { return true; }); OrderProcessor processor; processor.ProcessRange(range); //-does not compile //But the following loop compiles: //for (const data::Order& order : range) //{ // processor.Process(order); //} } it also compiles if I remove std::views::filter, what can be the difference? GCC errors: prog.cc: In instantiation of 'void app::OrderProcessor::ProcessRange(const Range&) [with Range = std::ranges::filter_view<std::ranges::ref_view<std::vector<data::Order> >, main()::<lambda(const data::Order&)> >]' : prog.cc : 51 : 27 : required from here prog.cc : 32 : 13 : error : passing 'const std::ranges::filter_view<std::ranges::ref_view<std::vector<data::Order> >, main()::<lambda(const data::Order&)> >' as 'this' argument discards qualifiers[-fpermissive] 32 | for (const data::Order& order : range) | ^ ~~ In file included from prog.cc : 2 : / opt / wandbox / gcc - 11.1.0 / include / c++ / 11.1.0 / ranges : 1307 : 7 : note : in call to 'constexpr std::ranges::filter_view<_Vp, _Pred>::_Iterator std::ranges::filter_view<_Vp, _Pred>::begin() [with _Vp = std::ranges::ref_view<std::vector<data::Order> >; _Pred = main()::<lambda(const data::Order&)>]' 1307 | begin() | ^ ~~~~ prog.cc : 32 : 13 : error : passing 'const std::ranges::filter_view<std::ranges::ref_view<std::vector<data::Order> >, main()::<lambda(const data::Order&)> >' as 'this' argument discards qualifiers[-fpermissive] 32 | for (const data::Order& order : range) | ^ ~~ In file included from prog.cc : 2 : / opt / wandbox / gcc - 11.1.0 / include / c++ / 11.1.0 / ranges : 1321 : 7 : note : in call to 'constexpr auto std::ranges::filter_view<_Vp, _Pred>::end() [with _Vp = std::ranges::ref_view<std::vector<data::Order> >; _Pred = main()::<lambda(const data::Order&)>]' 1321 | end() | ^ ~~
You just need to drop the const on the range argument to ProcessOrder(). A range may change when you iterate it - and apparently that's true for the filter view. Perhaps the library or the compiler could have guessed otherwise, but they don't. Without the const - it compiles: https://godbolt.org/z/MnEczfTjG Also note that if you make the range variable const to begin with, you'll be in trouble with your loop as well.
72,757,928
72,757,980
I'm reading "C++ Templates: The Complete Guide" and there is something that I don't understand
It says: A function generated from a function template is never equivalent to an ordinary function even though they may have the same type and the same name. This has two important consequences for class members: A constructor generated from a constructor template is never a default copy constructor. Firstly, I don't understand how that conclusion came from the first statement. Secondly, when I try to simulate that conclusion, it gives me an error that it cannot be overloaded, so I don't understand the outcome either. Edit: the code I used #include <iostream> template<class T> class entity { private: int x; public: entity(); entity (int const& y):x(y) { printf("non-template"); } entity (T const& y): x(y) { } }; int main() { entity<int> en(5); }
A copy constructor is a non-template constructor with a certain signature. A specialization of a constructor template is never (by definition) a copy constructor. I think "consequences" is not really used here to mean a logical implication immediately following from the previous statement. I think it is rather just meant to demonstrate some examples where the differentiation between an ordinary function and a function specialized from a function template matters. This use of the word "consequence" seems to be a linguistic oddity. I sometimes see it used like this. It really seems to mean something more like "this allows for the following (and the following is true)". The point here is that only declaring a copy constructor (meaning a non-template constructor) can inhibit the declaration of the implicit copy constructor. So if you only declare a constructor template that can be specialized to have the same signature as a copy constructor, there will still be an implicit copy constructor. I don't know though what the author means with "default" in "default copy constructor". I would usually guess they just used an informal variant for "implicit", but that wouldn't make sense in the context. In your example code there is no constructor template. The declaration of a template begins with template</*...*/> (or since C++20 as a function with auto placeholders in parameter types). entity (T const& y): x(y) { } This is just an ordinary non-template constructor. It's parameter type does depend on the template parameter of the class, but that doesn't make it itself a template (although a templated entity). Even setting that aside, if you specialize the class for e.g. entity<int>, then the parameter becomes type int const&, not entitiy<int> const&, so it won't have the signature of a copy constructor at all. The compiler complains about impossible overload because there is already another constructor with exactly the same parameter list and both are non-template constructors. A constructor template would be e.g.: template<typename U> entity (U const& y): x(y) { } and this one would not inhibit the implicit declaration and definition of the implicit copy constructor although it can be specialized to entity(entity<T> const&) for U = entity<T>. Overload resolution will then still choose the implicit copy constructor instead of this constructor template to perform copies.
72,758,384
72,758,458
Invocability of functors
Why does the standard not consider functors with a ref-qualified call operator to be invocable? #include <concepts> struct f { auto operator()() {} }; struct fr { auto operator()() & {} }; struct fcr { auto operator()() const& {} }; struct frr { auto operator()() && {} }; static_assert(std::copy_constructible<f>); // ok static_assert(std::copy_constructible<fr>); // ok static_assert(std::copy_constructible<fcr>); // ok static_assert(std::copy_constructible<frr>); // ok static_assert(std::invocable<f>); // ok static_assert(std::invocable<fr>); // fails static_assert(std::invocable<fcr>); // ok static_assert(std::invocable<frr>); // ok Well it might have something to do with std::declval returning a temporary object, I don't feel an implementation detail as such should be relevant to the user. Semantically, the functors in the example code should not be regarded differently in terms of invocability. Also, why does there appear to be this contradiction between what std::invocable and std::function consider to be a callable object? #include <functional> using tf = decltype(std::function{f{}}); // ok using tfr = decltype(std::function{fr{}}); // ok using tfcr = decltype(std::function{fcr{}}); // ok using tfrr = decltype(std::function{frr{}}); // fails Just to muddy the waters even further, it also seems that MVSC v19.32 accepts the following code. Is that simply a compiler bug of MSVC? template<std::invocable F> auto g() -> void {} using tg = decltype(g<f>); // ok using tgr = decltype(g<fr>); // ok using tgcr = decltype(g<fcr>); // ok using tgrr = decltype(g<frr>); // ok
This fails: static_assert(std::invocable<fr>); // fails Because it is testing the validity of the expression std::invoke(std::declval<fr>()), which is trying to invoke an rvalue of type fr. But fr's call operator is &-qualified, which means you can only invoke it on an lvalue. That's why it's being rejected. Why does the standard not consider functors with a ref-qualified call operator to be invocable? It's not that it doesn't consider them to be invocable, period. It's that the value category also plays a role in std::invocable. You can see that if you tried: static_assert(std::invocable<fr&>); // ok This is because now we're testing to see if fr can be invoked as an lvalue (which it can), as opposed to as an rvalue (which it cannot).
72,758,545
72,758,571
C++: No match for operator for the same types of operand
I have a vector of a map of int and float std::vector<std::map<int, float>> datad; And I want to iterate over the maps in vector and inside over pairs in map for (std::vector<std::map<int, float>>::iterator currentMap = datad.begin(); currentMap < datad.end(); ++currentMap) { for (std::map<int, float>::iterator it = currentMap->begin(); it < currentMap->end(); ++it) {/*some code here*/} } But in the second loop g++ compiler gives an error: no match for ‘operator<’ (operand types are ‘std::_Rb_tree_iterator<std::pair<const int, float> >’ and ‘std::map<int, float>::iterator’ {aka ‘std::_Rb_tree_iterator<std::pair<const int, float> >’}) But isn't it looks like the types std::_Rb_tree_iterator<std::pair<const int, float>> std::_Rb_tree_iterator<std::pair<const int, float>> are the same? Yes, I see that compiler says the currentMap->end() have the type std::map<int, float>::iterator but...it is aka _Rb_tree_iterator... maybe static_cast<std::_Rb_tree_iterator<std::pair<const int, float>>>(currentMap->end()) What is the easiest way to continue using iterators and fix the problem? PS. static_cast don't work, it gives no match for ‘operator<’ (operand types are ‘std::map<int, float>::iterator’ {aka ‘std::_Rb_tree_iterator<std::pair<const int, float> >’} and ‘std::map<int, float>::iterator’ {aka ‘std::_Rb_tree_iterator<std::pair<const int, float> >’}) PSS. I've also tried auto but it also doesn't work (the same error as the first one)
std::map's iterators are bidirectional iterators, not random access iterators. Therefore they do not provide relational comparison operators. You can only equality-compare them. So replace < with !=, which is the standard way of writing iterator loops. Or even better, replace the loop with a range-for loop: for (auto& currentMap : datad) { for (auto& el : currentMap) { /* Use el here as reference to the (pair) element of the map. */ } }
72,758,653
72,758,765
How to separate a string using separator
I want to separate this string using _ as the separators {[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]} where underscore should not be considered inside the { } brackets. so when we separate the strings we should have three new data items {[Data1]_[Data2]_[Data3]} {[Val1]_[Val2]} {[ID1]_[ID2]_[ID3]} currently I was separating using boost std::vector<std::string> commandSplitSemiColon; boost::split(commandSplitSemiColon, stdstrCommand, boost::is_any_of("_"), boost::token_compress_on); but how can we ignore the underscore inside the { } brackets and only consider underscore which are not inside the brackets.
A manual solution: iterate through the string and use a variable to check whether it's in the bracket or not: std::vector<std::string> strings; std::string s = "{[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]}"; std::string token = ""; bool inBracket = false; for (char c : s) { if (c == '{') { inBracket = true; token += c; } else if (c == '}') { inBracket = false; token += c; } else if (c == '_' && !inBracket) { strings.push_back(token); token = ""; } else { token += c; } } if (!token.empty()) { strings.push_back(token); }
72,758,843
72,758,967
C++ template size argument from initalizer list without standard library
I'm working on some C++ code for an embedded platform (an ATTiny, though I don't think that matters) which miraculously can compile with C++17. I am trying to use constexpr and template arguments anywhere possible in order to avoid managing array sizes manually while also avoiding memory allocations, while also producing something that's difficult to express an invalid state with in case coworkers need to modify it later. I have a particular data type which needs to be able to store a variable number of values (varies in the source code, not during runtime) which would be iterated through at runtime. Using the template array constexpr size trick and a template argument, I can define an array with an initializer list and then pass it to the object being constructed with a template size argument as follows: template <typename T, size_t n> constexpr size_t array_size(const T (&)[n]) { return n; } uint16_t data_fast_flash[] = { 100, 400 }; LedPattern<array_size(data_fast_flash)> fast_flash{data_fast_flash}; uint16_t data_slow_flash[] = { 100, 900 }; LedPattern<array_size(data_slow_flash)> slow_flash{data_slow_flash}; uint16_t data_double_flash[] = { 100, 200, 100, 1000 }; LedPattern<array_size(data_double_flash)> double_flash{data_double_flash}; The LedPattern class is as follows, though I'm not sure it's relevant: template <size_t N> class LedPattern : public ILedPattern { public: explicit LedPattern(uint16_t* delay) : delay_(delay), count_(N) {} void reset() override { index_ = 0; }; [[nodiscard]] uint16_t current() const override { return *(delay_ + index_); } void next() override { if (++index_ >= count_) index_ = 0; }; private: uint16_t* delay_; size_t count_; size_t index_{}; }; All of the above works as expected, but I was hoping to compress the definitions to something where the creation and naming of the uint16_t arrays could go away, given that I think they're now the most typo-prone part of the setup. I did find some seemingly related solutions, but they all rely on the standard library, which I don't have on this platform, such as one using std::index_sequence, and another using std::forward. With C++17 but without the standard library, is there some way of constructing something functionally similar with templates that would: Only require some sort of initializer list of values Could preferably deduce the number of elements in the value list itself Would not require any allocations at runtime Something roughly like the following, though I'm not attached to this exact syntax and I have no problem changing how LedPattern works internally: LedPattern fast_flash{100, 400}; LedPattern slow_flash{100, 900}; LedPattern double_flash{100, 200, 100, 1000};
This seems like a job for user-defined-deduction guides. You could do something like the following: #include <concepts> #include <cstddef> #include <cstdint> using std::size_t; using std::uint16_t; template<size_t N> class LedPattern { public: template<typename ...D> explicit LedPattern(D...d) : delay_{uint16_t(d)...}, count_(N) {} private: uint16_t delay_[N]; size_t count_; size_t index_{}; }; template<std::convertible_to<uint16_t> ...D> LedPattern(D...) -> LedPattern<sizeof...(D)>; LedPattern pat{100, 200, 300}; Just replace std::convertible_to<uint16_t> with typename if your compiler doesn't support concepts yet.
72,759,280
72,759,320
To read from file and store data in map c++
I am trying to read file contents and store it in map data structure, where I am trying to skip comment section not be included in my map. I am unable to keep my map as expected, I am kind off clueless how to go ahead. I have mentioned how my map should look like. Please suggest me what changes I have to add in my code. Thanks in Advnc :) Input file: # Filename: MyFile # Revision: 107 Items Types count price snacks junkfood Mango fruit 5 50 strawbery fruit 10 50 carrot veggie burger junkfood beetroot veggie 4 20 cinnamon masala Expected output file: Stored in map<string, string> [key] [value] Items -> Types count price snacks -> junkfood Mango -> fruit 5 50 strawbery -> fruit 10 50 carrot -> veggie burger -> junkfood beetroot -> veggie 4 20 cinnamon -> masala CPP file: #include <map> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <iterator> using namespace std; typedef std::pair<std::string, std::string> attribute_pair; void check(ifstream &inputFile, map<string, string> &diffm) { diffm.clear(); std::string line; while (getline(inputFile, line)) { std::stringstream ss(line); attribute_pair attribute; while (ss >> attribute.first >> attribute.second) { if (attribute.first != "#") diffm[attribute.first] = attribute.second; } } } int main(int argc, char const *argv[]) { map<string, string> list1; if (argc >= 2) { std::ifstream inputFile(argv[1]); check(inputFile, list1); map<string, string>::iterator itr; for (itr = list1.begin(); itr != list1.end(); itr++) { cout << itr->first << " " << itr->second << "\n"; } } else { std::cerr << "Usage <prog name here> <filename1 here> <filename2 here>\n"; return -2; } }
This is a mistake while (getline(inputFile, line, '\0')) should be while (getline(inputFile, line)) The first one reads 'lines' terminated by the \0 character, which I seriously doubt is what you want. You want lines terminated by the \n character, that's what the second version does. This illustrates the point that Beta was making. The very first thing you try is bugged, so writing and testing the rest of the code is a waste of time. You should write a little piece of code (like checking that you can read a file one line at a time) and only when you are sure that is working should you move onto to the rest of your task. For instance, after working out how to read the file one line at a time, the next task should be to see if you can skip the comment lines. See? Break the task into smaller tasks and solve each smaller task before moving onto the next. That is vitally important. Solving doesn't just mean writing and compiling the code, it means writing the code and writing some code to check that it is working (like some std::cout << ... code). Always make baby steps (especially when you are learning). There's too many things that can go wrong for you to write 20 lines of code at once. Write two, three, or four lines of code, test that code and only when it is working write some more code.
72,759,959
72,762,202
How to convert std::chrono::zoned_time to std::string
What is the most efficient way to convert from std::chrono::zoned_time to std::string? I came up with this simple solution: #include <iostream> #include <sstream> #include <string> #include <chrono> #if __cpp_lib_chrono >= 201907L [[ nodiscard ]] inline auto retrieve_current_local_time( ) { using namespace std::chrono; return zoned_time { current_zone( ), system_clock::now( ) }; } #endif int main( ) { const std::chrono::zoned_time time { retrieve_current_local_time( ) }; const auto str { ( std::ostringstream { } << time ).str( ) }; std::cout << str << '\n'; } As can be seen, time is inserted into the ostringstream object using the operator<< and then a std::string is constructed from its content. Is there anything better than this in the standard library? BTW, why doesn't the above program give proper output when executed on Compiler Explorer?
What you have is not bad. You can also use std::format to customize the format of the time stamp. And std::format returns a std::string directly: const auto str = std::format("{}", time); That gives the same format as what you have. const auto str = std::format("{:%FT%TZ}", time); This gives another popular (ISO) format. std::format lives in the header <format>. Here is the complete documentation for the chrono format flags.
72,759,994
72,760,064
Embed Define into a string
I have a preprocessor define that should determine the size of an array. This constant should also be passed to a HLSL shader. For this I need to pass it around as a string. Is there a way to embed preprocessor defines as a string? #include <iostream> #ifndef SIZE #define SIZE 16 #endif int main() { const int arr[SIZE] = {}; // array size is 16 :) const char* str = "SIZE"; // literal is "SIZE" and not "16" :( std::cout << str << std::endl; // should print "16" std::cout << SIZE << std::endl; // prints 16, but is not a string }
You can use a stringifying macro, eg: #define STRINGIFY(x) STRINGIFY2(x) #define STRINGIFY2(x) #x const char* str = STRINGIFY(SIZE); std::cout << str << std::endl; Alternatively, use a runtime format via snprintf() or equivalent, eg: char str[12]; snprintf(str, "%d", SIZE); std::cout << str << std::endl; However, you really should be using std::string in C++ instead of char*, eg: #include <string> std::string str = std::to_string(SIZE); std::cout << str << std::endl; Or: #include <string> #include <sstream> std::ostringstream oss; oss << SIZE; std::cout << oss.str() << std::endl;
72,760,201
72,760,312
no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>"
I try to implement lambda function:- vector<int> numbers; int value = 0; cout << "Pushing back...\n"; while (value >= 0) { cout << "Enter number: "; cin >> value; if (value >= 0) numbers.push_back(value); } print( [numbers]() -> { cout << "Vector content: { "; for (const int& num : numbers) cout << num << " "; cout << "}\n\n"; }); I got an error:- 1.Severity Code Description Project File Line Source Suppression State Error (active) E0312 no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>" exists consoleapplication C:\Users\insmitr\source\repos\consoleapplication\consoleapplication.cpp 46 IntelliSense 2.Severity Code Description Project File Line Source Suppression State Error (active) E0079 expected a type specifier consoleapplication C:\Users\insmitr\source\repos\consoleapplication\consoleapplication.cpp 47 IntelliSense Could you please help me in this regards
The problem is that print accepts a vector<int> but while calling print you're passing a lambda and since there is no implicit conversion from the lambda to the vector, you get the mentioned error. You don't necessarily need to call print as you can just call the lambda itself as shown below. Other way is to make print a function template so that it can accept any callable and then call the passed callable. int main() { std::vector<int> numbers; int value = 0; cout << "Pushing back...\n"; while (value >= 0) { cout << "Enter number: "; cin >> value; if (value >= 0) numbers.push_back(value); } //-------------------vvvv------>void added here ( [numbers]() -> void { cout << "Vector content: { "; for (const int& num : numbers) cout << num << " "; cout << "}\n\n"; //----vv---->note the brackets for calling })(); return 0; } Demo
72,760,488
72,762,934
Thread-safety about `std::map<int, std::atomic<T>>` under a special condition
In general, it's not thread-safe to access the same instance of std::map from different threads. But is it could be thread-safe under such a condition: no more element would be added to\remove from the instance of std::map after it has been initialized the type of values of the std::map is std::atomic<T> Here is the demo code: #include<atomic> #include<thread> #include<map> #include<vector> #include<iostream> class Demo{ public: Demo() { mp_.insert(std::make_pair(1, true)); mp_.insert(std::make_pair(2, true)); mp_.insert(std::make_pair(3, true)); } int Get(const int& integer, bool& flag) { const auto itr = mp_.find(integer); if( itr == mp_.end()) { return -1; } else { flag = itr->second; return 0; } } int Set(const int& integer, const bool& flag) { const auto itr = mp_.find(integer); if( itr == mp_.end()) { return -1; } else { itr->second = flag; return 0; } } private: std::map<int, std::atomic<bool>> mp_; }; int main() { Demo demo; std::vector<std::thread> vec; vec.push_back(std::thread([&demo](){ while(true) { for(int i=0; i<9; i++) { bool cur_flag = false; if(demo.Get(i, cur_flag) == 0) { demo.Set(i, !cur_flag); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } })); vec.push_back(std::thread([&demo](){ while(true) { for(int i=0; i<9; i++) { bool cur_flag = false; if(demo.Get(i, cur_flag)==0) { std::cout << "(" << i << "," << cur_flag <<")" << std::endl; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } }) ); for(auto& thread:vec) { thread.join(); } } What more, the compiler does not complain about anything with -fsanitize=thread option.
Yes, this is safe. Data races are best thought of as unsynchronized conflicting access (potential concurrent reads and writes). std::thread construction imposes an order: the actions which preceded in code are guaranteed to come before the thread starts. So the map is completely populated before the concurrent accesses. The library says standard types can only access the type itself, the function arguments, and the required properties of any container elements. std::map::find is non-const, but the standard requires that for the purposes of data races, it is treated as const. Operations on iterators are required to at most access (but not modify) the container. So the concurrent accesses to std::map are all non-modifying. That leaves the load and store from the std::atomic<bool> which is race-free as well.
72,760,907
72,760,941
Returning lvalue from function
Why the result of returning lvalue from function is that that object std::vector<int> v in main() function has same memory address as returned object std::vector<int> vec in a get_vec() function, even though these objects exist in a different stack frame ? Why there is not called move constructor ? #include <iostream> #include <vector> std::vector<int> get_vec() { std::vector<int> vec = { 1, 2, 3, 4, 5 }; std::cout << "get_vec():\n" << &vec << '\n' << vec.data() << "\n\n"; return vec; } int main() { std::vector<int> v = get_vec(); std::cout << "main():\n" << &v << '\n' << v.data() << "\n\n"; return 0; } OUTPUT: get_vec(): 0x7a07ee93baa0 0x226b290 main(): 0x7a07ee93baa0 0x226b290
vec is either moved (automatically, because you're returning a local variable), or, if the compiler is smart enough, is the same object as v (this is called NRVO). In both cases .data() is going to stay the same. When moved, the new vector takes ownership of the other vector's heap memory. &vec,&v are going to be the same only if the compiler performs NRVO.
72,761,126
72,761,584
Multithreading beginner query (C++)
I am trying to learn multithreading in C++. I am trying to pass elements of a vector as arguments to pthread_create. However, it is not working as expected. #include <iostream> #include <cstdlib> #include <pthread.h> #include <vector> using namespace std; void *count(void *arg) { int threadId = *((int *)arg); cout << "Currently thread with id " << threadId << " is executing " << endl; pthread_exit(NULL); } int main() { pthread_t thread1; vector<int> threadId(2); threadId[0] = 99; threadId[1] = 100; int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]); if (retVal) { cout << "Error in creating thread with Id: " << threadId[0] << endl; exit(-1); } pthread_t thread2; retVal = pthread_create(&thread2, NULL, count, (void *)&threadId[1]); if (retVal) { cout << "Error in creating thread with Id: " << threadId[1] << endl; exit(-1); } pthread_exit(NULL); } The output which I get is: Currently thread with id 99 is executing. Currently thread with id 0 is executing However, according to me, it should be: Currently thread with id 99 is executing. Currently thread with id 100 is executing. What am I missing here ?
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]); You have no guarantee, whatsoever, that the new execution thread is now running, right this very instant, without any delay. All that pthread_create guarantees you is that the thread function, thread1, will begin executing at some point. It might be before pthread_create() itself returns. Or it might be at some point after. It's really a big mystery when the new thread function will start executing, but you can take it to the bank that the new execution thread will begin. Eventually. The same thing goes for your 2nd execution thread. So, both execution thread could very well get in gear after your main() returns, and after your vector gets destroyed. There's nothing in the shown code that guarantees that the execution threads will execute before the vector (whose contents get passed into them, in the manner shown) gets destroyed. And this leads to undefined behavior. You will need to use other thread-related facilities that must be employed in order to synchronize multiple execution threads correctly. Additionally, you're using older POSIX threads. Modern C++ uses std::threads which offer many advantages over their predecessor, is completely type-safe (no ugly casts) and have numerous attributes that prevent common programming errors (however, in this instance std::threads also have no synchronization guarantee, this is usually the case with all typical execution thread implementations).
72,761,210
72,765,027
c++ mac/m1/intel how to get cpu architecture?
I need to find out at runtime which architecture the cpu is running. I've so far used qt : QSysInfo::currentCpuArchitecture() but there is a problem. The returned value will change when ever I run application that was compiled for x86_64 or arm64. So this will not return the hardware architecture that the system is natively running, but the emulated one by mac. Say if I run x86_64 it would run via rosetta probably and then the arch would be x86_64 and not arm64. I need a way to find out hardware arch of system that is, and not is emulated... Does any1 have any idea how to do it? Macros/etc will not work. Running QProcess from within the app still returns x86_64 from uname -p etc.
Starting QProcess does not work, he inherits base application architecture. I found out that apple added a command to figure out if I'm running in "translated" mode, this can then be used as indication if we are on intel or arm. https://developer.apple.com/documentation/apple-silicon/about-the-rosetta-translation-environment
72,761,386
72,761,460
How to reference a classes attribute inside another class method?
I'm trying to create a little ascii game where I can run around kill enemies etc. However I'm new to C++ and I would like to do something if the players location is at a certain point. Below is a simpler version of the code and a picture of the problem: #include <iostream> using namespace std; struct Game { bool bGameOver = false; int iWidth = 20; int iHeight = 40; void Draw() { if (player.x == 5) { cout << "Hello" } } }; struct Player { bool bGameOver = false; int x = 0; int y = 0; }; void Setup() { } int main() { Game game; Player player; while (!game.bGameOver) { Setup(); } } Picture of the error
The variable player is local in function main, so it's not visible where you tried to use it in Game::Draw. One solution could be to make player a global variable. You'll need to switch the order of the structs: struct Player { bool bGameOver = false; int x = 0; int y = 0; }; Player player; struct Game { bool bGameOver = false; int iWidth = 20; int iHeight = 40; void Draw() { if (player.x == 5) { cout << "Hello" } } }; But I'd prefer to instead model things so a Game "has a" Player. So make Player a member of the Game: struct Player { bool bGameOver = false; int x = 0; int y = 0; }; struct Game { Player player; bool bGameOver = false; int iWidth = 20; int iHeight = 40; void Draw() { if (player.x == 5) { cout << "Hello" } } }; (Aside: You probably don't want two different values called bGameOver, since keeping them in sync would be extra work. It sounds more like a game property than a player property to me.)
72,761,783
72,761,956
Why does it give an error when compiling the project:
I need to display an array of structures, as far as I understand, I need to use a memory shift, having a pointer to the first element of the array. When trying to fix the code, we saw the following error: Invalid types ‘[int]’ for array subscript my code: #include <iostream> #include <string.h> using namespace std; typedef struct Point3D{ double x; double y; double z; }Point3D; Point3D createPoint3D(double xnum, double ynum, double znum){//функція створення точки Point3D point; point.x = xnum; point.y = ynum; point.z = znum; return point; } void PrintPoint(Point3D point){//використовується в інщій ф-ції, по суті внутрішня не основна функція cout << "(" << point.x << ","<< endl; cout << point.y<< ","<< endl; cout << point.z<< ";"<< "\n"<< endl; } class Obj3D{ private: Point3D *array_of_points; int number_of_points; public: void setAddPoint(Point3D point){ *(array_of_points + sizeof(point)*number_of_points) = point; number_of_points++;} int getNumber(){ return number_of_points;} Point3D *getArray(){ return array_of_points;} Obj3D(Point3D point, int number){ number--; *(array_of_points + number) = point;} Obj3D(){ *array_of_points = createPoint3D(0.0, 0.0, 0.0); number_of_points = 1; } ~Obj3D(){} }; void printObj(Obj3D Obj){ for(int x = 0; x<=Obj.getNumber(); x++){ PrintPoint(Obj.getArray()[x]); } } int main(int argc, char* argv[]){ Obj3D Obj; Point3D point1 = createPoint3D(-0.5,-0.5,-0.5); Point3D point2 = createPoint3D(0.5,-0.5,-0.5); Point3D point3 = createPoint3D(-0.5,-0.5,0.5); Point3D point4 = createPoint3D(0.5,-0.5,0.5); Point3D point5 = createPoint3D(0.0,0.5,0.0); Obj.setAddPoint(point1); Obj.setAddPoint(point2); Obj.setAddPoint(point3); Obj.setAddPoint(point4); Obj.setAddPoint(point5); cout<<Obj.getArray(); exit(0); } You can not watch the main function, it is most likely not correct, I want to deal with the functions of the output and set
You absolutely don't need to memory shift *(array_of_points + sizeof(point)*number_of_points) = point; C++ is not that complicated, just array_of_points[number_of_points] = point; Because the compiler knows the type involved, Point3D, it's quite capable of working out the memory shift by itself. Also by the rules of C++ *(p + n) is exactly equivalent to p[n] but generally prefer the latter because it is easier to read. Other errors (which you'll find out when you run the code). Class Obj3D has an uninitialised pointer array_of_points. You use the pointer, e.g. here Obj3D(){ *array_of_points = createPoint3D(0.0, 0.0, 0.0); number_of_points = 1; } but you never give the pointer a value. So that is going to crash your program. You need to allocate memory using new for your pointer to point at. That doesn't happen automatically. E,g, Obj3D() { array_of_points = new Point3D[100]; // allocate 100 points array_of_points[0] = createPoint3D(0.0, 0.0, 0.0); number_of_points = 1; }
72,762,151
72,765,485
How can I iterate over a TGroupBox and check the state of its children?
Using C++ Builder 10.4 Community edition, I have a TGroupBox populated with some TCheckbox and TButton controls. I want to iterate over the TGroupBox to get the state of each TCheckBox. How can I do this? I tried this: auto control = groupBxLB->Controls; for( uint8_t idx = 0; idx < groupBxLB->ChildrenCount; idx++) { if( control[idx] == TCheckBox) { //get the state of the TCHeckBox } } but no success. Does anybody have an idea how I can do this?
The TWinControl::Controls property is not an object of its own, so you can't assign it to a local variable, the way you are trying to. Also, there is no ChildrenCount property in TWinControl. The correct property name is ControlCount instead. The C++ equivalent of Delphi's is operator in this situation is to use dynamic_cast (cppreference link) and check the result for NULL. Try this: for(int idx = 0; idx < groupBxLB->ControlCount; ++idx) { TCheckBox *cb = dynamic_cast<TCheckBox*>(groupBxLB->Controls[i]); if (cb != NULL) { // use cb->Checked as needed... } } UPDATE: You did not make it clear in your original question that you wanted a solution for FMX. What I posted above is for VCL instead. The FMX equivalent would look more like this: auto controls = groupBxLB->Controls; for(int idx = 0; idx < controls->Count; ++idx) { TCheckBox *cb = dynamic_cast<TCheckBox*>(controls->Items[idx]); if (cb != NULL) { // use cb->IsChecked as needed... } }
72,762,364
72,762,607
compile time parameter checking
I'm trying to understand how the Qt5 framework's Signals and Slots mechanism does type checking on function arguments. I've provided a summary of the section of code I'm interested in. The only thing I'm having trouble understanding is the following template specialization. How does the compiler decide to instantiate this? I especially don't understand when template parameter list template< typename Arg1, typename Arg2, typename... Tail1, typename... Tail2 > is considered. template< typename Arg1, typename Arg2, typename... Tail1, typename... Tail2 > struct Test< List< Arg1, Tail1... >, List< Arg2, Tail2... > > { enum { value = ArgsCompat< Arg1, Arg2 >::value && Test< List< Tail1... >, List< Tail2... > >::value }; }; namespace Test { template< typename... > struct List{}; template< typename H, typename... T > struct List< H, T... >{ typedef H Head; typedef List< T... > Tail; }; template< typename T > struct RemoveRef { typedef T type; }; template< typename T > struct RemoveRef< T& > { typedef T type; }; template< typename Arg1, typename Arg2 > struct ArgsCompat { static int test( const typename RemoveRef< Arg2 >::type & ); enum { value = true }; }; template< typename Elem1, typename Elem2 > struct Test { enum { value = false}; }; template<> struct Test< List<>, List<> > { enum { value = true }; }; template< typename Arg1> struct Test< Arg1, List<> > { enum { value = true }; }; template< typename Arg1, typename Arg2, typename... Tail1, typename... Tail2 > struct Test< List< Arg1, Tail1... >, List< Arg2, Tail2... > > { enum { value = ArgsCompat< Arg1, Arg2 >::value && Test< List< Tail1... >, List< Tail2... > >::value }; }; } int main( void ) { static_assert( Test::Test< Test::List<>, Test::List<> >::value, "" ); static_assert( Test::Test< Test::List< char >, Test::List< char > >::value, "" ); static_assert( Test::Test< Test::List< char, int, double >, Test::List< char, int, double > >::value, "expected true" ); return 0; }```
When it comes to the instantiations in the two last static_asserts, they both match these: template <typename Elem1, typename Elem2> struct Test { enum { value = false }; }; template <typename Arg1, typename Arg2, typename... Tail1, typename... Tail2> struct Test<List<Arg1, Tail1...>, List<Arg2, Tail2...> > { ... }; When there's more than one template matching, it always selects the one that is more constrained, which is the second one in this case. The first one is more relaxed (Elem1 and Elem2 can be anything). If they had been equally constrained there would have been ambiguity and compilation would fail. The parameters in the first static_assert matches these two: template <typename Elem1, typename Elem2> struct Test { enum { value = false }; }; template <> struct Test<List<>, List<> > { enum { value = true }; }; and again, the second one is more constrained and is therefore selected.
72,762,781
72,762,847
Create a pointer that points to a member function that takes a struct as an argument
I have main.cpp file where I defined a struct: struct values { string name1; string name2; int key ; } a; A class named Encrypt defined in a header file Encrypt.h and a file Encrypt.cpp where I define my functions... Im trying to create a pointer that points to a function that has a struct type as parameter here's how I did it: in my header file Encrypt.h #ifndef Encrypt_h #define Encrypt_h #include<iostream> using namespace std; class Encrypt { public: void print(void *); }; #endif /* Encrypt_h */ in my Encrypt.cpp : void Encrypt::print(void * args) { struct values *a = args; string name= a.name1; cout<<"I'm"<<name<<endl; }; here's how I tried to create the pointer in main.cpp void (Encrypt::* pointer_to_print) (void * args) = &Encrypt::print; THE ERROR I GET : " Cannot initialize a variable of type 'struct values *' with an lvalue of type 'void *' " in Encrypt.cpp the line : struct values *a = args; REMARQUE Im doing this because I want to pass a function with more than 2 parameters to the function : pthread_create() so my function print is just I simplified example.
The problem is that args is of type void* and a is of type values* so you get the mentioned error. To solve this uou can use static_cast to cast args to values* if you're sure that the cast is allowed: values *a = static_cast<values*>(args); Additionally change a.name1 to a->name1. Demo
72,763,138
72,763,703
Why does this minimal HTTP test server fail half of the time?
I'm trying to write a minimal HTTP server on Windows and see the response in Chrome with http://127.0.0.1/5000. The following code works sometimes ("Hello World"), but the request fails half of the time with ERR_CONNECTION_ABORTED in Chrome (even after I restart the server). Why? Error: #include <winsock2.h> #include <iostream> #pragma comment(lib, "ws2_32.lib") int main() { WSADATA WSAData; SOCKET sock, csock; SOCKADDR_IN sin, csin; WSAStartup(MAKEWORD(2,0), &WSAData); sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_addr.s_addr = INADDR_ANY; sin.sin_family = AF_INET; sin.sin_port = htons(5000); bind(sock, (SOCKADDR *) &sin, sizeof(sin)); listen(sock, 0); while(1) { int sinsize = sizeof(csin); if((csock = accept(sock, (SOCKADDR *) &csin, &sinsize)) != INVALID_SOCKET) { std::string response = "HTTP/1.1 200 OK\nConnection: close\nContent-Length: 11\n\nHello World"; send(csock, response.c_str(), response.size(), 0); std::cout << "done"; closesocket(csock); } } return 0; }
You fail to read the client's request before closing the connection. This usually results in the server sending a RST back to the client, which can cause the ERR_CONNECTION_ABORTED when it is processed before the response itself was processed. As observed by another (deleted) answer, this can be "mitigated" by adding some short delay before the connection is closed, so that the response is processed by the client. The right fix is to read the request from the client, though. Apart from that, your response is not valid HTTP since you use \n instead of \r\n as line end and header end. Working solution: #include <winsock2.h> #include <iostream> #define DEFAULT_BUFLEN 8192 #pragma comment(lib, "ws2_32.lib") int main() { char recvbuf[DEFAULT_BUFLEN]; WSADATA WSAData; SOCKET sock, csock; SOCKADDR_IN sin, csin; WSAStartup(MAKEWORD(2,0), &WSAData); sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_addr.s_addr = INADDR_ANY; sin.sin_family = AF_INET; sin.sin_port = htons(5000); bind(sock, (SOCKADDR *) &sin, sizeof(sin)); listen(sock, 0); while (1) { int sinsize = sizeof(csin); if ((csock = accept(sock, (SOCKADDR *) &csin, &sinsize)) != INVALID_SOCKET) { recv(csock, recvbuf, DEFAULT_BUFLEN, 0); std::string response = "HTTP/1.0 200 OK\r\nConnection: close\r\nContent-Length: 11\r\n\r\nHello World"; send(csock, response.c_str(), response.size(), 0); std::cout << "done"; closesocket(csock); } } return 0; }
72,764,614
72,764,688
Deduction in template functions with few args
I have few instances of one template function. Each of them sequentially executes each of given lambdas, accompanying them with specific messages. When I do that with one lambda, everything works fine, but when I try to add more than one, I get note: candidate template ignored: deduced conflicting types for parameter 'Task' From clang. Here is my code: template <class Task> void doTasks(Task task1) // works fine { if (std::__is_invocable<Task>::value) { std::cout << "doing first task" << endl; task1; } } template <class Task> void doTasks(Task task1, Task task2) // deduced conflicting types { if (std::__is_invocable<Task>::value) { std::cout << "doing first task" << endl; task1(); std::cout << "doing second task" << endl; task2(); } } int main() { doTasks([&] (){std::cout << "1" << endl;}); doTasks([&] (){std::cout << "1" << endl;}, [&] (){std::cout << "2" << endl;}); return 0; } What's wrong with it? How can I deal with my problem? Sorry if it's a stupid question, I'm some kind of beginner in C++ and may not understand some template nuances.
Even though the two passed lambdas does the same or looks similar, they have completely different types. Hence, you need two different template types there in the doTasks. Easy fix is providing the template parameter for two lambdas template <class T1, class T2> void doTasks(T1 task1, T2 task2) { // ... } otherwise, using the variadic template function and fold expression, you could do something like: #include <type_traits> // std::conjunction_v, std::is_invocable template <class... Ts> void doTasks(Ts&&... lmds) { if (std::conjunction_v<std::is_invocable<Ts>...>) // maybe if constexpr { (lmds(), ...); } } Since the argument is variadic, it will also work for the single/ any arguments of doTasks and hence no code duplication. Live demo
72,764,815
72,764,841
Best way to copy members from vector<Class> to vector<Member_Type>
I have a vector of complicated structs (here std::pair<int, int>). I now want to copy a member (say std::pair::first) into a new vector. Is there a better (more idiomatic) way than std::vector<std::pair<int, int>> list = {{1,2},{2,4},{3,6}}; std::vector<int> x_values; x_values.reserve(list.size()); for( auto const& elem : list ) { x_values.emplace_back(elem.first); }
std::transform is often used for exactly this: #include <algorithm> // transform #include <iterator> // back_inserter // ... std::vector<int> x_values; x_values.reserve(list.size()); std::transform(list.cbegin(), list.cend(), std::back_inserter(x_values), [](const auto& pair) { return pair.first; });
72,764,871
72,766,440
Examples of constinit declaration not reachable at the point of the initializing declaration
From dcl.constinit: No diagnostic is required if no constinit declaration is reachable at the point of the initializing declaration. What does it mean? I guess an example would be sufficient. Something dynamically initialized is just ill-formed (from the same link), so it's not that.
Suppose you have one translation unit that declares a symbol to be constinit: // a.cc #include <iostream> extern constinit bool has_constinit; int main() { std::cout << std::boolalpha << has_constinit << std::endl; } Now suppose the translation unit that defined the symbol does not declare it constinit: // b.cc #include <cstdlib> bool has_constinit = std::getenv("CONSTINIT"); You can compile and link these two files together without error, even though it doesn't do what you wanted, because has_constinit is being initialized dynamically.
72,765,068
72,812,265
Compiling assimp from source does not generate libassimp file
So I compiled the assimp library with cmake using the x64_x86 developer command prompt that was said to be required. (When I tried using the regular console cmake did an error that it could not find 'the cl compiler'). After some time it finally compiled without errors with the following commands: cmake CMakeLists.txt -DASSIMP_BUILD_ASSIMP_TOOLS=OFF cmake --build . It built 3 files: C static library zlibstaticd.lib CXX shared library ..\bin\assimp-vc142-mtd.dll CXX executable ..\bin\unit.exe But there was no libassimp.a or libassimp.so that I can link against in MinGW. I tried just linking with te dll in my own project with: -L\"{assimp root directory}/bin\" -lassimp-vc142-mtd and it failed with "undefined reference to `Assimp::Importer::Importer()" How can i get the lib file to link against?
I installed MSYS2, replaced my existing MinGW installation with MSYS, libraries installed flawlessly and everything works now. My mistake was that: I was compiling the library with VS C++ toolkit while I'm compiling my project with MInGW make and g++ even after I compiled assimp the correct way, version 5.2.4 couldn't find some header, 5.2.3 and some older versions compiled successfully, but failed some unit tests (God knows why). Seemed to always hit some unresolved issue on GitHub. Never again compiling libraries from source.
72,765,359
72,778,798
1D FFT MATLAB results are different from FFTW in C++
I have the MATLAB code: Nx = 10; Ny = 10; Lx = 2*pi; ygl = -cos(pi*(0:Ny)/Ny)'; %Gauss-Lobatto chebyshev points x = (0:Nx-1)/Nx*2*pi; %make mesh [X,Y] = meshgrid(x,ygl); A = 2*pi / Lx; u = sin( (2*pi / Lx) * X); uh = fft(u) This gives the following output: 0 6.4656 10.4616 10.4616 6.4656 0.0000 -6.4656 -10.4616 -10.4616 -6.4656 0 0.0000 0 0 0.0000 0.0000 -0.0000 0 0 0 0 0.0000 0 0 0.0000 0.0000 0 0 0 -0.0000 0 0 0 0 0.0000 0.0000 0 0 0 0 0 0.0000 0 0 0.0000 0.0000 -0.0000 0 0 0 0 0.0000 0 0 0.0000 0.0000 0 0 0 -0.0000 0 0.0000 0 0 0.0000 0.0000 0 0 0 -0.0000 0 0.0000 0 0 0.0000 0.0000 -0.0000 0 0 0 0 0 0 0 0.0000 0.0000 0 0 0 0 0 0.0000 0 0 0.0000 0.0000 0 0 0 -0.0000 0 0.0000 0 0 0.0000 0.0000 -0.0000 0 0 0 And the C++ code using FFTW: static const int nx = 10; static const int ny = 10; static const int nyk = ny/2 + 1; double Lx = 2 * M_PI; double A = (2 * M_PI)/Lx; double *XX; XX = (double*) fftw_malloc((nx*(ny+1))*sizeof(double)); memset(XX, 42, (nx*(ny+1))* sizeof(double)); double *YY; YY = (double*) fftw_malloc((nx*(ny+1))*sizeof(double)); memset(YY, 42, (nx*(ny+1))* sizeof(double)); double *u; u = (double*) fftw_malloc((((ny+1)*nx))*sizeof(double)); fftw_complex *uh; uh = (fftw_complex*) fftw_malloc(((ny+1)*nyk)*sizeof(fftw_complex)); memset(uh, 42, ((ny+1)*nyk)* sizeof(fftw_complex)); for(int i = 0; i< nx+1; i++){ for(int j = 0; j< ny; j++){ XX[i + (ny+1)*j] = (j)*2*M_PI/nx; YY[i + (ny+1)*j] = -1. * cos(((i) * M_PI )/ny); u[i + (ny+1)*j] = sin(A * XX[i + (ny+1)*j]); } } fftw_plan r2c1; r2c1 = fftw_plan_dft_r2c_1d(nx , &u[0], &uh[0], FFTW_ESTIMATE); fftw_execute(r2c1); fftw_destroy_plan(r2c1); fftw_cleanup(); //print uh This give the output: (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), (0.0000,0.0000), Why are these two results are NOT matching?? I understand there are some differences between FFT in MATLAB and C++ but this is a simple 1D FFT and it's WAY off than the MATLAB results. NOTE: I added the results of MATLAB and C++ for comparison ad requested by someone in the comments.
Was able to fix this by taking the FFT of each columns as someone suggested in the comments: { cplx_buffer out = my_fftw_allocate_cplx(nyk, nx); fftw_execute(fftw_plan_many_dft_r2c(1, &in.rows, in.cols, in.a, &in.rows, in.cols, 1, out.a, &in.rows, out.cols, 1, FFTW_ESTIMATE)); std::cout << "DFT of input, column-wise\n"; print_matrix(out); }
72,766,332
72,766,398
c++11: how to produce "spurious failures" upon compare_exchange_weak?
Is there a way that we can write some code to produce a "spurious failures" for the "weak" version of compare_exchange? While the same code should work well for compare_exchange_strong? I wish to see the real difference between the "weak" and "strong" version of 2 apis, any sample for it? Thanks a lot!
You'll need a non-x86 CPU, typically one that uses load-linked / store-conditional like ARM or AArch64 (before ARMv8.1). x86 lock cmpxchg implements CAS_strong, and there's nothing you can do to weaken it and make it possibly fail when the value in memory does match. CAS_weak can compile to a single LL/SC attempt; CAS_strong has to compile to an LL/SC retry loop to only fail if the compare was false, not merely from competition for the cache line from other threads. (As on Godbolt, for ARMv8 ldxr/stxr vs. ARMv8.1 cas) Have one thread use CAS_weak to do 100 million increments of a std::atomic variable. (https://preshing.com/20150402/you-can-do-any-kind-of-atomic-read-modify-write-operation/ explains how to use a CAS retry loop to implement any arbitrary atomic RMW operation on one variable, but since this is the only thread writing, CAS_strong will always succeed and we don't need a retry loop. My Godbolt example shows doing a single increment attempt using CAS_weak vs. CAS_strong.) To cause spurious failures for CAS_weak but not CAS_strong, have another thread reading the same variable, or writing something else in the same cache line. Or maybe doing something like var.fetch_or(0, std::memory_order_relaxed) to truly get ownership of the cache line, but in a way that wouldn't affect the value. That will definitely cause spurious LL/SC failures. When you're done, 100M CAS_strong attempts will have incremented the variable from 0 to 100000000. But 100M CAS_weak attempts will have incremented to some lower value, with the difference being the number of failures.
72,766,402
72,766,473
How to check if given year, month, day and time format is valid in C++?
I am working on an application where the log files will be named in the format "YYYYMMDDHHMM_****.gz". The log file contains YYYY (year), MM (month), DD (day), HH (hours) and MM (minutes). My class constructor needs to check if the file name is valid (whether the year, month, day and time are valid or not). I thought by passing these values to time_t structure, it will return -1 for invalid values. But it is not returning -1. Below is the program. #include <iostream> #include <iomanip> #include <ctime> #include <sstream> int main() { struct tm tm{}; std::istringstream iss("2018 12 22 00:26:00"); //std::istringstream iss("2018 12 aa 00:26:00"); --> THIS IS NOT -1 iss >> std::get_time(&tm, "%Y %m %d %H:%M:%S"); time_t time = mktime(&tm); std::cout << time << std::endl; std::cout << std::ctime(&time) << std::endl; return 0; } O/P: 1545438360 Sat Dec 22 00:26:00 2018 But If I give date as "2018 12 aa 00:26:00" (month : aa which is invalid), still it is printing some valid o/p. O/P: 1543536000 Fri Nov 30 00:00:00 2018 I need to discard the files which are having file names in the format ""YYYYMMDDHHMM_****.gz"" and which are 14 days old in a directory. But time_t is not giving -1 for invalid date time format. Can any one please let me know if there is any way to check if the given date is valid or do I need to check manually?
You need to check if std::get_time itself fails. The failing operation is the conversion, not the construction of a time_t value from the resulting struct tm. The sample code on cppreference.com gives a very easy to follow example of how to do that: ss >> std::get_time(&t, "%Y-%b-%d %H:%M:%S"); if (ss.fail()) { std::cout << "Parse failed\n"; When std::get_time fails it sets the input stream into a failed state, so all you do is check for that.
72,766,688
72,771,169
Reading sensors data from the sysfs interface (hwmon) occasionally results in a blocking call (longer execution time for the function than expected)
I have an ARM machine that runs Linux (BusyBox). I need to frequently read the data in this file /sys/class/hwmon/hwmon0/device/in7_input which contains voltage. It's located in the virtual file system sysfs under the /sys/class/hwmon/ directory. The file contains data that looks like this (SSHed to the device). root:~# cat /sys/class/hwmon/hwmon0/device/in7_input 10345 root:~# cat /sys/class/hwmon/hwmon0/device/in7_input 10250 Usually reading the data from that file takes about 1 ms but there are occasions where it takes about 1 sec. Unfortunately for me, I'm not able to replicate this issue on my bench since it doesn't happen very frequently on the field. I have checked the CPU utilization and it's usually less than 60% when this issue occurs. I'm not sure why occasionally reading from that file results in what appears to be a blocking call that results in a longer execution time for the function. I'm not sure if I'm dealing with a bigger problem that's occurring on the virtual file system sysfs or if the code I have in readVoltage() isn't completely non-blocking. Here is a snippet of that code that I had to tweak /****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> using namespace std; uint64_t GetClockCount(void); float calculateLoopTime(uint32_t tUsec1, uint32_t tUsec2); void readVoltage() { static const char VoltageFile[] = "/sys/class/hwmon/hwmon0/device/in7_input"; static int VoltageFD = -1; if (-1 == VoltageFD) { VoltageFD = open(VoltageFile, O_RDONLY | O_NONBLOCK); } if (-1 == VoltageFD) { std::cout << "couldn't open FD for " << VoltageFile << std::endl; } else { static const size_t bufSize = 15; char buffer[bufSize]; fd_set input; FD_ZERO(&input); FD_SET(VoltageFD, &input); struct timeval to; to.tv_sec = 0; to.tv_usec = 0; int n = 0; n = select(VoltageFD + 1, &input, NULL, NULL, &to); if (n > 0) { ssize_t bytes_read = pread(VoltageFD, buffer, bufSize, 0); if (bytes_read > 0) { float voltage = (atof(buffer) / 1000.0f); std::cout << "voltage= " << voltage << std::endl; } } } } int main() { uint32_t start_time = GetClockCount(); readVoltage(); uint32_t end_time = GetClockCount(); float time_diff = calculateLoopTime(start_time, end_time); std::cout << "function took " << time_diff << " ms to execute" << std::endl; return 0; } uint64_t GetClockCount(void) { struct timespec now; if (clock_gettime(CLOCK_MONOTONIC, &now)) return 0; return static_cast<uint64_t>(now.tv_sec) * 1000000 + now.tv_nsec / 1000; } float calculateLoopTime(uint32_t tUsec1, uint32_t tUsec2) { float time_diff = 0; if (tUsec1 != tUsec2) { uint32_t time_diff_temp = 0; if (tUsec2 > tUsec1) { time_diff_temp = (tUsec2 - tUsec1); } // Scale from microseconds to milliseconds time_diff = static_cast<float>(time_diff_temp) / 1000; } return time_diff; } You can run the code here but obviously you won't get the the voltage since this file /sys/class/hwmon/hwmon0/device/in7_input doesn't exist on that online IDE. https://onlinegdb.com/d0wcJ0tzT
The code you wrote in the readVoltage() is non-blocking. You can use the fact, that read() on non-blocking descriptor would return E_AGAIN / E_WOULDBLOCK errno if reading would block and therefore remove lines with select() and setting FD_SET (less code). You can't be sure what is happening between GetClockCount() calls. If your system is under load (like you say less 60%) it can be doing something else. Hardware thread can be doing some other operation even if it's not doing it 100% time it can introduce some jitter when switching back to your sysfs reading code. To be more accurate try to measure only pread() invocation time but therefore still be possibility for running some other process' code, especially when talking about system under load. You can also try to use perf to check out what's going on in your program. Look here to check out that perf can show how many context-switches occured during running your program. Try to also measure calling plain sysfs reading by using: root:~# cat /sys/class/hwmon/hwmon0/device/in7_input All the results should show that something other is done by the system and pread() call is not blocking itself as it's double checked - once using non-blocking flag and secondary when checking if select() returned ready descriptor.
72,766,788
72,766,815
Overloading << operator for printing stack in c++
#include <iostream> #include <ostream> #include <bits/stdc++.h> using namespace std; void printHelper(ostream& os,stack<int>& s){ if(s.empty()) return ; int val = s.top(); s.pop(); printHelper(s); os << val << " "; s.push(val); } ostream& operator<<(ostream& os,stack<int>& s){ os << "[ "; printHelper(os,s); os << "]\n"; return os; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif stack<int> s; for(int i = 0;i<5;i++){ s.push(i+1); } cout << s; return 0; } // c++ stack -- push pop top size empty I want to know as to why this code is not working, I want to print my stack in the same fashion as in java within square brackets i.e [ 1 2 3 4 5 ]. Please help me identify what have i done wrong.
The problem(error) is that printHelper expects two arguments but you're passing only when when writing: //----------v--->you've passed only 1 printHelper(s); To solve this(the error) just pass the two arguments as shown below: //----------vv--v---------->pass 2 arguments as expected by printHelper printHelper(os, s); Working demo
72,767,469
72,767,712
debug template for array C++
I want to create debug template for array for printing array. This is my template #define debug(x) cerr << #x <<" = "; print(x); cerr << endl; void print(ll t) {cerr << t;} void print(int t) {cerr << t;} void print(float t) {cerr << t;} void print(string t) {cerr << t;} void print(char t) {cerr << t;} template <class T> void print(vector <T> v) {cerr << "[ "; for (T i : v) {print(i); cerr << " ";} cerr << "]";} template <class T> void print(T arr[]) {cerr << "[ "; for (T i : arr) {print(i); cerr << " ";} cerr << "]";} But its giving some errors for array but vector works fine, template <class T> void print(T arr[]) {cerr << "[ "; for (T i : arr) {print(i); cerr << " ";} cerr << "]";} ^~~ A.cpp:16:55: note: suggested alternatives: In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\mingw32\bits\stdc++.h:95:0, from A.cpp:1: c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\valarray:1206:5: note: 'std::begin' begin(const valarray<_Tp>& __va) ^~~~~ c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\valarray:1206:5: note: 'std::begin' A.cpp:16:55: error: 'end' was not declared in this scope template <class T> void print(T arr[]) {cerr << "[ "; for (T i : arr) {print(i); cerr << " ";} cerr << "]";} ^~~ A.cpp:16:55: note: suggested alternatives: In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\mingw32\bits\stdc++.h:95:0, from A.cpp:1: c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\valarray:1226:5: note: 'std::end' end(const valarray<_Tp>& __va) ^~~ c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\valarray:1226:5: note: 'std::end' So how to create a debug for array ?
A range-based for loop (for(T i : v) internally uses std::begin and std::end to determine the range it hast to iterate over. These methods work for arrays whose size is fixed at compile time, e.g. int arr[10];, for any standard container, like std::vector, std::list, or any class that has a .begin() and .end()-method that return iterators, I think. However, it does not work for pointers. In fact print(T arr[]) equals print(T *arr). You can't determine the length of an array, when you only got a pointer. You can't even determine wether or not this pointer is pointing to an array. So you can't use range-based for loops with pointers. So how to create a debug for array ? If you want to use dynamically allocated arrays you have to pass the arrays size along template <class T> void print(T v[], size_t size) and use a normal for loop for(size_t i = 0; i < size; i++) { ... } Another possibility is to make a template for array-size, as in this question: Can someone explain this template code that gives me the size of an array?
72,767,708
72,767,787
How can I make a column chart?
I am facing a problem while doing a chart. I would want to output the chart in a same row without changing the code and without making it horizontal. I would wish to use for loop to solve this problem because I can iterate over everything because I have the same elements. The code is displayed below: # include <iostream> using namespace std; class InterestCalculator { protected: float principal_amount = 320.8; float interest_rate = 60.7; float interest = interest_rate/100 * principal_amount; public: void printInterest() { cout<<"Principal Amount: RM "<<principal_amount<<endl; cout<<"Interest Rate(%): "<<interest_rate<<endl; cout<<"Interest: RM"<<interest<<endl; } }; class LoanCalculator : public InterestCalculator { private: int loan_term; int month; float month_payment; public: void displayVariable() { cout<<"Enter loan amount (RM): "; cin>>principal_amount; cout<<"\n\nEnter annual interest rate(%): "; cin>>interest_rate; interest_rate = interest_rate / 100; cout<<"\n\nEnter loan term in years: "; cin>>loan_term; month = loan_term*12; month_payment = (principal_amount*interest_rate + principal_amount) / month; cout<<endl<<endl; } void outputStatistics() { cout<<"Month\tPayment(RM)\tPrincipal(RM)\tInterest(RM)\tBalance(RM)\n"; for(int i = 1; i <=month; i++) { cout<<i<<endl; } for(int j = 0; j <=month; j++) { cout<<"\t"<<month_payment<<endl; } } }; int main() { LoanCalculator obj; obj.displayVariable(); obj.outputStatistics(); return 0; } The output of the abovementioned code: Enter loan amount (RM): 120 Enter annual interest rate(%): 1.2 Enter loan term in years: 1 Month Payment(RM) Principal(RM) Interest(RM) Balance(RM) 1 2 3 4 5 6 7 8 9 10 11 12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 10.12 Process returned 0 (0x0) execution time : 3.940 s Press any key to continue. The desired output: Enter loan amount (RM): 120 Enter annual interest rate(%): 1.2 Enter loan term in years: 1 Month Payment(RM) Principal(RM) Interest(RM) Balance(RM) 1 10.12 2 10.12 3 10.12 4 10.12 5 10.12 6 10.12 7 10.12 8 10.12 9 10.12 10 10.12 11 10.12 12 10.12 Process returned 0 (0x0) execution time : 3.940 s Press any key to continue.
You don't need to undo endl you just need to reorganise your code so that you do things in the correct order in the first place, like this void outputStatistics() { cout<<"Month\tPayment(RM)\tPrincipal(RM)\tInterest(RM)\tBalance(RM)\n"; for(int i = 1; i <=month; i++) { // output one row at a time cout<<i<<"\t"<<month_payment<<endl; } } This code outputs one row at a time, your code outputted one column first and the next column second.
72,768,801
72,768,843
C-Style Character String
I want to connect two C-style character strings and store the result in a dynamic char array. int main() { char word1[] = "hello"; char word2[] = "haha"; auto ptr = new char[20]; strcpy(ptr,strcat(word1,word2)); cout<<ptr<<endl; return 0; } The compiler says there is a "segmentation fault" at the statement strcpy(ptr,strcat(word1,word2));. Why does the compiler say that?
Like this strcpy(ptr, word1); strcat(ptr, word2); You need to use ptr for both operations, the copy and the concatenation. In your version strcat(word1,word2) tries to concatenate word2after the end of word1. But there is no accessible memory there, so you get a segmentation fault.
72,769,594
72,769,668
How to invoke python function in c++ without running script
I'm working on embedded python. However I have a trouble in work. I used 'PyImport_ImportModule' function because I wanted to import python module in C++. Example, # foo.py class foo: def test(self): print("foo.test") foo().test() // main.cpp void main() { PyObject* myModule = PyImport_ImportModule("foo"); if (myModule) { PyObject* func = PyObject_GetAttrString(myModule, "test"); PyObject_CallObject(func, nullptr); } } When i run this main.cpp code, output is not expected result that i thought. I thought this code result is , **console** >> foo.test but actual result is, **console** >> foo.test >> foo.test I think the reason foo.test is called twice is because the 'PyImport_ImportModule' function runs the script. So i wonder how to invoke python function in c++ without running scirt.
Importing a module is the same as "running the script" in Python. All statements are run top-to-bottom, functions, classes are created when their definitions are executed, on the fly. If a module should be used both as a standalone script and as imported module, the canonical way how to do this in Python is wrapping in "ifmain" block # foo.py class foo: def test(self): print("foo.test") if __main__ == "__main__": foo().test()
72,770,137
72,771,645
Can I limit the size of a C++14 Vector?
As the tile says, is there anyway that I can declare a vector in C++ 14 and limit the max number of entries it can hold?
One possible solution would be to create your own Allocator. std::allocator is stateless, but yours could implement the max_size() member function which should return the value of a member variable that carries the max number of elements. An example that will work from C++11 up until at least C++20: template<class T> struct limited_allocator : public std::allocator<T> { using value_type = typename std::allocator<T>::value_type; using size_type = typename std::allocator<T>::size_type; using difference_type = std::ptrdiff_t; using propagate_on_container_move_assignment = std::true_type; using is_always_equal = std::false_type; // not needed since C++23 #if __cplusplus < 201703L using pointer = typename std::allocator<T>::pointer; using const_pointer = typename std::allocator<T>::const_pointer; using reference = typename std::allocator<T>::reference; using const_reference = typename std::allocator<T>::const_reference; template<class U> struct rebind { typedef limited_allocator<U> other; }; #endif // No default constructor - it needs a limit: constexpr limited_allocator(size_type max_elements) noexcept : m_max_elements(max_elements) {} constexpr limited_allocator( const limited_allocator& other ) noexcept = default; template< class U > constexpr limited_allocator( const limited_allocator<U>& other ) noexcept : m_max_elements(other.m_max_elements) {} // Implementing this is what enforces the limit: size_type max_size() const noexcept { return m_max_elements; } private: size_type m_max_elements; }; Since this allocator isn't stateless, you'd better implement the non-member comparison functions too: template< class T1, class T2 > constexpr bool operator==(const limited_allocator<T1>& lhs, const limited_allocator<T2>& rhs ) noexcept { return &lhs == &rhs; } template< class T1, class T2 > constexpr bool operator!=(const limited_allocator<T1>& lhs, const limited_allocator<T2>& rhs ) noexcept { return &lhs != &rhs; } A usage example, in which the vector is allowed to keep 1 element only: int main() { std::vector<int, limited_allocator<int>> vec(limited_allocator<int>(1)); // ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^ try { vec.push_back(1); // one element vec.pop_back(); // zero again vec.push_back(2); // one again vec.push_back(3); // here it'll throw } catch(const std::length_error& ex) { std::cout << "length_error: " << ex.what() << '\n'; } catch(const std::bad_array_new_length& ex) { std::cout << "bad_array_new_length: " << ex.what() << '\n'; } catch(const std::bad_alloc& ex) { std::cout << "bad_alloc: " << ex.what() << '\n'; } } Possible output: length_error: vector::_M_realloc_insert Demo
72,770,474
72,780,687
(C++) Two classes with some common function. Cleanest way to code
I have two classes that has some common functions and some different functions. Let's say class Red{ public: void funcA(); void funcC(); } class Blue{ public: void funcB(); void funcC(); } Note My actual code contains more functions (both common function and non-common one) and I need to make a class for an interface that initialize one of the two classes above. contains the function to run each function in the class above if it is available for that class Here is the example interface.cpp Red *red_object = nullptr; Blue *blue_object = nullptr; void init(int mode){ if (mode == 0) red_object = new Red(); else blue_object = new Blue(); } void run_func_a(){ if (mode == 0) red_object->funcA(); } void run_func_b(){ if (mode == 1) blue_object->funcB(); } void run_func_c(){ if (mode == 0) { red_object->funcC(); } else { blue_object->funcC(); } } The problem is, I think it is very clunky (e.g., run_func_c()) when I have to write it for every function so I want to somehow generalize it, like using inheritance. However, I cannot use it since there is some function that does not exist in both classes. I could fill in an empty function to the one that does not have it but it is not good in the long term. Is there a better way to construct the interface file in a more precise and cleaner way? Edit: I would like to clarify what I imagine in case of inheritance as @AdrianMole mentioned. I will have a base class Colour. class Colour{ void funcC(); } class Red: public Colour{ void funcA(); } But when I want to write the function in interface.cpp, Colour colour_object = nullptr; void init(int mode){ if(mode ==0) colour_object = new Red(); else(mode == 0) colour_object = new Blue(); } void run_func_a(){ colour_object->funcA(); // This will have error } void run_func_c(){ colour_object->funcC(); // This is okay and looks clean. } colour_object->funcA() will raise an error since it doesn't exist on the base class. I can just add funcA() in base class, but imagine if I have like 10 common functions, 10 functions unique to Red and 10 functions unique to Blue. I think that will be a lot of function in base class. (Although if it is the best approach, I might set on this approach)
Use virtual keyword to archive this. Example: class Color { public: void funcColor() { cout<<"Color::funcColor()\n"; } virtual void funcC() { cout<<"Color::funcC()\n"; } }; class Red : public Color{ public: void funcA() { cout<<"Red::funcA()\n"; } void funcC() { cout<<"Red::funcC()\n"; } }; class Blue : public Color{ public: void funcB() { cout<<"Blue::funcB()\n"; } void funcC() { cout<<"Blue::funcC()\n"; } }; int main() { Color *color; Blue blue; Red red; color=&blue; color->funcC(); color=&red; color->funcC(); return 0; }
72,770,927
72,771,041
Having a set of regex and a set of functions, how to link each regex to a specific function and then call that function once you have a match?
// vector of pairs vector<pair<regex, void (*)(string)>> patterns; // store a regex pattern patterns[0].first = pattern; // store a function name patterns[0].second = func1; patterns[1].first = pattern2; patterns[1].second = func2; // take user's input string input; cin >> input; for (int i = 0; i < patterns.size(); i++) { if (regex_match(input, patterns[i].first)) // if the input matches one of the patterns, call the function associated with that pattern { patterns[i].second(input); } } The problem is that I'm getting an error message for patterns[i].second(input); saying that: the expression preceding parentheses of apparent call must have (pointer-to-) function type
Let us first look at your code: I will show you the problems and how to fix it. And then I will show, how it could be optimized further. I will put comments in your code to show the problems: // vector of pairs // *** Here we have the base for a later problem // *** After this line, you will have an empty vector, that has no elements. vector<pair<regex, void (*)(string)>> patterns; // *** The vector is empty. // *** And if you try to access patterns[0] or patterns[1] // *** then you try to acess elements that don't exist. // *** This will cause UB (Undefined Behaviour) // store a regex pattern patterns patterns[0].first = pattern; // store a function name patterns[0].second = func1; patterns[1].first = pattern2; patterns[1].second = func2; // *** all UB (Undefined Behaviour) from here on. // take user's input //*** Please use getline to read a complete line string input; cin >> input; for (int i = 0; i < patterns.size(); i++) { if (regex_match(input, patterns[i].first)) // if the input matches one of the patterns, call the function associated with that pattern { patterns[i].second(input); } } So, obviously, you want to have a std::vector with 2 elements, so that you can use the index operator to fill it. With that the easiest way will be to use std::vectors constructor no. 4 to set aninitial size. This could be done like this: std::vector <std::pair <std::regex, void (*)(std::string&)>> patterns(2); Then your could use the index operator [] to assign values. But most likely, you would use either the std::vectors push_back - function, or an initializer list. So, an intermediate optimized solution could look like: #include <iostream> #include <string> #include <vector> #include <utility> #include <regex> void function1(std::string& s) { std::cout << "Function 1:\t " << s << '\n'; } void function2(std::string& s) { std::cout << "Function 2:\t " << s << '\n'; } int main() { // Pattern and related callback function std::vector <std::pair <std::regex, void (*)(std::string&)>> patterns{}; // Initialize vector patterns.push_back({ std::regex(".*abc.*"),function1 }); patterns.push_back({ std::regex(".*def.*"),function2 }); // Get input from user std::string input{}; std::getline(std::cin, input); // Find a pattern and call the corresponding function for (size_t i{}; i < patterns.size(); ++i) { if (std::regex_match(input, patterns[i].first)) patterns[i].second(input); } } Modern C++ has more nice features, like structured bindings and range based for loops. With that, the code can be made even more readable. #include <iostream> #include <string> #include <vector> #include <utility> #include <regex> void function1(std::string& s) { std::cout << "Function 1:\t " << s << '\n'; } void function2(std::string& s) { std::cout << "Function 2:\t " << s << '\n'; } int main() { // Pattern and related callback function std::vector <std::pair <std::regex, void (*)(std::string&)>> patterns{ { std::regex(".*abc.*"),function1 }, { std::regex(".*def.*"),function2 } }; // Get input from user std::string input{}; std::getline(std::cin, input); // Find a pattern and call the corresponding function for (const auto& [regex, function] : patterns) { if (std::regex_match(input, regex)) function(input); } }
72,771,470
72,771,542
cmake error: "cc: error: unrecognized command line option ‘-std=c++20’; did you mean ‘-std=c++2a’?"
I'm attempting to compile a binary from source, but keep running into an error while doing so. $ cmake --build ./\[binary_dir\]/ [ 0%] Building C object [binary_dir]/CMakeFiles/ZIPLIB.dir/extlibs/bzip2/bcompress.c.o cc: error: unrecognized command line option ‘-std=c++20’; did you mean ‘-std=c++2a’? make[2]: *** [[binary_dir]/CMakeFiles/ZIPLIB.dir/build.make:154: [binary_dir]/CMakeFiles/ZIPLIB.dir/extlibs/bzip2/bcompress.c.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:307: [binary_dir]/CMakeFiles/ZIPLIB.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 Specifically, "cc: error: unrecognized command line option ‘-std=c++20’; did you mean ‘-std=c++2a’?." I suspect this has to do with using the incorrect version of gcc; I have multiple version installed but believe I need to be using the latest, or at least 11.1.0. I have these versions installed: $ ls -l /usr/bin/gcc* lrwxrwxrwx 1 root root 5 Mar 20 2020 /usr/bin/gcc -> gcc-9 lrwxrwxrwx 1 root root 23 May 29 2021 /usr/bin/gcc-10 -> x86_64-linux-gnu-gcc-10 lrwxrwxrwx 1 root root 23 Apr 28 2021 /usr/bin/gcc-11 -> x86_64-linux-gnu-gcc-11 lrwxrwxrwx 1 root root 22 Mar 9 12:57 /usr/bin/gcc-9 -> x86_64-linux-gnu-gcc-9 lrwxrwxrwx 1 root root 8 Mar 20 2020 /usr/bin/gcc-ar -> gcc-ar-9 lrwxrwxrwx 1 root root 26 May 29 2021 /usr/bin/gcc-ar-10 -> x86_64-linux-gnu-gcc-ar-10 lrwxrwxrwx 1 root root 26 Apr 28 2021 /usr/bin/gcc-ar-11 -> x86_64-linux-gnu-gcc-ar-11 lrwxrwxrwx 1 root root 25 Mar 9 12:57 /usr/bin/gcc-ar-9 -> x86_64-linux-gnu-gcc-ar-9 lrwxrwxrwx 1 root root 8 Mar 20 2020 /usr/bin/gcc-nm -> gcc-nm-9 lrwxrwxrwx 1 root root 26 May 29 2021 /usr/bin/gcc-nm-10 -> x86_64-linux-gnu-gcc-nm-10 lrwxrwxrwx 1 root root 26 Apr 28 2021 /usr/bin/gcc-nm-11 -> x86_64-linux-gnu-gcc-nm-11 lrwxrwxrwx 1 root root 25 Mar 9 12:57 /usr/bin/gcc-nm-9 -> x86_64-linux-gnu-gcc-nm-9 lrwxrwxrwx 1 root root 12 Mar 20 2020 /usr/bin/gcc-ranlib -> gcc-ranlib-9 lrwxrwxrwx 1 root root 30 May 29 2021 /usr/bin/gcc-ranlib-10 -> x86_64-linux-gnu-gcc-ranlib-10 lrwxrwxrwx 1 root root 30 Apr 28 2021 /usr/bin/gcc-ranlib-11 -> x86_64-linux-gnu-gcc-ranlib-11 lrwxrwxrwx 1 root root 29 Mar 9 12:57 /usr/bin/gcc-ranlib-9 -> x86_64-linux-gnu-gcc-ranlib-9 If that's the issue, how can I specify which version of gcc to use? Would that happen in the makefile/cmakelist itself, as a path which I need to specify in my environment, or as a flag applied when calling cmake? Or does the error suggest another solution?
Presuming you are in a build directory: You can set CMAKE_C_COMPILER when you run the original call to cmake. cmake -DCMAKE_C_COMPILER=/usr/bin/gcc-11 .. cmake --build .
72,772,356
72,772,616
Passing an object by reference (C++)
I want a method that creates a binary tree from an array and returns nothing. So I would have to work by reference but I am having some troubles with the proper syntax to use. I have obviously tried to search before posting this question, I have seen similar posts but no answer were truly helpfull. Here what i have done so far : My Class : class Node { private: int data; Node* left; Node* right; public: [...] void make_tree(Node* node, int values[], int size); }; The method : // Every operations are done a copy of node, I want them to be done on the original object void Node::make_tree(Node* node, int values[], int size) { if (size <= 0) { return; } else { if (!node) { node = new Node(values[size]); } else if (!node->has_data()) { node->set_data(values[size]); } // recursive call make_tree(node->left, values, size - 1); make_tree(node->right, values, size - 1); } } The call : int main() { int tab[] = { 5,3,4,9,7,6 }; Node* root = new Node(); /* I want "root" to be passed by reference so every modifications are done on the original object and not a copy who will be destroyed at the end of the method scope. */ root->make_tree(root, tab, 6); root->print_tree(); // there is nothing more in root } Since I am already passing a pointer to the object "root", I am confused on how I could do it. Thank you. PS: I am aware that my recursive call does not do what I described it should do. That is a problem for an other time. PPS : first post btw, so if you see something I did wrong, please, tell me.
void Node::make_tree(Node* node, int values[], int size); Node pointer cannot be modified inside the function, as you pass it by value (only the copy is modified). You can use a reference, as suggested in comments : void Node::make_tree(Node* &node, int values[], int size); Or you can also use a pointer to a pointer void Node::make_tree(Node** node, int values[], int size); but there will be more work to modify your code.
72,772,753
72,772,962
organizing my files in C++ , ARGB to RGBA
I'm trying to understand how the hpp, cpp, and main all work together. for this example I'm working on a code that coverts ARGB to RGBA and I'm confused on what to put in each file. This is my code: color.hpp using namespace std; #include <stdio.h> #include <stdio.h> #include <iostream> #ifndef colors_hpp #define colors_hpp /* colors_hpp */ string getHex(); uint32_t fromArgb(); #endif color.cpp #include "colors.hpp" #include <iostream> #include <stdio.h> #include <stdarg.h> #include <stdint.h> template <typename T> struct Color { public: /* Works fine!!! */ Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) { buffer((r << 0) | (g << 8) | (b << 16) | (a << 24)); } Color(const uint32_t argb) { buffer = fromArgb(argb); } inline uint32_t fromArgb(uint32_t argb) { return // Source is in format: 0xAARRGGBB ((argb & 0x00FF0000) >> 16) | //____RR ((argb & 0x0000FF00)) | //_GG_ ((argb & 0x000000FF) << 16) | //__BB_ ((argb & 0xFF000000)); //AA____ // Return value is in format: 0xAABBGGRR } inline uint8_t getRed(void) const { return (buffer >> 0) & 0xFF; } inline uint8_t getGreen(void) const { return (buffer >> 8) & 0xFF; } inline uint8_t getBlue(void) const { return (buffer >> 16) & 0xFF; } inline uint8_t getAlpha(void) const { return (buffer >> 24) & 0xFF; } /* Works fine!!!*/ std::string getHex(void) const { std::string result = "#"; char colorBuffer[255] = {}; // Order is intentionally end to beginning sprintf_s(colorBuffer, 255, "%.2X", getAlpha()); result.append(colorBuffer); sprintf_s(colorBuffer, 255, "%.2X", getBlue()); result.append(colorBuffer); sprintf_s(colorBuffer, 255, "%.2X", getGreen()); result.append(colorBuffer); sprintf_s(colorBuffer, 255, "%.2X", getRed()); result.append(colorBuffer); return result; } private: uint32_t buffer; }; main.cpp int main(int argc, char**argv) { fromArgb(255,255,0,0); getHex(); } I'm not able to understand where to use or call the struct or functions, and i'm really confused on what to put in hpp, cpp, and main files.
Some advice Remove this template <typename T> Move struct Color { ... }; to color.hpp (all of it, you can delete color.cpp, it is not needed). Remove using namespace std; from color.hpp Remove string getHex(); uint32_t fromArgb(); from color.hpp change main to this int main(int argc, char**argv) { Color c; c.fromArgb(255,255,0,0); std::cout << c.getHex() << std::endl; } The main problem seems to be that you don't know how objects work. In order to use the fromArgb and getHex methods you need a Color object. So in my code I declared a Color object like this Color c; and then I used that colour object like this c.fromArgb(255,255,0,0); and this c.getHex(). How to use classes and objects is a more important topic than how to organise your code into headers and cpp files. I haven't tested these changes. If there are any further problems you can't figure out then ask again.
72,773,090
72,774,052
How to properly pass objects across multiple classes in C++
I am mostly self thought with C++ and I have built some large complex codes during my PhD research. One of the issues I have been continuously facing is lack of oversight during development as I am nearly the only one who can code in the entire group. So when I make a "bad" code, there's no one to correct me and make me kick off a bad habit. Question I have regards the following scenario: I need to solve several iterative systems of equations for Physics problem I am studying. The package I built has around 30 classes and when I reviewed my code I noticed that I often unnecessarily copy objects. Consider this example: class A { std::valarray<double> _someArray; public: const double doSomethingComplicated() const; A(const std::valarray<double> &someArray) : _someArray(someArray) {...}; } class B { A _objectA; public: const double doSomethingComplicatedWithObjectA() const; B(const A &objectA) : _objectA(objectA) {...}; } class C { A _objectA; B _objectB; public: const double doSomethingComplicatedWithObjectAandB() const; C(const A &objectA, const B &objectB) : _objectA(objectA), _objectB(objectB) {...}; } Disregard constructor definition in class declaration and what ... code in constructor is. The point is, in more complex classes as B and C, I am making private fields of previously made objects and in their constructors I am making copies of them. A lot of classes in my project do not change, so first time I make class A object, that will be it till the of code. I feel by making class A fields in more complex objects I am unnecessarily creating copies of A, even if it is just a "shallow" copy. I feel I can make much better code if I did this: class B { public: const double doSomethingComplicatedWithObjectA(const A &objectA) const; B() {...}; }; class C { public: const double doSomethingComplicatedWithObjectAandB(const A &objectA, const B &objectB) const; C() {...}; }; In this case I would pass references of objects A and B to methods of more complex classes when something is needed. So there won't be an unnecessary copy and the same chunk of memory would be used. Obvious issue is that I may have 10 methods that need object A, and every time method needs object B, I also need to pass object A in those methods as B depends on A. So I may end up with very messy code, and feel that's not the way to go. What would be a good recommendation to handle code like this? My gut feeling is to use pointers, for instance in class C, I could have A* and B* fields, but I am then unsure how to write constructors properly and if I need to do some destructor management. I clearly don't have much experience with pointer fields, and my fields are either stuff from STL or other libraries, so I rarely need to implement destructors. If C has A* field, how do I make sure its destructor does not delete A object. I only want A* pointer to point to A object wherever it is in memory when first created by some other code, and that code that creates it, will automatically destroy it, not class C, class C just needs to stop pointing at that chunk of memory when C is destroyed. Another feeling I have is to use shared or other types of smart pointers, but I understand those even less. I think the problem is my understanding of pointers and my lack of experience with them. In essence my issue is in understanding C++ as I have no one to ask, and literature feels overwhelming, which is why I am here.
If I understand your concern correctly, you just want to make class C have pointers to A and B, which are the instances that the instance of class C is going to work on. I am going to explain this on example. Consider the following code #include <iostream> class C { int* _num; public: C(int* num) : num(_num) {} // there may be some methods // ... // ... ~C() { std::cout << "C destroyed" << std::endl; } }; int main() { int* my_int = new int(5); // dynamically allocating int variable { // I am going to put C in another scope so that at the end it will be destroyed. C c(my_int); } std::cout << *my_int; delete my_int; return 0; } If you execute the code you will see the following output. C destroyed 5 Which means after the destruction of instance we can still access the memory by my_int pointer, hence the class did not deallocate the memory pointed by _num. Moreover, there is widespread practice of class having pointer to the instance it is going to work on, but deallocating the instance may not be its responsibility. In this case the destructor of C does not deallocate the memory pointed by my_int. If you want to know more about ownership and automated management of memory, I would advise to look up RAII. The smart pointers are implemented using RAII idiom. The first I would advice to look up is std::shared_ptr.
72,773,329
72,777,462
c++17 fast way for trans int to string with prefix '0'
I want to trans an int into string. I known under c++17, a better way is using std::to_string. But now I want to fill the prefix with several '0'. For example, int i = 1, std::to_string(i) is '1', but I want the result is '00001'(total lenght is 5). I know using sprintf or stringstream may achieve that. But which have a better performance or some other way?
If you know something about your domain and don't need to check for errors, nothing gets faster than rolling your own. For example if you know that your int is always in the range [0, 99'999], you could just: std::string convert(unsigned i) { std::string r(5, '0'); char* s = r.data() + 4; do { *s-- = static_cast<char>(i%10 + '0'); i /= 10; } while (i > 0); return r; } General purpose libraries don't have the luxury of making such assumptions.
72,773,640
72,953,110
Write in JSON file - Data not inserted in the correct order
I am creating a desktop app using QT C++ that take a text file and convert it to JSON File like this example: { "102": { "NEUTRAL": { "blend": "100" }, "AE": { "blend": "100" } }, "105": { "AE": { "blend": "100" }, "NEUTRAL": { "blend": "100" } } } This is the code I am using: for (int i = 0; i < output_list1.size(); i++) { if (output_list1[i] == "-") { c_frame++; continue; } if (output_list1[i] != "NEUTRAL") { QJsonObject neutralBlendObject; neutralBlendObject.insert("blend", "100"); QJsonObject phonemeObject; phonemeObject.insert("NEUTRAL", neutralBlendObject); QJsonObject keyBlendObject; keyBlendObject.insert("blend", output_list1[i].split(' ')[1]); phonemeObject.insert(output_list1[i].split(' ')[0], keyBlendObject); mainObject.insert(QString::number(c_frame), phonemeObject); } c_frame++; } jsonDoc.setObject(mainObject); file.write(jsonDoc.toJson()); file.close(); As you can see, I am inserting the NEUTRAL object first but I am getting data not in the correct order, somtimes NEUTRAL is the the first following with the next object and somtimes not. How can I correct this issue?
I did resolve it using rapidjson library instead of QJsonObject Based on this example #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include "rapidjson/filewritestream.h" #include <string> #include "RapidJson/prettywriter.h" using namespace rapidjson; using namespace std; FILE* fp = fopen("output.json", "wb"); // non-Windows use "w" char writeBuffer[65536]; FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); size_t sz = allocator.Size(); d.AddMember("version", 1, allocator); d.AddMember("testId", 2, allocator); d.AddMember("group", 3, allocator); d.AddMember("order", 4, allocator); Value tests(kArrayType); Value obj(kObjectType); Value val(kObjectType); string description = "a description"; //const char *description = "a description"; //val.SetString() val.SetString(description.c_str(), static_cast<SizeType>(description.length()), allocator); obj.AddMember("description", val, allocator); string help = "some help"; val.SetString(help.c_str(), static_cast<SizeType>(help.length()), allocator); obj.AddMember("help", val, allocator); string workgroup = "a workgroup"; val.SetString(workgroup.c_str(), static_cast<SizeType>(workgroup.length()), allocator); obj.AddMember("workgroup", val, allocator); val.SetBool(true); obj.AddMember("online", val, allocator); tests.PushBack(obj, allocator); d.AddMember("tests", tests, allocator); // Convert JSON document to string PrettyWriter<FileWriteStream> writer(os); char indent = ' '; // single space x 4 writer.SetIndent(indent, 4); d.Accept(writer); Thank you all for your time
72,773,647
72,774,212
Converting an unsigned char array to jstring
I'm having issues trying to convert an unsigned char array to jstring. The context is I'm using a shared c library from Java. So I'm implementing a JNI c++ file. The function I use from the library returs a unsigned char* num_carte_transcode And the function I implemented in the JNI C++ file returns a jstring. So I need to convert the unsigned char array to jstring. I tried this simple cast return (env)->NewStringUTF((char*) unsigned_char_array); But though the array should only contain 20 bytes, I get randomly 22 or 23 bytes in Java... (Though the 20 bytes are correct) EDIT1: Here some more details with example JNIEXPORT jstring JNICALL Java_com_example_demo_DemoClass_functionToCall (JNIEnv *env, jobject, ) { // Here I define an unsigned char array as requested by the library function unsigned char unsigned_char_array[20]; // The function feeds the array at execution function_to_call(unsigned_char_array); // I print out the result for debug purpose printf("result : %.*s (%ld chars)\n", (int) sizeof unsigned_char_array, unsigned_char_array, (int) sizeof unsigned_char_array); // I get the result I want, which is like: 92311221679609987114 (20 numbers) // Now, I need to convert the unsigned char array to jstring to return to Java return (env)->NewStringUTF((char*) unsigned_char_array); // Though... On debugging on Java, I get 21 bytes 92311221679609987114 (check the image below) } And sometimes I get 22 bytes, sometimes 23 ... though the expected result is always 20 bytes.
The string passed to NewStringUTF must be null-terminated. The string you're passing, however, is not null-terminated, and it looks like there's some garbage at the end of the string before the first null. I suggest creating a larger array, and adding a null terminator at the end: JNIEXPORT jstring JNICALL Java_com_example_demo_DemoClass_functionToCall (JNIEnv *env, jobject recv) { unsigned char unsigned_char_array[20 + 1]; // + 1 for null terminator function_to_call(unsigned_char_array); unsigned_char_array[20] = '\0'; // add null terminator printf("result : %s (%ld chars)\n", unsigned_char_array, (int) sizeof unsigned_char_array); return (env)->NewStringUTF((char*) unsigned_char_array); // should work now }
72,773,734
72,773,824
C++11 packaged_task doesn't work as expected: thread quits and no output
I've this code snippet: #include<future> #include<iostream> using namespace std; int main() { cout << "---------" << endl; packaged_task<int(int, int)> task([](int a, int b){ cout << "task thread\n"; return a + b; }); thread tpt(move(task), 3, 4); cout << "after thread creation\n"; future<int> sum = task.get_future(); cout << "before join\n"; tpt.join(); cout << "after join\n"; sum.wait(); cout << "after wait\n"; cout << sum.get() << endl; return 0; } It only printed --------- after thread creation task thread then hang for about 2 seconds, and ends. I don't see my packaged_task function execute. It didn't print "after join\n" and "after wait\n" Why my program ended unexpectedly, how to fix?
You're moving the packaged task into the thread and then trying to get the future object from the moved-from task which no longer has any state. For me this throws an exception: https://godbolt.org/z/Gh534dKac terminate called after throwing an instance of 'std::future_error' what(): std::future_error: No associated state You need to instead get the future from the task before moving it into the thread: ... future<int> sum = task.get_future(); thread tpt(move(task), 3, 4); cout << "after thread creation\n"; ... https://godbolt.org/z/xhzKxh96K
72,774,044
72,775,239
C++ type from dtype (how to initialize a cv::Mat from a numpy array)
pybind11 has the following method in numpy.h: /// Return dtype associated with a C++ type. template <typename T> static dtype of() { return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype(); } How do I get the inverse? the C++ type from a variable of type dtype ? EDIT My original problem is that I want to bring an OpenCV image from python to c++ as described here, note that the cast done in this answer is always of type unsigned char*: cv::Mat img2(rows, cols, type, (unsigned char*)img.data()); What I want to do is to use .dtype() to get the "python type" and then do the right cast. Because of this, my function signature takes an py::array as parameter. int cpp_callback1(py::array& img) { //stuff cv::Mat img2(rows, cols, type, (unsigned char*)img.data()); ^^^ Somehow I want this to be variable //more stuff } Maybe I can get the type_id from my dtype?
cv::Mat has a constructor that accepts a void* for the data pointer. Therefore you don't need to convert the dtype into a C++ type. You can simply use: cv::Mat img2(rows, cols, type, (void*)img.data());
72,774,210
72,778,221
sprintf_s problems. It worked on Windows, but not on Xcode
sprintf_s(colorBuffer, 255, "%.2X", getAlpha()); result.append(colorBuffer); The error is: Use of undeclared identifier 'sprintf_s'
sprintf_s is part annex K of the C11 standard, titled "bounds-checking interfaces". Annex K is optional. Annex K hasn't been successful. N1967 Field Experience With Annex K — Bounds Checking Interfaces stated in 1995: Despite more than a decade since the original proposal and nearly ten years since the ratification of ISO/IEC TR 24731-1:2007, and almost five years since the introduction of the Bounds checking interfaces into the C standard, no viable conforming implementations has emerged. The APIs continue to be controversial and requests for implementation continue to be rejected by implementers. The authors even propose: ... that Annex K be either removed from the next revision of the C standard, or deprecated and then removed. The only major compiler to implement it (or part of it) is Visual Studio. No luck with Xcode (based on clang) or gcc.
72,774,285
72,811,024
Abort trap 6 when merging arrays in bottom-up Merge Sort
I was trying to implement Merge Sort (Bottom-up approach) until a mysterious Abort trap occurs: void botup_mergesort(int *arr, int begin, int end) { for (int merge_sz = 1; merge_sz < (end - begin); merge_sz *= 2) { for (int par = begin; par < end; par += merge_sz*2) { const int &sub_begin = par; const int &sub_end = std::min(par + merge_sz*2, end); if (sub_end - sub_begin <= 1) { continue; } const int& m = par + merge_sz; const int &merge_size = sub_end - sub_begin; int *aux = new int[merge_size]; int cnt = -1; int p1 = sub_begin; int p2 = m; while (p2 < end && p1 < m && p2 < sub_end) { if (arr[p1] <= arr[p2]) aux[++cnt] = arr[p1++]; else if (arr[p1] > arr[p2]) aux[++cnt] = arr[p2++]; } while (p1 < m) { aux[++cnt] = arr[p1++]; } while (p2 < sub_end && p2 < end) { aux[++cnt] = arr[p2++]; } for (int i = sub_begin, m_cnt = 0; i < sub_end; ++i) { arr[i] = aux[m_cnt++]; } delete[] aux; } } } void sort(int *arr, int begin, int end) { botup_mergesort(arr, begin, end); } int main() { int arr[] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5}; // int arr2[] = {2, 2, 2, 2, 2, 8, 5, 3, 9, 4, 6, 2, 1, 5, 1, 5, 7}; int n = sizeof(arr) / sizeof(int); cout << "Size: " << n << endl; sort(arr, 0, n); print(arr, n); return 0; } The code works fine for small arrays, i.e int arr2[], but as the array gets bigger, Abort trap comes back. I tried using the debugger and it returned SIGABRT at delete[] aux;. I did a little search on the internet and decided to use std::vector instead of a dynamic array, and it worked. However, I really desired to know what is wrong behind this code. My compiler is Apple clang version 11.0.3 on Visual Studio Code. Thank you for your help! Sorry I've forgetten something, I am a inexperienced college student.
The following change will fix the error: const int& m = std::min(par + merge_sz, end); The code could be a bit faster if a one time allocation of a full sized second array was done, and if the direction of merge was changed on each pass, instead of doing a copy back after each merge. The code would need to detect if the number of passes is odd, where the last merge would put data into the second array, where it would need to copy the data back to the first array one time.
72,774,371
72,778,284
How to compile a Qt program without qtCreator on Windows?
I have read the question Can I use Qt without qmake or Qt Creator? which is basically the same for Linux, and very useful. How to compile a basic program using QtCore (console application, even without GUI) on Windows, without using qmake or qtCreator IDE, but just the Microsoft VC++ compiler cl.exe? For example, let's say we have: #include <iostream> #include <QtCore> int main() { QVector<int> a; // Qt object for (int i=0; i<10; i++) a.append(i); std::cout << "hello"; return 0; } Using: call "C:\path\to\vcvarsall.bat" x64 cl main.cpp /I D:\coding\qt\qtbase-everywhere-src-5.15.5\include fails with: D:\coding\qt\qtbase-everywhere-src-5.15.5\include\QtCore\QtCore(3): fatal error C1083: Cannot open include file: 'QtCore/QtCoreDepends': No such file or directory Indeed this file is not present in the release qtbase-everywhere-opensource-src-5.15.5.zip from https://download.qt.io/archive/qt/5.15/5.15.4/submodules/. TL;DR: More generally, which cl.exe arguments should we use to to able to use all Qt includes, and effectively compile such a minimal project using QtCore?
I finally managed to do it 100% from command line, without the qtCreator IDE, but not yet without qmake. Steps to reproduce: Let's assume Microsoft MSVC 2019 is installed. Install qt-opensource-windows-x86-5.14.2.exe. (This is the latest Windows offline installer I could find), double check that you install at least msvc2017_64. Note: Don't use qtbase-everywhere-opensource-src-5.15.4.zip: using the include subfolder from this package for cl.exe /I ... is not enough. (I thought it would, at first) Create a folder example containing the main.cpp file above Open a command line window in this folder and do: vcvarsall.bat x64 Now either do "c:\path\to\msvc2017_64\bin\qmake.exe" -project to create a example.pro project file or create it manually with: TEMPLATE = app TARGET = qt_example INCLUDEPATH += . CONFIG += console SOURCES += main.cpp Do "c:\path\to\msvc2017_64\bin\qmake.exe". This will create a Makefile file. Run nmake. This is Microsoft MSVC's equivalent of the make tool. Copy c:\path\to\msvc2017_64\bin\Qt5Core.dll into the release folder Run release\example.exe. Working! Addendum: here is solution now for a minimal GUI app: main.cpp #include <QtCore/QCoreApplication> #include <QTextStream> #include <QMessageBox> #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QMessageBox::information(NULL, "Hello", "Hello", "Ok"); return a.exec(); } qt_example_gui.pro TEMPLATE = app TARGET = qt_example_gui INCLUDEPATH += . SOURCES += main.cpp QT += gui widgets Do the vcvarsall.bat x64, qmake, nmake like in the solution above. No be sure you have this file structure: release\qt_example_gui.exe release\Qt5Core.dll release\Qt5Gui.dll release\Qt5Widgets.dll release\platforms\qwindows.dll Run the .exe, that's it!
72,774,495
72,775,174
How to traverse a graph with algorihtm
Need to find how many translators need for two persons to be able talking to each other. Given values are A : 1 2 B : 7 8 C : 4 5 D : 5 6 7 E : 6 7 8 F : 8 9 And the translators which we are looking for are as below B > E Can translate directly, answer : 0 A > B Can't translate, answer : -1 C > F Need 2 translators C (5)> D(6)> E(8)> F(8), answer : 2 D > F need 1 translator D (6)> E(8)> F(8), answer : 1 And the code written is as below but I don't know how to traverse. Down is the graph picture which the nodes are basically A to F and matched them having same number. #include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> using namespace std; #define SIZE 1000 vector<char>* graph; vector<int> v; bool vis[SIZE]{ 0 }; int n = 9; int Search(int start, char ch1, char ch2) { int count = 0; queue<char> v1, v2; v1.push(ch1); v2.push(ch2); for (int i = 1; i < n; i++) { for (int j = 0; j < graph[i].size(); j++) { auto begin = graph[i].begin(), end = graph[i].end(); auto iter1 = find(begin, end, v1.front()); auto iter2 = find(begin, end, v2.front()); auto lang = graph[i][j]; if (iter1 != end && lang != v1.front()) v1.push(lang); if (iter2 != end && lang != v2.front()) v2.push(lang); } } fill(vis, vis + SIZE, false); return count; } int main() { graph = new vector<char>[n+1]; vector<string> people{ { "A 1 2" }, { "B 7 8" }, { "C 4 5" }, { "D 5 6 7" }, { "E 6 7 8" }, { "F 8 9" } }; vector<string> pairs{ {"B E"}, {"A B"}, {"C F"}, {"D F"} }; vector<int> res; for (int i = 1; i <= n; i++) { for (auto item : people) { item.erase(remove(item.begin(), item.end(), ' '), item.end()); for (int j = 1; j < item.size(); j++) { int idx = item[j] - '0'; if(i==idx) graph[i].push_back(item[0]); } } } for (auto item : pairs) { item.erase(remove(item.begin(), item.end(), ' '), item.end()); int count = Search(1, item[0], item[1]); cout << count << endl; } delete[] graph; }
I think your graph construction is wrong, it's not really a graph at all. You need to do some work to translate the input into a proper graph. In your code you've created a mapping from language (1, 2, 3 etc) to translators (A, B, C etc) but really the problem is asking for a mapping from translators to translators (that speak the same language). So your graph should look like this A -> B -> D E F C -> D D -> B C E E -> B D F F -> B E Once you have a graph that connects translators I think you'll find it much easier to traverse. The languages themselves don't matter, all that matters is which translators speak a common language. That's what your graph should show.
72,774,506
72,774,642
std::unique_lock and std::shared_lock in same thread - shouldn't work, but does?
Why is it possible to acquire two different locks on a std::shared_mutex? The following code #include <shared_mutex> #include <iostream> int main(int /*argc*/, char * /*argv*/[]) { std::shared_mutex mut; std::unique_lock<std::shared_mutex> ulock{mut}; if(ulock) std::cout << "uniqe_lock is bool true\n"; if(ulock.owns_lock()) std::cout << "uniqe_lock owns lock\n"; std::shared_lock<std::shared_mutex> slock{mut}; if(slock) std::cout << "shared_lock is bool true\n"; if(slock.owns_lock()) std::cout << "shared_lock owns lock\n"; } when compiled with a g++ 9.4.0 (current available on Ubuntu 20.04.1) g++ -std=c++17 mutex.cpp outputs all cout lines. I.e. the thread acquires both the unique_lock and the shared_lock. As I understand cppreference on the shared_mutex, acquiring the second lock should fail while the first one is still alive. "Within one thread, only one lock (shared or exclusive) can be acquired at the same time." What do I miss here? Why can the shared_lock be acquired even with the previous unique_lock still active?
Also from cppreference: "If lock_shared is called by a thread that already owns the mutex in any mode (exclusive or shared), the behavior is undefined." You have UB; the toolchain is not required to diagnose this, though it might if you enabled your stdlib's debug mode (_GLIBCXX_DEBUG for libstdc++).
72,774,707
72,776,703
How can I catch a unique constraint violation through QT's QSqlDatabase interface?
The title says it all, really. I have a QT application, using the QSqlDatabase interface, and I need to take a different action on a unique key constraint violation as opposed to any other type of error. Currently the backend database is SQLite, if that matters. However, management is talking about switching to MS SQL Server, so if the solution is database-specific, I'll need one for both.
You can use a QSqlQuery::lastError method to check an error occured while INSERT or UPDATE query execution. It returns QSqlError, which has a nativeErrorCode method. I'm not sure, if it contains only a numeric value or a full error description. In common, according to documentation SQLite should return 2067 error, however SQL Server has a different error codes 2601 and 2627, those are table key constraint specific. So, you should check, if the string value of QSqlError::nativeErrorCode contains a database engine specific error code.
72,775,443
72,775,511
Is there a purpose for using a macro that does nothing over an empty macro in c++?
Learning c++ and reading through a project, I found this. #define EMPTY_MACRO do {} while (0) ... #if ASSERTS_ENABLED #define ASSERTCORE(expr) assert(expr) #else #define ASSERTCORE(expr) EMPTY_MACRO #endif What is the purpose of EMPTY_MACRO? Is it unnecessary or is there a reason for it?
It's there so ASSERTCORE(expr); behaves the same with or without ASSERTS_ENABLED. A plain #define ASSERTCORE(expr) would leave behind a lone ; and that would behave differently in some cases.
72,775,454
72,837,741
How to modernize code that uses deprecated NumPy C API?
The following C or C++ code, intended for use in a Python extension module, defines a function f that returns a NumPy array. #include <Python.h> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> PyObject* f() { auto* dims = new npy_intp[2]; dims[0] = 3; dims[1] = 4; PyObject* pyarray = PyArray_SimpleNew(2, dims, NPY_DOUBLE); double* array_buffer = (double*)PyArray_DATA((PyArrayObject*)pyarray); for (size_t i = 0; i < dims[0]; ++i) for (size_t j = 0; j < dims[1]; ++j) array_buffer[j*dims[0]+i] = j+100+i; delete[] dims; return pyarray; } If the #define statement is removed, then the compiler (or preprocessor) raises a warning #warning "Using deprecated NumPy API, disable it with ...". How to modernize the above code? Or how to find the response in the NumPy documentation djungle?
The code is up to date. There is no need for modernization. The code line #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION is required by bad design. See the discussion on the NumPy issue tracker, https://github.com/numpy/numpy/issues/21865.
72,775,490
72,776,032
C++20: Validate Template Bodies Against Concepts
C++20 introduces concepts, which allows us to specify in the declaration of a template that the template parameters must provide certain capabilities. If a template is instantiated with a type that does not satisfy the constraints, compilation will fail at instantiation instead of while compiling the template's body and noticing an invalid expression after substitution. This is great, but it begs the question: is there a way to have the compiler look at the template body, before instantiation (i.e. looking at it as a template and not a particular instantiation of a template), and check that all the expressions involving template parameters are guaranteed by the constraints to exist? Example: template<typename T> concept Fooer = requires(T t) { { t.foo() }; }; template<Fooer F> void callFoo(F&& fooer) { fooer.foo(); } The concept prevents me from instantiating callFoo with a type that doesn't support the expression that's inside the template body. However, if I change the function to this: template<Fooer F> void callFoo(F&& fooer) { fooer.foo(); fooer.bar(); } This will fail if I instantiate callFoo with a type that defines foo (and therefore satisfies the constraints) but not bar. In principal, the concept should enable the compiler to look at this template and reject it before instantiation because it includes the expression fooer.bar(), which is not guaranteed by the constraint to exist. I assume there's probably backward compatibility issues with doing this, although if this validation is only done with parameters that are constrained (not just typename/class/etc. parameters), it should only affect new code. This could be very useful because the resulting errors could be used to guide the design of constraints. Write the template implementation, compile (with no instantiations yet), then on each error, add whatever requirement is needed to the constraint. Or, in the opposite direction, when hitting an error, adjust the implementation to use only what the constraints provide. Do any compilers support an option to enable this type of validation, or is there a plan to add this at any point? Is it part of the specification for concepts to do this validation, now or in the future?
TL;DR: no. The design for the original C++11 concepts included validation. But when that was abandoned, the new version was designed to be much more narrow in scope. The new design was originally built on constexpr boolean conditions. The eventual requires expression was added to make these boolean checks easier to write and to bring some sanity to relationships between concepts. But the fundamentals of the design of C++20 concepts makes it basically impossible to do full validation. Even if a concept is built entirely out of atomic requires expressions, there isn't a way to really tell if an expression is being used exactly in the code the way it is in the requires expression. For example, consider this concept: template<typename T, typename U> concept func_to_u = requires(T const t) { {t.func()} -> std::convertible_to<U>; }; Now, let's imagine the following template: template<typename T, typename U> requires func_to_u<T, U> void foo(T const &t) { std::optional<U> u(std::in_place, t.func()); } If you look at std::optional, you find that the in_place_t constructor doesn't take a U. So... is this a legitimate use of that concept? After all, the concept says that code guarded by this concept will call func() and will convert the result to a U. But this template does not do this. It instead takes the return type, instantiates a template that is not guarded by func_to_u, and that template does whatever it wants. Now, it turns out that this template does perform a conversion operation to U. So on the one hand, it's clear that our code does conform to the intent of func_to_u. But that is only because it happened to pass the result to some other function that conformed to the func_to_u concept. But that template had no idea it was subject to the limitations of convertible_to<U>. So... how is the compiler supposed to detect whether this is OK? The trigger condition for failure would be somewhere in optional's constructor. But that constructor is not subject to the concept; it's our outer code that is subject to the concept. So the compiler would basically have to unwind every template your code uses and apply the concept to it. Only it wouldn't even be applying the whole concept; it would just be applying the convertible_to<U> part. The complexity of doing that quickly spirals out of control.
72,775,755
72,775,909
C++, fast removal of elements from vector by binary index
There are several posts focused on the fast removal of elements given by indices from a vector. This question represents a slightly modified version of the problem. There is a vector of elements: std::vector <double> numbers{ 100, 200, 300, 400, 500, 600 }; and the corresponding binary index: std::vector<bool> idxs{ 0, 1, 0, 1, 0, 1 }; What is the fastest method of removal of elements with the "zero indices" from the vector? It may contain millions of elements. I tried experiments with remove_if(), but this is not correct: numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [](bool b)->bool { return b == 1; }), numbers.end());
Unfortunately there is no automatism for this. You simply have to implement a custom erase function yourself: auto widx = numbers.begin(); for (auto ridx = numbers.cbegin(), auto bidx = idxs.cbegin(); ridx != numbers.end; ++ridx, ++bidx) { if (*bidx) *widx++ = *ridx; } numbers.erase(widx, numbers.end());
72,775,945
72,776,090
using remove method of std::list in a loop is creating segmentation fault
I am using remove() of std::list to remove elements in a for loop. But it is creating segmentation fault. I am not using iterators. Program is given below. #include <iostream> #include <list> using namespace std; int main() { list <int> li = {1, 2, 3, 4, 5}; for(auto x : li) { if (x == 4) { li.remove(x); } } return 0; } In case of iterators, I understand that iterators are invalidated if we remove an element and we need to take care of incrementing iterator properly. But here I am not using iterators and I am using remove() which doesn't return any. Can any one please let me know if we can't use remove in a loop or if there is any issue with the code.
But here I am not using iterators and I am using remove() which doesn't return any. Can any one please let me know if we can't use remove in a loop or if there is any issue with the code. You are mistaken. Range-based for loops are based on iterators. So after this call: li.remove(x); The current used iterator becomes invalid. For example, in C++17, the range-based for loop is defined in the following way (9.5.4 The range-based for statement): 1 The range-based for statement for ( for-range-declaration : for-range-initializer ) statement is equivalent to { auto &&__range = for-range-initializer ; auto __begin = begin-expr ; auto __end = end-expr ; for ( ; __begin != __end; ++__begin ) { for-range-declaration = *__begin; statement } } Pay attention to that. Using the range-based for loop to call the member function remove() does not make a great sense, because the function will remove all elements with the given value. If the compiler supports C++20, you can just write: std::erase( li, 4 );
72,776,522
72,776,628
Boost rotation matrix no match for operator *
I am trying to rotate a vector based on another orientation vector. Elsewhere in the code, this works fine. But here, it fails and Boost complains about an operator error. // (Assume these vectors are filled with useful values) boost::qvm::vec<double, 3> aspectVec; boost::qvm::vec<double, 3> orientation; // Rotate aspect into world coords // Note, orientation already in radians auto rot = boost::qvm::rot_mat_zyx<3>( orientation.a[2], orientation.a[1], orientation.a[0]); boost::qvm::vec<double, 3> aspectRotated; aspectRotated = boost::qvm::normalized(rot * aspectVec); The specific error I get is: myfile.cpp:391: error: no match for ‘operator*’ (operand types are ‘boost::qvm::qvm_detail::rot_mat_<3, double>’ and ‘boost::qvm::vec<double, 3>’) 391 | aspectRotated = boost::qvm::normalized(rot * aspectVec); | ~~~ ^ ~~~~~~~~~ | | | | | boost::qvm::vec<double, 3> | boost::qvm::qvm_detail::rot_mat_<3, double> But I don't understand why. In another file, I have an identical line and it works flawlessly. I'm wondering if it's somehow a missing include? I have both ones I thought were relevant: #include <boost/qvm/mat_operations.hpp> #include <boost/qvm/vec_operations.hpp>
The issue was the includes. I noticed they were the only difference in the code between the two files. I swapped out: #include <boost/qvm/mat_operations.hpp> #include <boost/qvm/vec_operations.hpp> For: #include <boost/qvm/all.hpp> And the problem went away. I'm not really sure why, but it did. I don't like including more than necessary, so if anyone knows a sub-set of this that is more appropriate, please let me know.
72,776,764
72,776,865
Determine data type of items in an STL container in a template method
I'm trying to write a template method to handle items in an STL container. Getting details of the container is easy (and I use a std::enable_if clause to allow this template method to be called only if the container can be iterated over (detects a begin() method.)) I further need to know the data type held by the container. Here's what works: template <typename CONTAINER> std::string doStuff(const CONTAINER & container) { using CONTAINER_TYPE = typename CONTAINER::value_type; } I can use if constexpr within this method to do certain things if I can also determine the type of the things held in the container. Here's code that won't work but is like what I'm trying for: template <typename CONTAINER, typename ITEM> std::string doStuff(const CONTAINER<ITEM> & container) { using CONTAINER_TYPE = typename CONTAINER::value_type; using ITEM_TYPE = typename ITEM::value_type; } It completely makes sense why I can't invoke the method this way, but what could I do (either in invoking the method or with metaprogramming inside the method) to determine the type of the items in the container. I'd like to do it such that it is known at compile time. (I've tried a couple permutations of decltype and invoke_result and tons of searching but nothing is quite working yet.) I've tried for example: using ITEM_TYPE = std::invoke_result<&CONTAINER::begin>::type; Of course, that returns an iterator type which needs to be dereferenced but '*' doesn't seem to work as expected here.
You could use template template parameters: template <template <class, class...> class CONTAINER, class ITEM, class... REST> std::string doStuff(const CONTAINER<ITEM, REST...>& container) { using CONTAINER_TYPE = ITEM; // or `typename CONTAINER<ITEM, REST...>::value_type` // This requires SFINAE to not match `ITEM`s without `value_type`: using ITEM_TYPE = typename ITEM::value_type; //... }
72,777,019
72,777,133
c++ complains about __VA_ARGS__
The following code has been compiled with gcc-5.4.0 with no issues: % gcc -W -Wall a.c ... #include <stdio.h> #include <stdarg.h> static int debug_flag; static void debug(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } #define DEBUG(...) \ do { \ if (debug_flag) { \ debug("DEBUG:"__VA_ARGS__); \ } \ } while(0) int main(void) { int dummy = 10; debug_flag = 1; DEBUG("debug msg dummy=%d\n", dummy); return 0; } However compiling this with g++ has interesting effects: % g++ -W -Wall -std=c++11 a.c a.c: In function ‘int main()’: a.c:18:10: error: unable to find string literal operator ‘operator""__VA_ARGS__’ with ‘const char [8]’, ‘long unsigned int’ arguments debug("DEBUG: "__VA_ARGS__); \ % g++ -W -Wall -std=c++0x <same error> % g++ -W -Wall -std=c++03 <no errors> Changing debug("DEBUG:"__VA_ARGS__); to debug("DEBUG:" __VA_ARGS__); i.e. space before __VA_ARGS__ enables to compile with all three -std= options. What is the reason for such behaviour? Thanks.
Since C++11 there is support for user-defined literals, which are literals, including string literals, immediately (without whitespace) followed by an identifier. A user-defined literal is considered a single preprocessor token. See https://en.cppreference.com/w/cpp/language/user_literal for details on their purpose. Therefore "DEBUG:"__VA_ARGS__ is a single preprocessor token and it has no special meaning in a macro definition. The correct behavior is to simply place it unchanged into the macro expansion, where it then fails to compile as no user-defined literal operator for a __VA_ARG__ suffix was declared. So GCC is correct to reject it as C++11 code. This is one of the backwards-incompatible changes between C++03 and C++11 listed in the appendix of the C++11 standard draft N3337: https://timsong-cpp.github.io/cppwp/n3337/diff.cpp03.lex Before C++11 the string literal (up to the closing ") would be its own preprocessor token and the following identifier a second preprocessor token, even without whitespace between them. So GCC is also correct to accept it in C++03 mode. (-std=c++0x is the same as -std=c++11, C++0x was the placeholder name for C++11 when it was still in drafting) It is also an incompatibility with C (in all revisions up to now) since C doesn't support user-defined literals either and considers the two parts of "DEBUG:"__VA_ARGS__ as two preprocessor tokens as well. Therefore it is correct for GCC to accept it as C code as well (which is how the gcc command interprets .c files in contrast to g++ which treats them as C++). To fix this add a whitespace between "DEBUG:" and __VA_ARGS__ as you suggested. That should make it compatible with all C and C++ revisions.
72,777,348
72,777,381
Why C++ template array length deduction need to be like "f(T (&a)[N]"?
Use C++ template to know the length of C-style array, we need this: #include<stdio.h> template<class T,size_t N> size_t length(T (&a)[N]){ return N; } int main() { int fd[2]; printf("%lld\n", length(fd));; return 0; } It works, prints 2. My question is about the syntax. In the declaration of length, why the parameter should be like (&a)[N], and a[N] doesn't work? If I change to template<class T,size_t N> size_t length(T a[N]){ return N; } gcc will say: template argument deduction/substitution failed: couldn't deduce template parameter 'N' Why need an extra & and a pair of braces around array identifier here, what's the template rule / syntax rule behind this? Appreciate detailed explanations.
In this function declaration template<class T,size_t N> size_t length(T a[N]){ return N; } the compiler adjusts the parameter having the array type to pointer to the array element type. That is this declaration actually is equivalent to template<class T,size_t N> size_t length(T *a){ return N; } On the other hand, the array used as an argument expression in this call length(fd) is implicitly converted to a pointer to its first element. So the compiler cannot deduce the value of the template non-type parameter N. When the parameter is declared as a reference then such an adjustment and implicit conversion as described above do not occur. The reference serves as an alias for the array. Pay attention to that to output objects of the unsigned integer type size_t with the C function printf you need to use the conversion specifier zu instead of lld.
72,777,590
72,777,625
How to use Resources in c++?
I want to put an exe file in my C++ program, but I don't understand how to do it. I am using Visual Studio 2019. I know that it can be done through project resources, but I don't know how to work with it.
Create an .rc file to refer to the desired embedded .exe as an RCDATA resource, eg: MYEXE RCDATA "path\to\file.exe" Add the .rc file to your project. The referred .exe file will then be compiled into your final executable. You can then access the MYEXE resource at runtime using the Win32 FindResource()/LoadResource()/LockResource() functions, or higher-level framework equivalent.
72,777,821
72,778,827
Eigen::Map and dimension change 4 to 3
Context: I want to operate rotations and scaling on an existing array, representing a 4x4 matrix, using Eigen. I don't know how to do it without copying data around: Edit: Input matrix is of type array<double,16> The code: Rotation: Eigen::Map <Eigen::Matrix4d> mapped_data( (double *)&input_matrix ); auto rot = Eigen::AngleAxisf( angle_z, Eigen::Vector3f::UnitZ() ); mapped_data *= rot.matrix(); Scale: Eigen::Map <Eigen::Matrix4d> mapped_data( (double *)&input_matrix ); auto scaler = Eigen::Scaling(sx, sy, sz); mapped_data *= scaler; Obviously it tells me that I cannot do it because of matrices of different sizes. Constraint: Again, I don't want to copy, so Map should be what I am after, but it only allows plain matrices (matrix2x, 3x or 4x) to be used (am I wrong?). Question: How to modify my code to make it work, with no useless copies? Thanks,
Eigen's geometry module has a handy Transform class that helps with this stuff. Something like this should work: using Affine3d = Eigen::Transform<double, 3, Eigen::Affine>; double angle_z = ..., sx = ..., sy = ..., sz = ...; Affine3d transform = Eigen::AngleAxisd(angle_z, Eigen::Vector3d::UnitZ()) * Eigen::Scaling(sx, sy, sz); mapped_data = mapped_data * transform.matrix(); Two notes: Please double-check whether to apply the transformation on the left or right side. I always mess this up but I think the given order is correct (first rotate, then scale) You used AngleAxisf but then want to combine it with a matrix of doubles. I changed everything to doubles for consistency but Eigen::Transform also has a cast method if you really want to compute the rotation at reduced precision
72,778,175
72,778,943
Can I get the memory address on the data from the static JNI field?
Can I get the memory address on the data from the static JNI field? For example, I have 2 situations: First: jclass clazz = ...; jfieldID staticFiled = ...; // static field on java object uintptr_t *staticFiledPtr = ((uint64_t) staticFiled); // get field ptr jboolean *boolPtr = *magic code with static field*; *boolPtr = true; Second: jclass clazz = ...; jfieldID staticFiled = ...; // static field on java object uintptr_t *staticFiledPtr = ((uint64_t) staticFiled); // get field ptr jobject *objectPtr = *magic code with static field*; jobject object = *objectPtr; The examples are very simple. I just want to get the memory address on the static field data, without using GetStaticObjectField and etc. It is possible?
Fields in the JVM have no addresses. There are only references to objects (which are not pointers), and then those references are accessed at a certain offset to read or write a field. This operation might involve un-compressing and adding the reference' value to the heap base address to obtain a temporary memory address. It will also potentially be guarded by GC barriers. i.e. it is not a simple pointer dereference. Of course, outside of this operation the GC is free to move the object around. Since every access is guarded by a GC barrier, even the reference value itself might be stale, since the GC could defer updating the value until just before the access, inside the GC barrier. So, in short, getting the address of a field is not really possible, and reading/writing through that address even less so. At best you can hope to get some ephemeral value which points somewhere into the Java heap.
72,778,474
72,779,009
What are the best sorting algorithms when 'n' is very small?
In the critical path of my program, I need to sort an array (specifically, a C++ std::vector<int64_t>, using the gnu c++ standard libray). I am using the standard library provided sorting algorithm (std::sort), which in this case is introsort. I was curious about how well this algorithm performs, and when doing some research on various sorting algorithms different standard and third party libraries use, almost all of them care about cases where 'n' tends to be the dominant factor. In my specific case though, 'n' is going to be on the order of 2-20 elements. So the constant factors could actually be dominant. And things like cache effects might be very different when the entire array we are sorting fits into a couple of cache lines. What are the best sorting algorithms for cases like this where the constant factors likely overwhelm the asymptotic factors? And do there exist any vetted C++ implementations of these algorithms?
Introsort takes your concern into account, and switches to an insertion sort implementation for short sequences. Since your STL already provides it, you should probably use that.
72,778,797
72,778,802
Resolving apparent circular dependency: class A having a method that takes in class B, while class B having a member of type class A
I have two classes that I want to define, Position and TangentVector, partially given as follows: class Position { public: Position(double x, double y, double z); // getters double x(){ return m_x }; double y(){ return m_x }; double z(){ return m_x }; void translate(const TangentVector& tangent_vector); private: double m_x; double m_y; double m_z; } class TangentVector { public: Tangent(double x, double y, double z, Position position); // getters double x(){ return m_x }; double y(){ return m_x }; double z(){ return m_x }; private: double m_x; double m_y; double m_z; Position m_position; } The key thing to note with the classes is that TangentVector has a member of type Position (TangentVector depends on Position) while Position has a method that takes in an argument of type const TangentVector& (Position depends on TangentVector?). For context's sake, Position is intended to represent a point on the unit sphere, and TangentVector describes a vector tangent to the sphere, with the origin of the vector specified by a Position. Since the definition of a VectorTangent requires a Position to be specified, it seems reasonable to say that VectorTangent depends on Position. However, now I want to define a function that takes a Position on the sphere, and "translates" it along the sphere by a direction and distance given by TangentVector. I would really like this translate method to live in the Position class, since it a function that modifies the state of Position. This would lend itself to the following usage, which I feel is fairly natural: Position position{ 1.0, 0.0, 0.0 }; TangentVector tangent_vector{ 0.0, PI/2, 0.0, position }; position.translate(tangent_vector); // Now { 0.0, 1.0, 0.0 }; However, I fear that this results in some circular dependency. So... Is this case an example of circular dependency? Is this case bad practice? If so, how can this circular dependency be avoided? How can this code be modified such that it is in-line with good OOP practices? (I considered making the Position m_position member a raw pointer instead. In this case, however, I intend m_position to be fully owned by TangentVector, rather than allow the possibility of it being altered external to the class. In the example usage code, I do not want the translate method to modify tangent_vector, which would happen if tangent_vector's constructor took in position as a pointer and stored it as a member.)
class Position takes only a reference to class TangentVector. Therefore you might pre-declare TangentVector as class TangentVector; before the declaration of class Position: class TangentVector; class Position { public: Position(double x, double y, double z); // getters double x(){ return m_x }; double y(){ return m_x }; double z(){ return m_x }; void translate(const TangentVector& tangent_vector); private: double m_x; double m_y; double m_z; };
72,779,101
72,779,145
Why do I have to make a 2d array for this
I was solving a question online on strings where we had to perform run-length encoding on a given string, I wrote this function to achieve the answer using namespace std; string runLengthEncoding(string str) { vector <char> encString; int runLength = 1; for(int i = 1; i < str.length(); i++) { if(str[i - 1] != str[i] || runLength == 9) { encString.push_back(to_string(runLength)[0]); encString.push_back(str[i - 1]); runLength = 0; } runLength++; } encString.push_back(to_string(runLength)[0]); encString.push_back(str[str.size() - 1]); string encodedString(encString.begin(), encString.end()); return encodedString; } Here I was getting a very long error on this particular line in the for loop and outside it when I wrote: encString.push_back(to_string(runLength)); which I later found out should be: encString.push_back(to_string(runLength)[0]); instead I don't quite understand why I have to insert it as a 2D element(I don't know if that is the right way to say it, forgive me I am a beginner in this) when I am just trying to insert the integer... In stupid terms - why do I gotta add [0] in this?
std::to_string() returns a std::string. That's what it does, if you check your C++ textbook for a description of this C++ library function that's what you will read there. encString.push_back( /* something */ ) Because encString is a std::vector<char>, it logically follows that the only thing can be push_back() into it is a char. Just a single char. C++ does not allow you to pass an entire std::string to a function that takes a single char parameter. C++ does not work this way, C++ allows only certain, specific conversions betweens different types, and this isn't one of them. And that's why encString.push_back(to_string(runLength)); does not work. The [0] operator returns the first char from the returned std::string. What a lucky coincidence! You get a char from that, the push_back() expects a single char value, and everyone lives happily ever after. Also, it is important to note that you do not, do not "gotta add [0]". You could use [1], if you have to add the 2nd character from the string, or any other character from the string, in the same manner. This explains the compilation error. Whether [0] is the right solution, or not, is something that you'll need to figure out separately. You wanted to know why this does not compile without the [0], and that's the answer: to_string() returns a std::string put you must push_back() a single char value, and using [0] makes it happen. Whether it's the right char, or not, that's a completely different question.
72,779,225
72,795,934
How to use results from mysql built-in functions when inserting via mysql-x-devapi in C++?
I am using mysql-x-devapi and need to insert a row to a table and put UNIX_TIMESTAMP() of the server in a column: sql_client_.getSession().getDefaultSchema() .getTable("event") .insert("title", "time") .values("event title", "UNIX_TIMESTAMP()") .execute(); This code gives me: CDK Error: Incorrect integer value 'UNIX_TIMESTAMP()' for column 'time' at row 1 How can I do this using xdevapi (not sql command that needs sql string)? I am able to use mysqlx::expr("UNIX_TIMESTAMP()") in set function when updating the table. The same doesn't work with insert and fails with the following error: /usr/include/mysql-cppconn-8/mysqlx/devapi/table_crud.h:157:17: error: ‘mysqlx::abi2::r0::internal::Expression::Expression(V&&) [with V = mysqlx::abi2::r0::internal::Expression&]’ is private within this context 157 | add_values(get_impl(), rest...);
I used mysqlx::expr("UNIX_TIMESTAMP()"): sql_client_.getSession().getDefaultSchema() .getTable("event") .insert("title", "time") .values("event title", mysqlx::expr("UNIX_TIMESTAMP()")) .execute(); then fixed the compile error by touching: /usr/include/mysql-cppconn-8/mysqlx/devapi/table_crud.h replaced: template<typename... Types> TableInsert& values(Types... rest) { try { add_values(get_impl(), rest...); return *this; } CATCH_AND_WRAP } with: template<typename... Types> TableInsert& values(Types&&... rest) { try { add_values(get_impl(), std::forward<Types>(rest)...); return *this; } CATCH_AND_WRAP } /usr/include/mysql-cppconn-8/mysqlx/devapi/detail/crud.h replaced: template <typename... T> static void add_values(Impl *impl, T... args) { Add_value::Impl row{ {}, 0 }; Args_processor<Add_value>::process_args(&row, args...); Add_row::process_one(impl, row.first); } with: template <typename... T> static void add_values(Impl *impl, T&&... args) { Add_value::Impl row{ {}, 0 }; Args_processor<Add_value>::process_args(&row, std::forward<T>(args)...); Add_row::process_one(impl, row.first); }
72,779,255
72,779,290
Getting a specific element from Queue
I have a queue: queue<string> saves. I need to use it's ability to remove elements from the front. Is there a way to get a specific element in the queue like the 5th one? Neither saves.at(4) nor saves[4] works.
The entire point of a queue is you can only see and get the item, if any, waiting at the out end. Anything that allows you to see any other values in the queue is not a queue. Wanting to see inside the queue suggests that you do not want a queue. Try a std::deque instead.
72,779,319
72,779,460
How can you require that a concept parameter is a reference `&` type?
In the following concept implementation struct, String, the operator() method does not take the value Source by reference but still satisfies the concept Consumer. How can I prevent String from being a valid Consumer, specifically by requiring Source source to be a reference &? template <class Type, class Source> concept Consumer = requires(Type type, Source & source, std::ranges::iterator_t<Source> position) { { type.operator()(source, position) } -> std::same_as<Source>; }; struct String { public: std::string operator()(const std::string source, std::string::const_iterator position) { return "test"; } }; int main(const int, const char * []) { String consumer{}; static_assert(Consumer<String, std::string>); auto test = std::string("test"); consumer(test, std::begin(test)); }
You cannot (reasonably) detect if takes a reference parameter. But you can detect if it can take an rvalue: template <class Type, class Source> concept ConsumerOfRvalue = requires(Type type, Source &&source, std::ranges::iterator_t<Source> position) { type(std::move(source), position); }; If the function takes its parameter by &&, by const&, or by value (assuming Source is moveable), then it will satisfy ConsumerOfRvalue. Therefore, you can make your Consumer require that the types not satisfy ConsumerOfRvalue: template <class Type, class Source> concept Consumer = !ConsumerOfRvalue<Type, Source> && requires(Type type, Source & source, std::ranges::iterator_t<Source> position) { { type(source, position) } -> std::same_as<Source>; };
72,779,418
72,779,509
C++ function resolution matches different function when I adjust their sequence
I've got a test program to see how compiler(g++) match template function: #include<stdio.h> template<class T>void f(T){printf("T\n");} template<class T>void f(T*){printf("T*\n");} template<> void f(int*){printf("int*\n");} int main(int argc,char**) { int *p = &argc; f(p); // int* return 0; } It prints int*. Seems the specialized template is the high priority match? Then I switched the function declaration a bit, this time: #include<stdio.h> template<class T>void f(T){printf("T\n");} template<> void f(int*){printf("int*\n");} template<class T>void f(T*){printf("T*\n");} int main(int argc,char**) { int *p = &argc; f(p); // T* return 0; } It prints T*. The only difference between the 2 programs is I changed the function declaration for overloaded "f" a bit, why the result is different?
You have two (overloaded) template functions here, and a third function f(int*) that is specializing one of the template functions. The specialization happens after after the overload resolution. So in both cases you will select f(T*) over f(T). However, in the first case when you have specialized f(T*), you will get the int* specialization. In the second case, when you have specialized f(T), the selected function has no specialization. Remember that you can't partially-specialize a template function, only fully specialize it. If you want f always to print int*, then consider making f(int*) a regular function, rather than a template specialization.
72,779,432
72,779,469
Advice for getting a pointer to an object from a vector stored inside a class
class Element { class Point { private: double x; double y; public: //getters/setters for x and y }; private: std::string name; std::vector<Point> values; public: void insertValue(unsigned int index, double x, double y); ... }; class Collection { private: std::string name; std::vector<Element> elements; public: ... ... Element* elementAt(unsigned int index) const { return const_cast<Element*>(&elements.at(index)); } }; What I need is to get an Element in a certain index from the collection to do operations like Element::insertValues. It is a bad practice doing it as it's done in the Collection::elementAt method (using const_cast)? Is it better to remove the const qualifier from the method? I marked the method const since the method itself does not modify the object.
The usual idiom for this is to have two methods, a const one and a non-const one. In this case one returns a const Element *, and the other one returns an Element *, keeping everything const-correct. const Element* elementAt(unsigned int index) const { return &elements.at(index); } Element* elementAt(unsigned int index) { return &elements.at(index); } Yes, it is true that this leads to some code duplication. Such is life, noone has ever accused C++ of being compact and concise. P.S.: you didn't ask this, but an even better idiom would be to return a reference, rather than a pointer. std::vector::at returns a reference, why shouldn't your pinch-hitter do the same?
72,779,626
72,779,716
Why does std::barrier allocate?
Why does std::barrier allocate memory on the heap while std::latch doesn't? The main difference between them is that std::barrier can be reused while std::latch can't, but I can't find an explanation on why this would make the former allocate memory.
While it is true that a naive barrier could be implemented with a constant amount of storage as part of the std::barrier object, real-world barrier implementations use structures that have > O(1) storage, but better concurrency properties. The naive, constant-storage barrier can suffer from a large number of threads contending on the same counter. Such contention can lead to O(N) runtime to release threads from the barrier. As an example of a "better" implementation, the gcc libstdc++ implementation uses a tree barrier. This avoids the contention on a single counter/mutex shared among all threads, and a tree barrier can propagate the "barrier done, time to release" signal in logarithmic time, at the expense of needing linear space to represent the thread tree. It's not too difficult to imagine enhanced tree-style barrier implementations that are aware of cache/socket/memory bus hierarchy, and group threads in the tree based on their physical location to minimize cross-core, cross-die, and cross-socket polling to the minimum required. On the other hand, a latch is a much more lightweight synchronization tool. However, I'm not quite sure why a latch would be forbidden to allocate - cppreference states, The latch class is a downward counter of type std::ptrdiff_t which would indicate that it should not allocate (i.e. it's just a counter and has no space to hold a pointer to an allocated object). On other hand, [thread.latch] in the standard says nothing more than "A latch maintains an internal counter that is initialized when the latch is created" without forbidding it from allocating.
72,781,255
72,781,527
Can you call a constexpr function to assign a constexpr value with a forward declaration?
I found myself in a weird spot, with the error message "expression did not evaluate to a constant": constexpr uint64 createDynamicPipelineStateMask(); static inline constexpr uint64 dynamic_state_mask = createDynamicPipelineStateMask(); struct CullMode { static constexpr inline bool bIsDynamicState = false; static constexpr inline uint64 mask = 0; }; constexpr uint64 createDynamicPipelineStateMask() { uint64 dynamic_mask = 0; if constexpr (CullMode::bIsDynamicState) dynamic_mask |= CullMode::mask; return dynamic_mask; } Now I guess I could just move the constexpr value to below the definition, but I wanted to know the answer to this question. I know that it's compiler, and not the linker that needs the full definition of the constexpr function, but the compiler has it right below.
I know that it's compiler, and not the linker that needs the full definition of the constexpr function, but the compiler has it right below. The behavior of the program can be understood using expr.const#5 which states: 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: 5.2 an invocation of an undefined constexpr function; (emphasis mine) This means that when writing //------------vvvvvvvvv--------------------------> note the constexpr here, this is not allowed because the call expression cannot be used in a constexpr context until the function is defined static inline constexpr int dynamic_state_mask = createDynamicPipelineStateMask(); the call expression createDynamicPipelineStateMask() at this point is an invocation of an undefined constexpr function and so the initializer is not a constant expression according to the above quoted statement which in turn means that it cannot be used as an initializer to initialize dynamic_state_mask. Basically, you can't use the call expression createDynamicPipelineStateMask() in a constexpr context until the function is defined. But the following is perfectly fine. //------------v-------------------------->note no constexpr here, this is allowed static inline int dynamic_state_mask = createDynamicPipelineStateMask(); This time, even though createDynamicPipelineStateMask() does not evaulate to a constant expression, it can still be used as an initializer to initialize dynamic_state_mask as we have removed the constexpr specifier from the left hand side of the declaration. Basically this isn't a constexpr context and so using the call expression as an initializer is fine. Perhaps a contrived example might clear this further: constexpr int func(); //constexpr int i = func(); //not allowed as the call expression func() at this point is an invocation of an undefined constexpr function and so the initializer is not a constant expression int i = func(); //allowed constexpr int func() { return 4; } constexpr int j = func(); //allowed Demo Clang&Gcc, MSVC Demo
72,781,450
72,925,857
Recursive nested initializer list taking variant
I want an object obj to be initialized from an initializer_list of pairs. However, the second value of the pair is a variant of bool, int and again the obj. gcc reports trouble finding the right constructors I guess. Can I make this work recursively for the following code? #include <utility> #include <string> #include <variant> struct obj; using val = std::variant<int, bool, obj>; struct obj { obj(std::initializer_list<std::pair<std::string, val>> init) { } }; int main() { obj O = { {"level1_1", true }, { "level1_2", 1 }, { {"level2_1", 2}, {"level2_2", true}}}; } gcc 12.1 doesn't get it: <source>: In function 'int main()': <source>:57:93: error: could not convert '{{"level1_1", true}, {"level1_2", 1}, {{"level2_1", 2}, {"level2_2", true}}}' from '<brace-enclosed initializer list>' to 'obj' 57 | obj O = { {"level1_1", true }, { "level1_2", 1 }, { {"level2_1", 2}, {"level2_2", true}}}; | ^ | | | Any hints on what I need to change? EDIT: It seems that the approach using initializer lists is probably not suitable. Maybe there exists a solution using templates which is also appreciated. I know it is possible from nlohmanns json library (see section "JSON as first-class data type"). Also the solution should get by without using heap allocations during the initialization process.
As Igor noted, without any changes to your type or constructor, your code can compile fine with an explicit type specified for your subobject: obj O = { { "level1_1", true }, { "level1_2", 1 }, { "level2", obj { { "level2_1", 2 }, { "level2_2", true }, } }, }; I believe the problem may originate with the particular combination of std::pair, along with a variant that contains an incomplete type. We can observe this by replacing std::pair<...> with our own custom type that lacks any internal storage: struct obj { using mapped_type = std::variant<int, bool, obj>; struct kv_pair { kv_pair(const std::string &k, int v) { } kv_pair(const std::string &k, bool v) { } kv_pair(const std::string &k, const obj &v) { } }; obj(std::initializer_list<kv_pair> entries) { } }; int main(void) { obj _ = { { "level1_1", true }, { "level1_2", 1 }, { "level2", { { "level2_1", 2 }, { "level2_2", false }, }, }, }; return 0; } With this, we get your desired syntax, but lack any implementation. My guess here is that the problem lies with std::pair in combination with std::variant. We can get back our storage by having kv_pair instead be a convenience wrapper over pairs of strings and pointers, i.e. struct kv_pair : public std::pair<std::string, std::shared_ptr<mapped_type>> { kv_pair(const std::string &k, int v) : pair(k, std::make_shared<mapped_type>(v) { } kv_pair(const std::string &k, bool v) : pair(k, std::make_shared<mapped_type>(v) { } kv_pair(const std::string &k, const obj &v) : pair(k, std::make_shared<mapped_type>(v) { } }; So for a full and complete implementation: struct obj { using mapped_type = std::variant<int, bool, obj>; struct kv_pair : public std::pair<std::string, std::shared_ptr<mapped_type>> { kv_pair(const std::string &k, int v) : pair(k, std::make_shared<mapped_type>(v)) { } kv_pair(const std::string &k, bool v) : pair(k, std::make_shared<mapped_type>(v)) { } kv_pair(const std::string &k, const obj &v) : pair(k, std::make_shared<mapped_type>(v)) { } }; obj(std::initializer_list<kv_pair> entries) { for (auto &[k, v]: entries) { _entries.emplace(k, *v); } } protected: std::map<std::string, mapped_type> _entries; }; int main(void) { obj _ = { { "level1_1", true }, { "level1_2", 1 }, { "level2", { { "level2_1", 2 }, { "level2_2", false }, }, }, }; return 0; }
72,781,492
72,790,900
C++20 : Memory allocation of literal initialization of const references
I am trying to optimize for speed of execution a piece of code using the factory design pattern. The factory will produce many objects of a class having some members that are constant throughtout the execution of the program, and some members that are not. I always initialize the constant members with literals. My question is, how is the memory of the constant members going to be managed? Can the compiler optimize the code so that this memory is not allocated/deallocated each time I create/destroy a new object? Ideally I would like the literals to reside on a fixed piece of memory and only the reference to this memory be given to each new object. I would like to avoid using global variables. class Test { private: const std::string &name_; int value_; public: Test(const std::string &name, int value) : name_(name), value_(value) {} }; int main() { Test test1("A", 1); Test test2("B", 2); Test test3("B", 3); Test test4("A", 4); Test test5("B", 5); // etc ... } PS1. notice that in the code snippet the factory pattern implementation is not shown. PS2. Assume GCC 11.2.0 on Linux
The easiest way to get what you want is just to make name_ a const char *: class Test { private: const char *const name_; int value_; public: Test(const char *name, int value) : name_(name), value_(value) {} }; int main() { Test test1("A", 1); Test test2("B", 2); Test test3("B", 3); Test test4("A", 4); Test test5("B", 5); // etc ... } That works because the compiler will optimize strings in memory, so that in this case you don't need multiple copies of "A" in memory. Unfortunately, the code you supply will not work, and leaves a dangling reference. The reason is that the rules for when to extend temporary object lifetimes extend when the reference is bound to a temporary materialization of an object. However, in your code, the temporary std::string is first bound to name, and then name is bound to name_. So the temporarily materialized std::string will be destroyed at the semicolon. One downside to using a const char * is that you will lose length information in the event that you want to embed NUL characters ('\0') in your string. A potential work around would be to take the length of the string as a template argument, as in: class Test { private: const char *const name_; const std::size_t size_; int value_; public: template<std::size_t N> Test(const char name[N], int value) : name_(name), size_(N-1), value_(value) {} };
72,782,114
72,782,532
Get PDF Page size from HDC C++
I want to draw string in 3 location(Top, Center, bottom) of my printing page. I use Gdiplus::RectF and drawstring() to Draw string in the page. for setting string Location I need the Page dimentions. I have to Hook EndPage (Inject DLL) and I have only the HDC. how can I Get the dimentions of printing page? here is my code : int StopPrint::hookFunction(HDC hdc) { sendinfo WaterMarkParams; rpcclient(WaterMarkParams); Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); Graphics grpc(hdc); Gdiplus::FontFamily nameFontFamily(L"Arial"); Gdiplus::Font font(&nameFontFamily, WaterMarkParams.FontSize, Gdiplus::FontStyleBold, Gdiplus::UnitPoint); Gdiplus::RectF rectF(200.0f, 200.0f, 200.0f, 200.0f); Gdiplus::SolidBrush solidBrush(Gdiplus::Color(100, 0, 0, 250)); grpc.DrawString(WaterMarkParams.WaterMarkTxtstr, -1, &font, rectF, NULL, &solidBrush); return getOriginalFunction()(hdc); }
I find The method that is somehow close to the correct answer, it returns dimensions close to correct size, but it's not exact. I get the printable area of the page Width and Height in pixel by GetDeviceCaps(hdc, HORZ|VERT RES) and get Number of pixels per logical inch along the screen Width and Height by GetDeviceCaps(hdc, LOGPIXELS X|Y). Then I divide them and get page size in inch. After that I get pixel per inch by(FLOAT)GetDpiForWindow(GetDesktopWindow()) and convert page size to pixel. It return dimensions but 20 - 30 pixel is smaller than correct page size. Anyway it work for A3-5 page size. The code is: double WidthsPixels = GetDeviceCaps(hdc, HORZRES); double HeightsPixels = GetDeviceCaps(hdc, VERTRES); double WidthsPixelsPerInch = GetDeviceCaps(hdc, LOGPIXELSX); double HeightsPixelsPeInch = GetDeviceCaps(hdc, LOGPIXELSY); float Screendpi = (FLOAT)GetDpiForWindow(GetDesktopWindow()); rectF.Width = (WidthsPixels/ WidthsPixelsPerInch)*Screendpi ; rectF.Height = (HeightsPixels/ HeightsPixelsPeInch)*Screendpi ;
72,782,588
72,783,673
C++ reinitializing variables in a while loop
I have a settings menu that can make the window fullscreen. Most of the menu elements are dependent on the window size. By default, all the menu elements are in the same position they were in before the window was resized (meaning they are not in the position I intend). I understand the positions needs to be recalculated, but in this instance, rather than create a function that resets the position of all the elements in the menu, I've just called the initial load() function. Here is a code summary to help: while(!exit) { switch(State) { case Menu: Menu settings = Menu(...); settings.load() //load here while(State == Menu) { if (window.fullscreen()) { settings.load(); //reload here } }//end while break; default: break; }//end switch }//end while This works, but I'm worried about the memory used by load() when it was first called. The variables use the same name, but are new objects created? Are they overwritten? What happened to the memory that stored the objects when I first loaded the menu? Also, the "What" that is being loaded and reloaded here is a std::unique_ptr<Table> that makes a std::vector<std::pair<std::string, std::unique_ptr<TextRect>>>. Edit: the Settings class: class Settings { Window& _window; sf::RenderWindow& _win; //MainState& _mainState; MenuState& _menuState; Resources& _res; Input& _input; std::unique_ptr<TextRect> SettingsBanner; std::unique_ptr<Table> SettingsMenu; std::unique_ptr<Table> SettingsSave; public: Settings(Window& pWindow ,MainState& pMainState ,MenuState& pMenuState ,Resources& pResources ,Input& pInput ); ~Settings(); void load(); void update(); private: void inputs(); }; and the load(): void Settings::load() { //all kinds of variables SettingsBanner = std::make_unique<TextRect>(_win ,string ,font ,texture ,sf::Color::White ,size ,origin ,position ,sf::Color::White ,outColor ,charSize ,outline ); //more variables SettingsMenu = std::make_unique<Table>(_win ,font ,texture ,textureColor ,fillColor ,outColor ,charSize ,outline ); SettingsMenu->element("FullScreen"); SettingsMenu->element("VSync"); SettingsMenu->element("FrameRate"); SettingsMenu->element("Volume"); SettingsMenu->makeTable("CenterLeft", position, rowCol); //more variables SettingsSave = std::make_unique<Table>(_win ,font ,texture ,textureColor ,fillColor ,outColor ,charSize ,outline ); SettingsSave->element("Save"); SettingsSave->element("Back"); SettingsSave->makeTable("BottomRight", position, rowCol); }// end func
In short: std::make_unique makes new objects, every time it's called. It cannot reuse the memory of the previous object. What would happen if the constructor of the new object throws an exception? It's only in the assignment to the existing unique_ptr that the old object is discarded, and you wouldn't get there if an exception is thrown. This ensures exception safety. You can of course write Settings::load() in different ways. If SettingsBanner is not empty, you can assign to *SettingsBanner instead of calling std::make_unique.
72,783,071
72,783,562
What does field 'predicate' exactly mean in (find_if) function in cpp?
I'm a beginner in c++. I was learning STL especially vectors & iterators uses..I was trying to use (find_if) function to display even numbers on the screen.I knew that I have to return boolean value to the third field in the function(find_if) ..but it gives me all elements in the vector !!! .but,When I used the function (GreaterThanThree) the code outputs the right values without any problem. this is my code: #include <iostream> #include <vector> #include <algorithm> using namespace std; bool EvenNumber(int i) { return i%2==0 } /*bool GreaterThanThree(int s) { return s>3; } */ int main() { vector <int> v={2,1,4,5,0,3,6,7,8,10,9}; sort(v.begin(),v.end()); auto it= find_if(v.begin(),v.end(),EvenNumber); for(;it!=v.end();it++) { cout<<*it<<" "; } return 0; }
You can use std::find_if, but each call finds only one element (at best). That means you need a loop. The first time, you start at v.begin(). This will return the iterator of the first even element. To find the second even element, you have to start the second find_if search not at v.begin(), but after (+1) the first found element. You should stop as soon as std::find_if returns v.end(), which could even be on the first call (if all elements are odd). I.e. for(auto it = std::find_if(v.begin(), v.end(), EvenNumber); it != v.end(); it = std::find_if(it+1, v.end(); EvenNumer))
72,784,373
72,785,068
Weird LTO behavior with -ffast-math
Summary Recently I encountered a weird issue regarding LTO and -ffast-math where I got inconsistent result for my "pow" ( in cmath ) calls depending on whether -flto is used. Environment: $ g++ --version g++ (GCC) 8.3.0 Copyright (C) 2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ ll /lib64/libc.so.6 lrwxrwxrwx 1 root root 12 Sep 3 2019 /lib64/libc.so.6 -> libc-2.17.so $ ll /lib64/libm.so.6 lrwxrwxrwx 1 root root 12 Sep 3 2019 /lib64/libm.so.6 -> libm-2.17.so $ cat /etc/redhat-release CentOS Linux release 7.5.1804 (Core) Minimal Example Code fixed.hxx #include <cstdint> double Power10f(const int16_t power); fixed.cxx #include "fixed.hxx" #include <cmath> double Power10f(const int16_t power) { return pow(10.0, (double) power); } test.cxx #include <iostream> #include <cmath> #include <iomanip> #include <cstdint> #include "fixed.hxx" int main(int argc, char** argv) { if (argc >= 3) { int64_t value = (int64_t)atoi(argv[1]); int16_t power = (int16_t)atoi(argv[2]); double x = Power10f(power); std::cout.precision(17); std::cout << std::scientific << x << std::endl; std::cout << std::scientific << (double)value * x << std::endl; return 0; } return 1; } Compile & Run Compile it with -ffast-math and with/without -flto gives different results With -flto will eventually call the __pow_finite version and gives the an "accurate" result: $ g++ -O3 -DNDEBUG -ffast-math -std=c++17 -flto -o fixed.cxx.o -c fixed.cxx $ g++ -O3 -DNDEBUG -o fdtest fixed.cxx.o test.cxx $ ./fdtest 81 20 1.00000000000000000e+20 8.10000000000000000e+21 $ objdump -DC fdtest > fdtest.dump $ cat fdtest.dump ... 0000000000400930 <Power10f(short)>: 400930: 0f bf ff movswl %di,%edi 400933: 66 0f ef c9 pxor %xmm1,%xmm1 400937: f2 0f 10 05 99 00 00 movsd 0x99(%rip),%xmm0 # 4009d8 <_IO_stdin_used+0x8> 40093e: 00 40093f: f2 0f 2a cf cvtsi2sd %edi,%xmm1 400943: e9 d8 fd ff ff jmpq 400720 <__pow_finite@plt> 400948: 0f 1f 84 00 00 00 00 nopl 0x0(%rax,%rax,1) 40094f: 00 ... Without -flto eventually calls __exp_finite ( as an optimization enabled by -ffast-math if I guess right ), and gives an "inaccurate" result. $ g++ -O3 -DNDEBUG -ffast-math -std=c++17 -o fixed.cxx.o -c fixed.cxx $ g++ -O3 -DNDEBUG -o fdtest fixed.cxx.o test.cxx $ ./fdtest 81 20 1.00000000000000786e+20 8.10000000000006396e+21 $ objdump -DC fdtest > fdtest.dump $ cat fdtest.dump ... 0000000000400930 <Power10f(short)>: 400930: 0f bf ff movswl %di,%edi 400933: 66 0f ef c0 pxor %xmm0,%xmm0 400937: f2 0f 2a c7 cvtsi2sd %edi,%xmm0 40093b: f2 0f 59 05 95 00 00 mulsd 0x95(%rip),%xmm0 # 4009d8 <_IO_stdin_used+0x8> 400942: 00 400943: e9 88 fd ff ff jmpq 4006d0 <__exp_finite@plt> 400948: 0f 1f 84 00 00 00 00 nopl 0x0(%rax,%rax,1) 40094f: 00 ... Question Is the above example expected behavior or is there something wrong with my code that caused this unexpected behavior? Update The same result can also be observed on some other platforms ( e.g. ArchLinux with g++ 12.1 and glibc 2.35 ).
man gcc: To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time. For example: gcc -c -O2 -flto foo.c gcc -c -O2 -flto bar.c gcc -o myprog -flto -O2 foo.o bar.o
72,784,505
72,790,117
Figure out which desktop is active at the moment from the Win service
I have a Win service running under the SYSTEM account. In case the user logs out from the system, the service should detect this and restart particular application on the logon desktop (and stop itself in case than user closing this application manually). The obvious way for me is detect which desktop (Default, ScreenSaver or Winlogon) is active now, but it seems that OpenInputDesktop call doesn't work under the service.
Services run in a different session than users do. Desktops (and other UI resources) belong to the Session they are created in, and cannot be accessed across session boundaries. So the service simply can't directly access a user's desktops at all. To access a given user's desktop, you will have to run a separate process in that user's session, and that process can then communicate back to the service process as needed via any IPC mechanism of your choosing. The service can monitor for SERVICE_CONTROL_SESSIONCHANGE events from the SCM to detect user logins/logouts, and spawn a process in a desired user session by using WTSQueryUserToken() and CreateProcessAsUser().
72,784,535
72,784,598
how to use objects of nested classes
I have a class in a header file: dmx.h // dmx.h #ifndef dmx_h #define dmx_h class Dmx { public: Dmx() { } // some functions and variables void channelDisplay() { } class touchSlider; }; #endif and a nested class in another header file: touchSlider.h // touchSlider.h #ifndef touchSlider_h #define touchSlider_h #include "dmx.h" class Dmx::touchSlider{ private: // some variables public: touchSlider(){ } // some functions void printChannel() { } }; #endif And I initialize my objects in my main file like this: // main.cpp #include "dmx.h" #include "touchSlider.h" Dmx dmx[10] = {Dmx(1), Dmx(2),Dmx(3), Dmx(4), Dmx(5), Dmx(6), Dmx(7), Dmx(8), Dmx(9), Dmx(10)}; Dmx::touchSlider slider[10] = {50,130,210,290,370,50,130,210,290,370}; // functions: Dmx::touchSlider::printChannel() {} Dmx::channelDisplay() {} There is an error message when compiling saying: 'class Dmx' has no member named 'slider' Could someone explain to me how this works correctly?
The problem is that inside the class dmx you already provided a definition for the nested class touchSlider since you used {} and so you're trying to redefine it inside touchSlider.h. To solve this you can provide the declarations for the member functions of touchSlider in the header and then define those member functions inside a source file named touchSlider.cpp as shown below: dmx.h // dmx.h #ifndef dmx_h #define dmx_h class Dmx { public: Dmx() { } Dmx(int){ } // some functions and variables void channelDisplay() { } class touchSlider{ private: // some variables public: touchSlider(); //declaration touchSlider(int);//declaration // some functions void printChannel();//declaration }; }; #endif touchSlider.cpp #include "dmx.h" //default ctor implementation Dmx::touchSlider::touchSlider(){ } //definition void Dmx::touchSlider::printChannel() { } //definition Dmx::touchSlider::touchSlider(int) { } Working demo
72,784,867
72,784,981
private and public, how to make it work properly? -> C++
I have been trying to make the string name; private. I left the correct font below without putting the "string name"; in particular. Well, all attempts failed to put the "string name; private. Does anyone know how I could do this correctly. I'm new to C++ and object-oriented programming. #include <iostream> #include <string> using namespace std; class Aluno { I would like to put string nome; in private, but it is not the same other functions public: string nome; void setIda(int age) { if (age > 0 && age < 60) idade = age; else idade = 0; } int getIda() { return idade; } void setMatr(int matr) { if (matr > 0 && matr <= 1000) matricula = matr; else matricula = 0; } int getMatr() { return matricula; } I would like call string nome; here private: int matricula; int idade; }; However, how could I call the functions string nome; in the int main()? int main() { Aluno *novo_aluno1 = new Aluno(); Aluno *novo_aluno2 = new Aluno(); novo_aluno1->nome = "John Smith"; novo_aluno1->setIda(32); novo_aluno1->setMatr(999); novo_aluno2->nome = "Mary Smith"; novo_aluno2->setIda(21); novo_aluno2->setMatr(998); cout << "\nNome: " << novo_aluno1->nome << "\n"; cout << "Idade: " << novo_aluno1->getIda() << "\n"; cout << "Matricula: " << novo_aluno1->getMatr() << "\n"; cout << "\nNome: " << novo_aluno2->nome << "\n"; cout << "Idade: " << novo_aluno2->getIda() << "\n"; cout << "Matricula: " << novo_aluno2->getMatr() << endl; return 0; }
A private parameter is only accesible from the class it is declared in. If you want to be able to get or set the information stored in a private field you have to make what we call (public) getters and setters methods. private: std::string nome; public: std::string get_nome() { return this->nome; } void set_nome(std::string var) { this->nome = var; } Then your setters and getters can be called in main()
72,785,753
72,786,006
Count maximum consecutive occurrence of a substring in a string, using only basic string operations
int longest_str(std::string str, std::string dna) { int longest_count = 0; int current_count = 0; std::string temp; for (int i = 0; i <= (dna.size() - str.size()); ++i) { if (dna.at(i) == str.at(0)) { for (int j = i; j < i + str.size(); ++j) { temp.push_back(dna.at(j)); } if (temp.compare(str) == 0) { current_count++; temp.clear(); i += str.size(); } else if (temp.compare(str) != 0) { if (current_count >= longest_count) { longest_count = current_count; } temp.clear(); current_count = 0; } } else if (dna.at(i) != str.at(0)) { if (current_count >= longest_count) { longest_count = current_count; } continue; } } return longest_count; } Basically what I'm trying to do here is to loop through the given DNA strand, and when I encounter the first letter of the STR, say at index i, I will append the next i + str.size() letters from the DNA strand to a temporary variable. Then, I will compare that temporary variable with the STR, and if they equal, increase the current count by 1, clear the temporary string, increase the index accordingly, and repeat the process. If the temporary string does not equal the STR, I will clear the string, update longest count up to that point, and reset current count to 0. If I encounter a character that does not equal to the first character of the STR, I will similarly update the longest count, reset current count to 0, and repeat the process. So for example, if the given DNA is "GTATTAATTAATTAATTAGTA", and the STR is "ATTA", this function should return 4. The function has been giving me seemingly arbitrary answers when I tested it against different inputs, so I am not really sure what's going wrong here. My speculation is that there's something wrong with the way I update the longest_count variable. Any suggestions?
The issue is that you do: i += str.size() but you forget that your loop itself is also incrementing i, so you are actually skipping an index. Second issue is that you might exit the loop before if (current_count >= longest_count) { longest_count = current_count; } is executed, if your last match was less than the lenght of the string back (or if your last match ends exactly at the end of the string). Here is a dirty fix of your code: int longest_str(std::string str, std::string dna) { int longest_count = 0; int current_count = 0; std::string temp; for (int i = 0; i <= (dna.size() - str.size()); ++i) { if (dna.at(i) == str.at(0)) { for (int j = i; j < i + str.size(); ++j) { temp.push_back(dna.at(j)); } if (temp.compare(str) == 0) { current_count++; temp.clear(); i += (str.size()-1); } else if (temp.compare(str) != 0) { temp.clear(); current_count = 0; } if (current_count >= longest_count) { longest_count = current_count; } } else if (dna.at(i) != str.at(0)) { if (current_count >= longest_count) { longest_count = current_count; } continue; } } return longest_count; } Other solutions might be cleaner, but hopefully you see the problems now. Another issue that you might have missed is what happens when your string contains overlapping matches. for example: "ATTATTAATTA" With you code you will find the first "ATTA", but you won't find the overlapping "ATTAATTA", so you actually need to rethink your logic anyways Since it seems you didn't fully understand this problem, let's reformulate: When your code reads the string "ATTATTAATTA" it first sees the first "ATTA" and then it goes to the index after that, which is the next "T" and checks the rest of the string. The rest of the string is "TTAATTA" which only contains a single time "ATTA" so your code returns 1, but actually there are two consecutive "ATTA" in that string What you would need to do to get the correct answer is to try starting with every letter, so you would need to first check "ATTATTAATTA" then "TTATTAATTA" then "TATTAATTA" then "ATTAATTA" which finally gets your correct result of 2. Honestly a good idea might be to look at the other answer in this thread and see how he did it, I made sure he looked at this problem too :)