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 |
|---|---|---|---|---|
73,602,012 | 73,602,094 | Remove undefined behavior from overflow of signed integers in constant expressions? | EDIT In the actual example, it appears possible that negative overflow can happen, I've also added an example to demonstrate the error there
I'm using C++20 and trying to convert a library which relies on signed integer overflow in Java and C# into C++ code. I'm also trying to generate the tables it uses at compile ti... | Signed integers have two's complement layout in any implementation that you could name. It's also guaranteed to use two'
s complement layout since C++20.
This means that you can perform your math on unsigned integers and get well-defined overflow behavior that matches what you want your signed integers to do.
#include... |
73,602,071 | 73,602,299 | C++: Function call precedence rules for calling functions on objects of derived classes? | I have a class Iterator, for which I have defined various operator overloads for equality testing (<, <=, >, >=, == and !=) as friend functions. Prototype example:
friend bool operator<(const Iterator &A, const Iterator &B);
class RevIterator inherits (virtually) from Iterator. Naturally, I have had to overload the op... | Your assumption seems correct. You may find rules of overload resolution here https://en.cppreference.com/w/cpp/language/overload_resolution
Here is the part concerning your question:
If Mid is derived (directly or indirectly) from Base, and Derived is derived (directly or indirectly) from Mid
a) Derived* to Mid* ... |
73,602,090 | 73,602,192 | What is the meaning of this expression | I am trying to push a integer that is stored in a string to a stack of type int I was trying to do the same by using stack.push(str[i]) which resulted in some weird values in the final outcome
Github copilot suggeted to do it this way which was succesfull
else
{
temp.push(exp[i]-'0');
}
what ... | The char '0' has ascii value 0x30 (48 decimal).
The char '9' has ascii value 0x39 (57 decimal).
If you do '9' - '0' = 57 - 48 = 9.
So you are converting a digit from its ascii number '9' = 57 to its numeric value 9.
This is often used when fast-converting a string of integers to its numeric value.
|
73,602,986 | 73,603,019 | O(n/2) search in linked list | I'm supposed to make a search method for a linked list that has time complexity O(n/2). What would this look like? I heard that saying O(n/2) is the same as O(n). So is it just a search of all of the linked list's items? Or is there a specific sorting algorithm that would help me do this?
| O(n/2) is indeed equivalent to O(n) so an O(n/2) search is just a linear search i.e. iterate over the list and test each item until you find the one you are looking for.
If you are confused why O(n) and O(n/2) are equivalent, see my answer here.
|
73,603,396 | 73,608,660 | Regex Replace gives different output according to compiler | DEMO
#include <iostream>
#include <regex>
int main() {
std::string bstr = "111111111111111111111111111111111111111110";
std::regex re(".{6}");
bstr = std::regex_replace(bstr, re, "|$00");
std::cout << "bstr: " << bstr << std::endl;
return 0;
}
Why when I compile the same code using visual s... | Short answer: Use $& as a reference to whole match. In this case the correct format string is:
bstr = std::regex_replace(bstr, re, "|$&");
Long answer: Well, this is a rare case where MSVC is right and gcc and clang are (technically) buggy.
C++ default regex flavour is based on ECMAScript standard. This standard ... |
73,603,586 | 73,603,707 | Question about the types `std::basic_string<char>::size_type` and `size_t` in the solution shown below | What is the difference between std::basic_string<char>::size_type and size_t?
Some extra context: I have in mind something like the function in the code example appearing in the SO question linked below. There, an STL array is constructed for the purposes of parsing a string and saving information to said array. In the... | std::string is a typedef for std::basic_string<char> (so you do not need to keep unpacking this).
std::string::size_type is a typedef for an unsigned type large enough to hold the length of any string. Usually this is a typedef for size_t although that is not a guarantee, so very robust code shouldn't rely on it.
std:... |
73,603,794 | 73,679,667 | QtApplication Error. Sound Effect is not a type. M300 error | I am facing a QQmlApplicationEngine failure while loading a component. The error is mentioned below:
QQmlApplicationEngine failed to load component
qrc:/KBButton.qml:54:5: SoundEffect is not a type
The following section of KBButton.qml is failing:
import QtQuick 2.0
import QtMultimedia 5.15
Rectangle {
id: kbButt... | As far as I know, QML should load the right version for you, so in this case it seems a good solution is to remove the version from your import: import QtMultimedia instead of import QtMultimedia 5.15
More info about the import statement: https://doc.qt.io/qt-6/qtqml-syntax-imports.html
|
73,603,798 | 73,603,911 | What is the difference between "sum = addTwoNumbers" to just calling "addTwoNumbers"? | I'm a freshman in IT and we're currently discussing functions in C++. I just want to ask the difference between our prof's code and the other code that I tried.
This is the sample code our prof showed us:
#include<iostream> //header file
using namespace std;
int num1, num2, sum = 0; // global variable
in... | The 1st code is ... confusing. I hope your professor didn't show this code to introduce you to functions, but to rather quiz your already knowledge of functions and global variables.
The confusing part are the global variables and how they are used inside the function. If we remove them and forget about them completely... |
73,603,909 | 73,604,033 | right associativity and order of execution of nested ternary operator in c++ | I have the solution regarding execution order, but I cant understand how right associativity is linked to SCENARIO 2.
a ? b: c ? d : e ? f : g ? h : i // scenario 1 : associativity understood, which is : (a?b:(c?d:(e?f:(g?h:i))))
and
a ? b ? c : d : e // scenario 2 : NOT UNDERSTOOD
From the first answer here, I am ab... | The obvious (and generally best) advice about things like this is "just don't do it."
Other than that, I find the easiest approach to be to think of them like Algol-style ifs. An Algol if was an expression, not a statement, so (much like a conditional, except readable) you could write something like this:
a = if b then... |
73,604,042 | 73,609,086 | Compiling Rust that calls C++ to WASM | I've found this How do I use a C library in a Rust library compiled to WebAssembly?, but this relies on wasm-merge, which has been discontinued. My problem is the following, I have some C++ code that I would like to call from Rust in order to have the option to compile the resulting package either to native code for us... | (This is not really a full answer, but too long for a comment.)
I can compile your example with
cc::Build::new()
.archiver("llvm-ar") // Takes care of "archive has no index" - emar might be an alternative
.cpp_link_stdlib(None) // Takes care of "unable to find library -lstdc++"
… // rest of your flags
but I'm no... |
73,604,153 | 73,629,351 | How to use an external DLL in a winrt component | I'm trying to use an external DLL in a winrt component. To be specific I built https://github.com/webview/webview and got the required DLLs but when trying to add a reference to these DLLs I get "The DLL is not a type or version current project can use". Now I know that Winrt components can use a winmd file as a refere... | Just to Answer this question. I was trying to use a set of APIs in WinRT specific only to Win32 API. And that caused including the headers and lib to fail. Some of these APIs are the likes of SetDPIProcessAware. Otherwise you should follow this guide How to add additional libraries to Visual Studio project? to include ... |
73,604,422 | 73,604,975 | Including a locally installed library in Arduino | How do I include a local file? This is my project structure (with multiple sketches):
(project root)
- some_config.json
- SketchOne/
- SketchOne.ino
- SketchTwo/
- SketchTwo.ino
- lib/
- lib_1/
- some.h
From SketchOne/SketchOne.ino, I want to include lib/lib_1/some.h... | In Arduino projects are called "sketches". The name of the main ino file of the sketch must match the name of the sketch folder. CLI builds one sketch at time.
Sketches are in file system organized into a folder called "sketchbook". The sketchbook folder should containing a special folder named "libraries". Folders in ... |
73,604,455 | 73,604,596 | Error when building FLTK: Configure could not find required X11 libraries | I am having trouble getting FLTK set up. I am currently using windows and trying to built it with msys2. Whenever I try to configure it with ./configure I get this error:
configure: error: Configure could not find required X11 libraries, aborting.
Here is the full stack trace: https://pastebin.com/raw/YeA72wYr
I tried... | See this GitHub issue, where jputcu could workaround the issue by passing --build=mingw32 to the configure script.
You can read the rest of the GitHub issue to learn more, or subscribe to it follow discussion. Feel free to participate there.
|
73,604,587 | 73,604,609 | How to keep threads untangled when changing vector? c++ | This program will crash cause the threads are tangled... One could be pushing while the other is trying to erase.
How can I make this work?
#include <thread>
#include <vector>
using namespace std;
vector<int> v_test;
void push()
{
v_test.push_back(0);
}
void erase()
{
if (v_test.size() > 0)
{
v_... | You need to synchronize the threads so they coordinate their access to the vector. For example, by using a std::mutex, eg:
#include <thread>
#include <mutex>
#include <vector>
using namespace std;
vector<int> v_test;
mutex m_sync;
void push()
{
lock_guard<mutex> lock(m_sync);
v_test.push_back(0);
}
void eras... |
73,605,178 | 73,605,219 | C++ function pointer at declaration and argument | I am confused about using C++ function pointers.
using fn_p1 = void(int); // function pointer
using fn_p2 = void (*)(int);
void functional(fn_p1 f) {
f(1);
}
void callback(int value){
// do something
}
int main() {
fn_p2 f = callback; //works
fn_p1 f1 = static_cast<fn_p1>(f); //does not work
fn_... | The most useful error that the IDE should give you is on the line fn_p1 f2 = callback;:
Illegal initializer (only variables can be initialized) [illegal_initializer]
(This is the message I get from clangd.)
That means literally that an entity of type void(int) (or more in general someReturnType(someArgTypes...)) is n... |
73,605,354 | 73,608,754 | Call a derived class' (non-virtual) function in the base class' Destructor | Suppose we have the following class template:
template<typename T>
class Object
{
public:
Object() = default;
Object(const Object&) = delete;
Object(Object&& other) noexcept
{
if (this != &other)
{
static_cast<T*>(this)->Release();
m_Id = std::exchange(other.m_Id,... | Short answer: Yes, this is undefined behaviour, don't do that.
Long answer:
The destruction of VertexBuffer invokes first ~VertexBuffer() and then invokes ~Object<VertexBuffer>() afterwards. When ~Object<VertexBuffer>() is invoked the VertexBuffer "part" of the object has already been destroyed, i.e. you are now doing ... |
73,605,841 | 73,605,879 | std::pair returned by std::transform resulting in segfault | I'm trying to transform a vector of strings to a vector of pairs of strings, and I was getting segfault. I've tried to narrow it down to a simple test case (below), and I'm sure it's likely to do with the memory allocation:
#include <string>
#include <vector>
#include <utility>
std::pair<std::string, std::string>
newP... | The vector pairs is empty, and pairs.begin() will return the pairs.end() iterator which can't be dereferenced.
Set the size of pairs to the same size as vec before calling transform:
pairs.resize(vec.size());
std::transform(vec.cbegin(), vec.cend(), pairs.begin(), newP);
An alternative that has been mentioned is to p... |
73,606,411 | 73,607,379 | I'm writing a c++ mandelbrot generator but I need to work with HSV | I'm starting with a black cv::Mat image but I would like to add HSV to it. How do I achieve this??
int RE_START = -2;
int RE_END = 1;
int IM_START = -1;
int IM_END = 1;
int MAX_ITER = 80;
int mandelbrot(std::complex<double> c){
std::complex<double> z{0,0};
int n = 0;
while (abs(z) <= 2 && n < MAX_ITER){
... | There were numerous issues in you original code, and there are still quite a few in your current one.
To name some:
cv::Mat constructor expects first the height, then the width.
cv::Mat::at method expects first the y coordinate, then the x.
The final color conversion should be COLOR_HSV2BGR not COLOR_BGR2HSV.
mandelbr... |
73,606,569 | 73,606,662 | How do I change Clang's default include path on Windows | I failed to find system interal header files (like <iostream>).
I can pass arguments to compile every time, but is there a way to change the default includes?
C:\WINDOWS\system32>clang++ -v -c -xc++ nul
clang version 16.0.0 (https://github.com/llvm/llvm-project.git e529c0a2a03fb4eb0ddffafe0ddc7a02059f74cc)
Target: x86_... | The trick I use with GCC, which should also work with Clang, is using the environment variables C_INCLUDE_PATH/CPLUS_INCLUDE_PATH for compiler include paths and LIBRARY_PATH for linker library paths.
|
73,606,971 | 73,607,129 | What the meaning of mark a lambda capturing this as mutable in C++? | I found following code in a raft implementation.
[this](ptr<resp_msg>& resp, const ptr<rpc_exception>& e) mutable {
this->handle_peer_resp(resp, e);
}
When we capture this in a lambda expression, we have already be allowed to modify the value of member or call member function (as shown following).
#include <... | In this
std::function<void(int)> func = [this](const int & b) mutable {
a = 10;
this->print(b);
};
there is nothing mutating the lambda and removing mutable would be the reasonable thing to do.
I therefore made a pull request in the Cornerstone repo to remove mutable from the lambdas that don't mutate, which h... |
73,607,289 | 73,654,370 | How to configure Visual Studio Code so that it selects an already opened file in a different split view instead of opening it again in the same view? | I often use split view in Visual Studio Code, e.g., showing a C++ header file in the left view and the associated source file in the right view. What I often do is use the command Go to Definition (default key binding F12) in the header file (which is open in the left view). And then Visual Studio Code goes on to open ... | Visual Studio Code provides the following option which enables the desired behavior:
Reveal If Open
Controls whether an editor is revealed in any of the visible groups if opened. If disabled, an editor will prefer to open in the currently active editor group. If enabled, an already opened editor will be revealed inste... |
73,607,462 | 73,607,780 | Itoa stopping strcat from properly appending | I am trying to append a series of char arrays in Arduino C++. I have a char array "outputString", and a series of other char arrays that I with to append with via strcat. I also have a checkSum generator that generates the checksum and I used Itoa to convert the checksum value from an int into a base16 character array ... | The char outputString[] = "TOSBC_"; declaration gives the array just enough space to hold the initializer string; that is, the size of the array will be determined from the number of elements in the string literal – which will 7 (the 6 visible characters plus a nul terminator).
Thus, attempting any strcat() on that wil... |
73,608,580 | 73,608,938 | Quick sort Hoare's partition not working when choosing last element as pivot | I'm learning about quick sort and have been having trouble for days with this problem.
I implemented Hoare partition algorithm according to the algorithm on wikipedia: https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme
// Sorts a (portion of an) array, divides it into partitions, then sorts those
algorithm ... | TL;DR
The implementation you use may not choose the final element as a pivot.
Explanation
You need to carefully read the whole description of the algorithm. Specially, note the following quote from the section you linked:
The division returned is after the final position of the second pointer, so the case to avoid is ... |
73,608,886 | 73,609,839 | Where to find BGI file? | I am trying to plot circle using graphics.h library but all the tutorials and examples I have seen had "C:\TurboC\BGI" in the initgraph() function. As long I understand, the mentioned path leads to the graphics driver, but in my my PC I was unable to find any BGI file.
I am using mingw-w64 environment on visual studio ... | Go to https://github.com/ananay/turboc OR download Turbo C++ software then use the installation location (which is C:/ in above example) /TurboC/BGI
BGI files come with Turbo C++
|
73,609,126 | 73,610,015 | Is there any C++ counterpart for Borland C++ Builder 5's dir.h header? | I need to adapt a file written in Borland C++ Builder 5 to be usable in MS Visual Studio 2022. One of the files heavily utilizes the dir.h library, which, as far as I can tell, is a C library exclusive to Builder. The source files are available, however they have a lot of dependencies and, as I've mentioned, are writte... | The functions in dir.h are mapping quite direct to Win32 API calls of fileapi.h. You could use this header for a quick port.
For a modernization, it might be the best idea to re-write the code using std::filesystem. There is hardly any sensible C++ library with such a C-like API.
Well, there are the modernized Embarcad... |
73,609,369 | 73,609,684 | How can I save Checkbox selection in qt c++? | I am trying to develop an application with QT C++. I added a checkBox. How can I make my checkBox be in the last selection when I close my app and open it again. For example, if the checkbox was selected before the application was closed, I want it to be selected when the application runs again. If it wasn't selected b... | Read the value of the checkbox when your app shuts down. Save the value somewhere, like; QSettings, a custom file, windows registry, etc. When your application starts, read the stored value and set the checkbox state to match.
|
73,612,148 | 73,612,182 | Did I just change const value in C++ using refrence? | Code:
#include <iostream>
int main() {
int a = 137;
const int &b = a;
std::cout << a << " " << b << std::endl; // prints 137 137
a++;
std::cout << a << " " << b << std::endl; // prints 138 138
}
The value of variable b becomes 138 after a++ statement, although it's declared as const Shouldn't this be not ... |
Shouldn't this be not allowed?
It's fine. Your code only prevents the b reference from changing the value, but the original variable a doesn't have such a restriction, so it can be freely changed.
|
73,612,230 | 73,612,864 | Cross-compiling c++ with sdl on linux | I'm on Arch Linux, and I have a C++ SDL2 program, contained in single main.cpp file, and I compile it for Linux with such command:
g++ main.cpp -lSDL2 -lSDL2_image
Now I wanna compile it for windows. Any advice on what should I do?
| I suggest my own tool, quasi-msys2, which lets you reuse the precompiled SDL2 for MinGW provided by MSYS2 (and more).
Install Clang, LLD, make, wget, tar, zstd, gpg.
git clone https://github.com/HolyBlackCat/quasi-msys2
cd quasi-msys2/
make install _gcc _SDL2 _SDL2_image
env/shell.sh
win-clang++ main.cpp `pkg-config --... |
73,612,303 | 73,612,370 | How to clear a `priority_queue` that uses user-defined compare? | How to clear a priority_queue that uses user-defined compare?
From std::priority_queue documentation, I reduced the use of priority_queue to the case I need (= queue with user-defined compare)
>> cat test.cpp
#include <functional>
#include <queue>
#include <vector>
#include <iostream>
#include <utility>
auto queue_cm... | Not in C++17.
C++20 gives capture-less lambdas a default constructor. But in earlier language versions, the constructor is deleted.
Really, you should not be using a lambda. Just use a named struct.
|
73,613,276 | 73,613,327 | Why is friend function showing me error that member x and y are private? | Somebody please help me as I can't understand why the compiler is throwing me an error that members x and y are inaccessible even though I have given the friend function declaration?
#include<iostream>
using namespace std;
#include<math.h>
class die;
class point{
int x , y;
public:
friend int die :: dist(poi... | You cannot use incomplete names in nested specifiers use . I.e., here: friend int die::dist(point, point).
You cannot refer to a name that hasn't been declared. It's not enough to know that die exists. You also need to know that die::dist exists. In your original snippet, simple class die; does not say anything about d... |
73,613,371 | 73,613,470 | Conditionally initialize an array | I want an array to have two different values, based on a condition. I can initialize the array inside the condition with the values i want.
if (myCondition == 0)
{
byte my_message[8] = {0x00, 0xAB, 0xEE, 0xFF, 0x00, 0x01, 0x0A, 0x0B};
}
else if (myCondition == 1)
{
byte my_message[8] = {0x11, 0xA1, 0xBC, 0x71, 0x00... | If my_message isn't changed, you could use a pointer instead of an array.
const byte my_messages[2][8] = {
{ 0x00, 0xAB, 0xEE, 0xFF, 0x00, 0x01, 0x0A, 0x0B },
{ 0x11, 0xA1, 0xBC, 0x71, 0x00, 0x02, 0x94, 0x10 },
};
const byte *my_message = my_messages[ myCondition ];
If you need to be able to change my_array, I'... |
73,613,566 | 73,613,593 | Changing a Macros in another C++ file | I have a C++ file that uses functions defined in another C++ file.
Let's say I am working with main.cpp and func.cpp.
func.cpp
#define SIZE 32
bitset<SIZE> functionA(int a)
{
Code;
}
and I have main.cpp
main.cpp
#include "func.cpp"
int main(void)
{
int a;
cin >> a;
bitset<64> out;
out = function... | You cannot change the definition of SIZE to be used with bitset<SIZE> without changing func.cpp. It is not possible.
Do not use a macro.
Make functionA a function template:
template <size_t SIZE = 32>
bitset<SIZE> functionA(int a)
{
Code;
}
Then in main call it with the SIZE you want:
int main(void)
{
int a;
... |
73,613,579 | 73,614,247 | Error while trying to compile an c++ sdl2 program with mingw | Basically, when I'm trying to compile my program for windows on linux, I get such an error:
/usr/lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld: ../libs/SDL2-2.24.0/x86_64-w64-mingw32/lib//libSDL2main.a(SDL_windows_main.o): in function `main_getcmdline':
/Users/valve/release/SDL/SDL2-2.24.0-s... | Oh, okay I was just dumb, didn't pass name of main.cpp to the compiler.
|
73,614,069 | 73,614,733 | parameter isn't destroyed when argument throws exception? | Consider the following toy code:
class X {};
class Y {
public:
Y() { cout << "Y ctor\n"; }
~Y() { cout << "Y dtor\n"; }
};
int gun() {
throw X{};
return 42;
}
void fun(Y yy, int i) {}
int main()
{
Y a;
cout << "--------\n";
try
{
fun(a, gun());
}
catch (const X&)
... | There are no sequencing rules between the argument expressions in a function call and/or the initialization of function parameters until C++17. Since C++17 there are some rules which however still do not establish any ordering between the individual arguments.
As a consequence only the indeterminate sequencing rules fo... |
73,614,093 | 73,614,196 | Conversion from initializer_list<const char*> to initializer_list<string> in vector constructor | std::vector‘s initializer list constructor has the form
vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
What makes an initialization like std::vector<string> vec{ “foo”, “bar” }; possible? Why does the constructor accept an std::initializer_list<const char*>, even though the std::vectors... | I think you should refer to this section of the C++ 17 Standard (11.6.4 List-initialization)
5 An object of type std::initializer_list is constructed from an
initializer list as if the implementation generated and materialized
(7.4) a prvalue of type “array of N const E”, where N is the number of
elements in the initi... |
73,614,571 | 73,621,964 | how to split log messages into file and screen in wxwidgets | When I read the WxWidgets documentation, I get the impression that the developers wrote it just for themselves, just to remember what they did 20 years ago.
Regardless, I figured out how to send log messages to a file:
wxLog::SetActiveTarget(new wxLogStderr(fopen(logPath + "/wxApp.log", "w + ")));
and also I figured o... | I may be missing something but this seems very simple?
For example, this could be the simplest possible log target which logs some messages into a wxTextCtrl and all of them into a wxFFile.
#include <wx/wx.h>
#include <wx/ffile.h>
class MyLogTarget : public wxLog
{
public:
// textCtrl must have longer lifetime tha... |
73,614,980 | 73,615,142 | Why does reinterperet cast work on pointers and static doesn't | I'm learning about type casting and finding it pretty tough to understand it.
So from what I've learned. You cannot static cast pointers of one type to another. I don't know exactly why. Because you can static cast an int to a char which has there own address in memory so its super confusing me as to why you cannot do ... | Taking this one question at a time:
<int *>something // what is the * inside of the <int> meaning?
When you are casting, what you put in the angle brackets is the type, int* (or int *) is a pointer to an integer. This is often confusing for those new to C++ because you also use the * operator to dereference a pointer, ... |
73,615,389 | 73,615,430 | Implement a virtual function for two derived classes, that is the same except for one variable Type | I have an abstract class Node that can either be a Leaf or a NonLeaf. I have written a large function SplitNode. The problem is, this function is basically the same for a Leaf as for a NonLeaf. The only difference being that it operates on the entries vector for Leafs, as opposed to the children vector, for NonLeafs. T... | This is a textbook case for a template function. Presuming that the common logic freestanding logic whose only dependency is the vector itself:
template<typename T>
void doSplitNode(T &entries_or_children)
{
for (auto &entry_or_child:entries_or_children)
{
auto &the_r=entry_or_child->the_r;
// Here's... |
73,615,507 | 73,615,651 | How to transfer a mutex containing object from one function to another? | #include <mutex>
class ConcurrentQueue {
// This class contains a queue and contains functions push to the queue and pop from the queue done in a thread safe manner.
std::mutex m;
};
class Producer {
// This class contains several methods which take some ConcurrentQueue objects and then schedule tasks ont... | If you don't want your ConcurrentQueue class to be copyable, then don't pass it by value; use pass-by-reference (i.e. arguments of types const ConcurrentQueue & or ConcurrentQueue &) instead.
OTOH if you actually want your ConcurrentQueue class to be copyable (and you should carefully consider whether or not allowing t... |
73,615,686 | 73,618,555 | Does an implementation that returns fundamental types by value using registers do "temporary materialization"? | (c++20; Working Draft N4868)
[stmt.return]/2 says that the return statement initializes the glvalue result or prvalue result object by copy initialization
the return statement initializes the glvalue result or prvalue result object of the (explicit or
implicit) function call by copy-initialization (9.4) from the opera... |
Does an implementation that returns fundamental types by value using registers do "temporary materialization"?
Yes.
Does implementation like that for fundamental types (int, double, etc.) uses the [class.temporary]/1.2 as source?
[class.temporary]/(1.2) is a non-normative reference to [class.temporary]/3, and an im... |
73,616,803 | 73,617,300 | Clang partial class template specialization error | I've the following simple c++20 test:
#include <type_traits>
/////////////////////////////////////// constraints
template <typename Type> concept isConst = ::std::is_const_v<Type>;
template <typename Type> concept isNotConst = !isConst<Type>;
/////////////////////////////////////// class decleration
template <typen... | If there's no reason that you must use concepts, you can use a pre-C++20 way to implement it.
template <typename T, typename = void>
class TestRef;
template <typename T>
struct TestRef<T, std::enable_if_t<std::is_const_v<T>>> {
explicit TestRef(T& value) noexcept;
};
template <typename T>
struct TestRef<T, std::e... |
73,617,065 | 73,628,720 | Overloading conversion ctor and conversion operator in `To to = from;` and `To to = {from};` | In brief
When I learned about C++ initialization these days, I found To to = from; behaves differently from To to = {from};, where from is of another type From:
If conversion constructor To::To(From &) and conversion operator From::operator To() are provided, both of them will be considered for To to = from;, which wil... | To to = from; is copy-initialization. It falls under [dcl.init.general]/16.6.3, according to which
... user-defined conversions that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated ... and the best one is chosen through overload... |
73,617,081 | 73,617,792 | Will the compiler ever use the move constructor to move a named variable that is about to go out of scope? | consider function void foo() and class myclass
class myclass { /* some data members, including pointers, and a move constructor */ };
void foo()
{
myclass myvar = myclass(...); // foo() allocates space on the stack for sdlv
// then passes address in %rdi to constructor
/* ... | myclass myvar_copy = myvar; is copy initialization where myvar is an lvalue. The copy constructor has a parameter of type const myclass& and the move constructor has a parameter of type myclass&&.
Now, since the argument that we're passing is myvar which is an lvalue only the copy constructor can be used since the mov... |
73,617,170 | 73,618,663 | Why SFINAE has different behavior with gcc <11 vs >12? | I saw this example of using SFINAE to check if a type is streamable here. However, I noticed that it is not portable, i.e. returns different results for templated types with different compilers. I'd be glad for any tips to understand the problem here.
The code below returns true, false with any version of clang++ and G... | operator<<(std::ostream& os, const std::vector<T>& v) won't be found by ADL (for std::vector<int>, it would for std::vector<C>) (and so need to be declared before usage to be usable).
That is why correct answer is true, false.
previous version of gcc misbehave on this.
Note: It is discouraged to overload operator for t... |
73,617,302 | 73,618,031 | created a linked list to insert an array in it, but it's not giving desired output | I had created a program to create a linked list and insert an array in it. But it's not giving the desired output, may be the problem is in display function
#include <iostream>
using namespace std;
//node
class node {
public:
int data;
node *next;
} *head = nullptr;
//function to insert array in linkedl... | The problem is that you have multiple variables named head being used for different purposes. You have a global variable head, which your display() function uses, but your create() function does not populate. create() populates a local variable named head instead, which shadows the global variable. display() never sees... |
73,617,971 | 73,618,114 | Type error in C++ when instantiating a priority_queue of int pairs with a custom comparator (to implement a min heap) | Currently working through a leetcode problem for which I need a min Heap of pairs.
I am trying to use a priority_queue with int pairs and a custom compare type.
Attempts of implementation of the same have failed with the following error:
In file included from prog_joined.cpp:1:
In file included from ./precompiled/head... | As you can see in the std::priority_queue documentation:
The 1st template argument is the data type (should be pair<int,int> in your case).
The 2nd template argument should be the underlying container type used for the queue.
The 3rd should be the compare type.
For example if you want a priority_queue of int pairs th... |
73,618,656 | 73,618,809 | What is the usage of std::multimap? | I've just started learning STL containers, and I cannot understand why std::multimap exists. With std::map, we can access values by user-defined keys, but with std::multimap we cannot do that as the latter does not even have an overloaded operator[] and the same key can be mapped to several different values. To me, thi... | First note that std::map::operator[] is a little quirky. It is not the way to access elements in the map. Instead std::map::operator[] potentially inserts an element into the map and then returns a reference to either the element that was already present before or to the newly inserted. This may seem like splitting hai... |
73,618,718 | 73,618,781 | What to pass in a class constructor with multiple inheritance? | I just started learning C++ and QT, sorry if this is a weird question.
I inherit a class from two classes, each of which has a constructor. How can I correctly pass parameters to these two constructors?
I have first class - WirelessSensor
class WirelessSensor : public BoxSensor
{
public:
explicit WirelessSensor(con... | It's really simple - you need to call it directly by chaining the initializations in the derived class:
struct A
{
A(int a) { AA=a; }
int AA;
};
struct B
{
B(std::string b) { BB=b;}
std::string BB;
};
struct C : public A, public B
{
C(int a, std::string b)
:A(a),
B(b)
{
}
};
Try... |
73,619,255 | 73,619,635 | Negative number input help-how-to | // ConsoleApplication6.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <limits>
int getInput() {
while (true) {
std::cout << "Indtast fire point-tal mellem 0 og 100: ";
int number = 0;
int number2 = 0;
int nu... | you could make a inputPositive function that reads the input and sets a boolean to true if the input number was negative:
void inputPositive(int& number, bool& negative) {
std::cin >> number;
if (number < 0) {
negative = true;
}
}
then you can call these functions for the 4 numbers. If negative fla... |
73,619,383 | 73,726,717 | Why does pybind fail for functions without arguments? | I have an overloaded constructor in C++ (default + other). My automatically generated pybind code looks like this:
py::class_<MyClass>(m, "MyClass")
.def(
py::init<>(),
py::kw_only()
)
.def(
py::init<
std::valarray<std::string>
... | Thanks @463035818_is_not_a_number for pointing me in the right direction. I was confused cause I mixed up kw_only with **kwargs. kw_only means, that only named arguments are allowed when calling a function which doesn't make sense without arguments.
My custom pybind generator added kw_only to all functions and the buil... |
73,619,448 | 73,623,327 | Removing copy ctor of 3rd party class | I have a class that stores a large std::map. My understanding is that the idiomatic way to do this is:
class Foo {
public:
Foo(/* Note: passed by value */ std::map<Bar, Baz> large_map) : large_map_(std::move(large_map)) {}
private:
std::map<Bar, Baz> large_map_;
};
int main() {
std::map<Bar, Baz> large_map;
... | The title appears to be a slight misnomer here (or is at least at odds with the contents with your question):
(At least in the example given), you do not want to remove the copy constructor i.e. Foo::Foo(const Foo& other), but rather prevent invokation of Foo's constructor with a non-movable argument.
As Mestkon pointe... |
73,619,926 | 73,742,332 | Random error in exe_common.inl in Debug build | I am using VS 2022 Community Edition (v17.3.3) to build wxWidgets application (v3.2.0) using C++ (v14.3 - Features from Latest C++). The windows SDK is using the latest installed (10.0.22621). The project is also using C++ modules.
The Debug build succeeds but when I run the project's exe file at random it throws the e... | There were a few things needed attention:
Discontinued use of wxSQLite (the library was not maintained for over a decade),
The main frame was a singleton data structure, not anymore, and not deriving from wxMDIFrame anymore.
All unnecessary (a chain of them) #include removed.
Inclusion of <boost/json.hpp> in a few fil... |
73,619,994 | 73,620,044 | How to initialize a struct with two std::array members? | I can initialize a struct with a single std::array element using a variadic template constructor:
#include <array>
#include <initializer_list>
#include <memory>
struct Foo {
using data_type = int;
using foo_type = std::array<data_type,2>;
using init_type = std::initializer_list<data_type>;
template <ty... | Just specify the parameters as arrays themselves:
struct Foo {
using data_type = int;
using foo_type = std::array<data_type,2>;
using init_type = std::initializer_list<data_type>;
Foo(const foo_type &arr, const foo_type &arr2): array1_{ arr }, array2_{ arr2 } {}
foo_type array1_, array2_;
};
|
73,620,242 | 73,620,608 | Do I need a transaction for multiple queries in one string? | https://github.com/SRombauts/SQLiteCpp
SQLite::Database db("example.db3");
while(...)
{
db.exec("INSERT INTO xxx VALUES(...)");
}
It's sample code for SQLite to insert data. If there's no transaction, each db.exec is slow, almost takes 1 second.
So, you need a transaction :
db.exe("BEGIN");
while(...)
{
db.... | If you want to insert 'everything' or 'nothing', then, YES. You still need a transaction. SQLite::Database::exec() internally calls sqlite3_exec() and semicolon separated SQL statement will not be executed atomically without a transaction.
|
73,620,656 | 73,620,713 | Passing image to function as a char array in C++ and display with SFML | I'm aware there are similar posts already but I just couldn't find anything that solved my problem.
I have my image stored as a char array of hex numbers and I am trying to pass this to a function that loads that data from memory in order to read the data and display the image. When I write the array name directly into... | You can't pass arrays like that to function. What you're passing is only a pointer to the first element of the array. And the sizeof of a pointer is the size of the pointer itself, not what it actually points to.
All of this means that for the loadSpriteResource function the argument is really
const unsigned char* imag... |
73,620,711 | 73,620,956 | Create a tuple of successive elements of a vector divided by each other | I have a member variable of a class, offsets, which is a vector with at leastN+1 elements. I would like to create a member function which will return a tuple with N entries with values of successive elements of the vector divided by each other. An example is shown below for a specific instance of this function when N=3... | You can implement this with std::index_sequence.
template<size_t N>
struct foo {
std::array<double, N + 1> offsets;
auto get_tuple() const {
auto make_tuple =
[this]<typename I, I... idx>(std::index_sequence<idx...>) {
return std::make_tuple((offsets[N - idx] / offsets[N - ... |
73,621,975 | 73,622,641 | Does taking a reference to an object via two different base classes violate strict aliasing rule? | I have three pure virtual classes, let's call them ServiceA, ServiceB and ServiceC.
The concrete implementation provides all three services using multiple inheritance:
class Concrete : public ServiceA, public ServiceB, public ServiceC
{
//...
};
It is possible that the services could also be provided by separate c... |
If instantiate my class as shown below, will that be a violation of the strict aliasing rule?
Strict aliasing rule doesn't break because svcA and svcB do not refer to the same address in the memory. When you refer to base classes, you actually refer to subobjects of the complete class Consumer, where each has its own... |
73,623,523 | 73,625,748 | Why is my program continuing on the setw value which I have set for the previous cout statements? And this is happening in a pattern too? | This is my code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
int n1 = 1, n2 = 2;
cout << setw(5) << n1 << endl;
cout << setw(6) << n1 << " " << n2 << endl;
cout << setw(7) << n1 << " " << n2 << endl;
cout << setw(8) << n1 << " " << n2 << endl;
... | You just put the numbers in wrong order, try this:
int main() {
int n1 = 1, n2 = 2;
cout << setw(9) << n1 << endl;
cout << setw(8) << n1 << " " << n2 << endl;
cout << setw(7) << n1 << " " << n2 << endl;
cout << setw(6) << n1 << " " << n2 << endl;
cout << setw(5) << n1 << " " << n2 <<... |
73,624,093 | 73,624,425 | Stack Smashing detected while implementing mergeSort in C++14 | I am implementing standart MergeSort algorithm. I am getting a runtime error 'Stack Smashing Detected'. What is the root cause of such error and how to prevent my code from this error?
I saw that the control is coming to merge function , but somewhere it is getting messed up.
#include<iostream>
using namespace std;
//... | The problem is in your merge routine. If you look at the case where low and mid are 6 and high is 7, which will happen towards the end of the recursion, the loop
while (i <= mid)
res[k++] = arr[i++];
will end up executing with k being out-of-bounds. I think you meant for k to be initialized to low because it is sup... |
73,624,398 | 73,625,445 | Call to implicitly deleted default constructor when instantiating unordered_map<const char, std::string> | I'm trying to instantiate an std::unordered_map<const char, std::string>:
std::unordered_map<const char, std::string> cities = {
{'A', "Amsterdam"},
{'B', "Berlin"},
{'C', "Canberra"}
};
This fails with error: call to implicitly-deleted default constructor of 'std::unordered_map<const char, std::basic_stri... | As stated in documentation for std::hash it is implemented through template specialization:
Each specialization of this template is either enabled ("untainted") or disabled ("poisoned").
The enabled specializations of the hash template defines a function object that implements a hash function. Instances of this func... |
73,624,769 | 73,625,020 | C++ template function recursive | I have a function that calculate determinant of a matrix.
My matrix class is like this:
template <int Col, int Row, typename T>
class Matrix;
I have implemented 3 specific function for Mat<1, 1, T>, Mat<2, 2, T>, Mat<3, 3, T>:
template <typename T>
float Determinant(const Matrix<1, 1, T>& mat);
template <typename T>
... | Imagine you instantiate Determinant with Dim = 0. Your compiler will try to instantiate Determinant<-1>, which will then again instantiate Determinant<-2>, and so on. At some point you will reach the maximum 1024. A minimal reproducible example could look like:
template <int I>
void foo() {
foo<I - 1>();
}
int main(... |
73,624,899 | 73,624,945 | C++ error C2280. Why struct is non-copyable | I have a struct inside header file in C project.
struct tgMethod {
const char *name;
const enum tgAccessModifier access;
const enum tgMethodKind kind;
tgTypeRef return_type;
const tgParams params;
const tgMethod *overrides;
const void *userptr;
const tgObject *(*methodptr)(tgObject *, si... |
Why tgMethod is non-copyable?
tgMethod can be copied, via copy construction, but it is not assignable.
Your class tgMethod has several const members.
const enum tgAccessModifier access;
const enum tgMethodKind kind;
const tgParams params;
const members can not change, therefore a constructed tgMethod object can not... |
73,625,050 | 73,626,597 | What is the most efficient way to compare two QStringList in QT? | I have two String Lists and I already have a function that compares two lists to find out which elements of list 2 do not exist in list 1. This block of code works, but maybe it is not the best way to achieve it, there are any other way to get the same result without performing so many iterations with nested loops?
QSt... | If you switch to QSet<QString>, your code snippet boils down to:
auto diff = set2 - set1;
If the input and output data structures must be QStringLists, you can still do the intermediate computation with QSets and still come out ahead:
auto diff = (QSet::fromList(list2) - QSet::fromList(list1)).toList();
|
73,625,801 | 73,625,902 | Undefined reference to info() | So basically I was given an assignment to write a program that uses three arrays, one to store the given names and the other two to output whether an Employ will be an Attendee at a conference. The employee is allowed to attend both sessions. (We are not allowed to use pointers, referencing or structs)
This is what I h... | You are just missing this - [10] in your function definition.
//Info Function
bool info(string Names[10], int num, int pos) {
...
}
|
73,626,013 | 73,626,584 | std::variant does not seem to work with shared_ptr in C++ | With the code below, I'm getting:
In static member function ‘static std::shared_ptr<std::variant<MyClass<InputClass1>, MyClass<InputClass2> > > MyCreatorClass::create()’:
main.cpp:34:57: error: could not convert ‘std::make_shared(_Args&& ...) [with _Tp = MyClass; _Args = {}]()’ from ‘shared_ptr>’ to ‘shared_ptr, My... | static std::shared_ptr<VariantType> create()
this is a function that returns a shared pointer to a variant over MyClass<InputClass1>, MyClass<InputClass2>.
{
return std::make_shared<MyClass<InputClass2>>();
}
this is a function body that returns a shared pointer to a MyClass<InputClass2>.
These two types are unrel... |
73,626,367 | 73,626,770 | use std::accumulate to add an array to only a vector slice | I have following code
std::vector<float> d;
d.resize(800);
std::array<float, 8> adder;
int ind_slice = 5; // we want to add the array adder to v[40],v[41] ... v[47]
const auto it_begin = d.begin() + ind_slice *8;
const auto it_end = d.begin() + ind_slice *8 + ind_slice;
int index = 0;
std::a... | At least if I understand your intent correctly, the algorithm to use here would almost certainly be std::transform, not std::accumulate.
accumulate is intended for taking some collection, and simply adding them up, roughly equivalent to sum() in a spreadsheet (for one example).
transform allows you (among other things)... |
73,626,694 | 73,626,842 | Getting first 5 even numbers element from vector after reverse const iteration | I have this code below that generates 15 random integers and uses them to initialize my vector, intVec. What I'm trying to do here is to iterate through the vector in reverse order and only print out the first 5 even numbers encountered while iterating.
I tried using the erase method to just print the first 5 elements... | The requirement of having to use the const_reverse_iterator (note the "const") should be telling you that modifying the vector is not allowed. And nor is it even necessary: just use that iterator and run through the vector, printing out the elements that are even and, when doing so, incrementing a "counter" variable. W... |
73,627,187 | 73,627,458 | Can I specify the radius of each corner of a rounded rectangle? | In Direct2D, rounded rectangle geometry can be created this way:
D2D1_ROUNDED_RECT rq = {0};
rq.rect.left = 0;
rq.rect.top = 0;
rq.rect.right = 100;
rq.rect.bottom = 100;
rq.radiusX = 5;
rq.radiusY = 5;
factory->CreateRoundedRectangleGeometry(rq, &geometry);
Where radiusX and radiusY are confusing me, because I can't... | According to the documentation, radiusX and radiusY are the radii for the quarter ellipse that are drawn in every corner.
You are not specifying the radius for every corner but for all of them at once. When radiusX is larger than radiusY, it's essentially a rounded rectangle that looks "squished".
If the radii are lar... |
73,627,348 | 73,627,384 | Why is the text of the file displayed twice | I have been working on a project which needs to read the text from a .txt file. But I get the text displayed in the console twice.
Here is the CreateFiles.cpp
#include "CreateFiles.h"
void createF()
{
std::fstream fs{ "C:\\Users\\bahge\\source\\repos\\Education\\Education\\myfile.txt" };
std::string s;
wh... | You are encountering a variation of Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?.
You are ignoring the stream's state after getline() returns. Your file has only 1 line in it, so s is not valid (and in your case, is unchanged) after the 2nd read fails, but you are not ha... |
73,627,351 | 73,627,809 | Find unique element in sorted array using c++ | I am trying to find unique element from the array these is question
Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output : arr[] = {1, 2, 3, 4, 5}
They give me correct output but why they give 0 at the end in output:
these is my output:
{1,2,3,4,5,0}
Code:
#include<iostream>
using namespace std;
int main(){
int a... | Except for std::cout, you code is much more C than ++.
std::unique of the C++ Standard Library does exactly what you want. There is no need to re-implement this.
Next there is the erase-remove idiom to delete the superfluous elements.
For the output, you can use std::for_each() or at least a range-based for loop.
And ... |
73,628,029 | 73,628,529 | Java shared library generated from C++ code | I'm trying to run C++ code in java using the java wrapper to generate such code, I've successfully generated all the code and implemented it in my code, but when I try to compile, I get an architecture error
Can't load this .dll (machine code=0x7) on a AMD 64-bit platform
I'm running java 1.8.0_022, the PC I'm running ... | The typical solution to run C++ code in Java is with Java Native Interfaces (JNI)
https://docs.oracle.com/javase/8/docs/technotes/guides/jni/
You might also want to check SWIG that makes the C++/JNI integration much easier.
https://www.swig.org/Doc1.3/Java.html
As user @KCWong added in the comments, there's also JNA (g... |
73,628,084 | 73,628,271 | Why am i getting seg. fault? | I'm starting with pointers, and I can't see the reason why I'm getting a segfault with this code. I guess I'm accessing the array the wrong way, so how should I access it?
const int MAXIMO_LIBROS_INICIAL = 20;
typedef struct {
string titulo;
char genero;
int puntaje;
} libro_t;
int main(){
libro_t** l... | You are creating an array of pointers that don't point anywhere. You are getting a segfault from trying to access invalid memory. You need to create the individual objects that the pointers will point at, eg:
const int MAXIMO_LIBROS_INICIAL = 20;
struct libro_t {
string titulo;
char genero;
int puntaje;
... |
73,628,107 | 73,629,611 | RegexReplace different output according to compiler | LIVE
#include <iostream>
#include <regex>
int main()
{
std::string text = R"(11111111111111111111
11111111111111111111
11111111111111111111
11111111111110000000
11111111111000000000
11111111100011111100
11111111100111100000)";
std::regex re("^1+\n");
std::string str = std::regex_replace(text, re, "");
... | I modified my answer. It might be a compiler difference. You can refer to the flags and similar thread.
std::regex_constants::match_flag_type fonly =
std::regex_constants::format_first_only;
std::regex re("^1+\n");
std::string str = std::regex_replace(text, re, "", fonly);
|
73,628,314 | 73,628,451 | reinterpret_cast a slice of byte array? | If there is a buffer that is supposed to pack 3 integer values, and you want to increment the one in the middle, the following code works as expected:
#include <iostream>
#include <cstring>
int main()
{
char buffer[] = {'\0','\0','\0','\0','A','\0','\0','\0','\0','\0','\0','\0'};
int tmp;
memcpy(&tmp... | The latter approach is technically undefined, though it's likely to work on any sane implementation. Your syntax is slightly off, but something like this will probably work:
int* tmp = reinterpret_cast<int*>(buffer + 4);
(*tmp)++;
The problem is that it runs afoul of C++'s strict aliasing rules. Essentially, you're ... |
73,628,384 | 73,630,947 | WinUI 3 C++/WinRT loading string resources | I have a basic WinUI3 C++/WinRT app, containing a resw file with a simple entry named "APPNAME". I wish to put that string in the title of my Xaml form.
My MainWindow.xaml.cpp has this snippet of code in it.
MainWindow::MainWindow()
{
InitializeComponent();
auto resourceLoader{ Windows::Applicatio... | With WinUI 3, most namespaces usually start with Microsoft, instead of Windows (which was more for UWP).
It's actually difficult to get to the WinUI3-only documentation, here is some: Manage resources with MRT Core
The WinUI 3 resource entry point is now the Microsoft.Windows.ApplicationModel.Resources.ResourceManager ... |
73,628,848 | 73,628,883 | Is the std::views namespace not available in Xcode's C++? | I have Xcode 14 beta, and I tried to compile this join example from cppreference.com.
#include <iostream>
#include <ranges>
#include <string_view>
#include <vector>
int main()
{
using namespace std::literals;
const auto bits = { "https:"sv, "//"sv, "cppreference"sv, "."sv, "com"sv };
for (char const c : b... | AppleClang does not support C++ views. See the red boxes in the 4th column on C++ compiler support.
|
73,628,882 | 73,629,633 | How do I create a GstValueArray in C++? | I am trying to create a GstValueArray in C++ to update a pad property in some GStreamer code, but am unable to figure out from the documentation how to do so. My problem is that I have a GStreamer element that has sink pads with a property "dimensions", which is a "GstValueArray of GValues of type gint". See output fro... | g_object_set is a convenience function that, among other things, parses internally the GType of the property and automatically creates the underlying GValue for you. If you are creating the GValue yourself you need to use g_object_set_property instead.
Replace your g_object_set with:
g_object_set_property (G_OBJECT(pad... |
73,629,766 | 73,629,931 | Good sound apis for linux? | I am learning game development and came across this playlist(Handmade Hero) about making a game from absolute scratch, like using only Os provided apis. The series focuses on windows, I also want to develope the same thing for linux. What should be the sound api that I should use? In the series he was using DirectSound... | ALSA (Advanced Linux Sound Architecture)
part of the linux kernel (sound drivers)
user space library (alsa-lib)
There are also so called sound servers available on linux, like PulseAudio or pipewire.
Frameworks for game development
SDL
OpenAL
|
73,630,606 | 73,632,379 | Is it unsafe to take the address of a variable inside a loop where it is defined? | I came across a comment in cppcheck source code here, stating that it is unsafe to move the definition of i in the example into the inner loop. Why is that?
void CheckOther::variableScopeError(const Token *tok, const std::string &varname)
{
reportError(tok,
Severity::style,
"vari... | The question is focused on the second comment in this hypothetical code:
void f(int x)
int i = 0;
if (x) {
// it's safe to move 'int i = 0;' here
for (int n = 0; n < 10; ++n) {
int i=0;
// it is possible but not safe to move 'int i = 0;' here
do_something(&... |
73,630,748 | 73,631,229 | Mapping enums to types | I have two unrelated types: Object and Unrelated implementing the same basic interface Interface (for storing in the same container).
I have an enum class that basically maps these types to enums
enum class TypeEnum {
TYPE_OBJECT,
TYPE_UNRELATED,
};
I have a reading method, that basically down-casts from the I... | I turn the reference into a copy to fit std::variant,
// using std::type_identity for C++20 or later
template <typename T>
struct type_identity {
using type = T;
};
using VType = std::variant<type_identity<Object>,
type_identity<Unrelated>>;
using RType = std::variant<Object, Unrelated>... |
73,630,821 | 73,631,324 | Best practice for very large if-else-statement using LLVMs RTTI system | I am currently writing a piece of software that relies on another library, which makes heavy use of LLVMs RTTI system. I cannot change the API of said library and it forces me to implement very large if-else-statements over several types and their sub-types. Usually I would have used at a switch-statement instead, but ... | You can switch(something->getType()->getTypeId()) sometimes, but some dyn_cast<>() calls will probably be unavoidable, e.g. for struct types you define.
|
73,631,293 | 73,647,440 | How to encrypt a string using OpenSSL C library and a public key file? | What is the recommended way of encrypting a short std::string into another std::string using the openssl C library (not the command-line tool of the same name) using a public keyfile, and knowing the algorithm? (in this case the string is no larger than ~100 bytes, keyfile is in .pem format, algorithm can be any asymme... | As it turned out in the comments, RSA is an acceptable option for you.
When implementing RSA with OpenSSL, the following steps are required for encryption:
Loading the public key
Creating and initializing the context
Specifying the padding
Encryption
The implementation below for encryption with RSA and OpenSSL runs s... |
73,631,465 | 73,631,672 | How to take a pointer address as command line argument in C++ | I have a C++ code which will take a pointer address as an argument. The code arguments are:
./main 0x7fad529d5000
Now when reading the arguments, this value will be read as a string.
How do I convert the string "0x7fad529d5000" into an address?
| Read a hexadecimal from stdin:
uintptr_t x;
std::cin >> std::hex >> x;
Read a hexadecimal from string:
uintptr_t x;
// assuming you used argc / argv and checked argc > 1
std::istringstream sstr( argv[1] );
sstr >> std::hex >> x;
An alternative would be x = std::stoll( argv[1] ); but there is a cast involved there th... |
73,631,608 | 73,634,291 | How to toggle a QCustomPlot graph's visibility by clicking on the legend | I have a QCustomPlot with multiple graph items on it.
I wish to toggle their visibility by clicking on the relevant item in the legend.
QObject::connect(
plot,
&QCustomPlot::legendClick,
[](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)... | I suggest you try this
QObject::connect(
plot,
&QCustomPlot::legendClick,
[](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
{
for (int i=0; i<customPlot->graphCount(); ++i)... |
73,631,617 | 73,631,870 | pcre2: include a static library in c++ CMake project | need to include pcre2 static library in my CMake project.
I've built last version of pcre2 from official sources and got libpcre2-32.a (I need 32-bit char width libray)
Put it in my project folder, with its header pcre2.h
Have added this library to CMakeLists.txt:
...
include_directories(SupportFiles/OSLinux/pcre2)
... | (I don't have enough reputation to leave comments :( )
The linker error seems to be from a separate executable (a unit test). Does it have libpcre2 added as a dependency (using target_link_libraries())?
|
73,631,820 | 73,632,272 | How do I normalize a filepath in C++ using std::filesystem::path? | I am trying to convert a path string to a normalized (neat) format where any number of directory separators "\\" or "/" is converted to one default directory separator:
R"(C:\\temp\\Recordings/test)" -> R"(C:\temp\Recordings\test)"
Code:
#include <string>
#include <vector>
#include <iostream>
#include <filesystem>
st... | As answered by bolov:
std::string normalizePath(const std::string& messyPath) {
std::filesystem::path path(messyPath);
std::filesystem::path canonicalPath = std::filesystem::weakly_canonical(path);
std::string npath = canonicalPath.make_preferred().string();
return npath;
}
weakly_canonical does not th... |
73,632,135 | 73,633,675 | How do I assign an arbitrary value to a unique_ptr? | Is there a way to assign an arbitrary value to a unique_ptr?
Let's say I have some unique_ptr of an object. For testing purposes, I want to have this unique_ptr to be != nullptr, and/or pObj.get() != 0 without having to construct the object.
std::unique_ptr<someObj> pObj;
assert(!pObj);
// OK, but not what I want
// p... | Summarize the answers given in the comments of the question.
The new code has to look like this:
std::unique_ptr<someObj> pObj;
assert(!pObj);
// Assign a "fake" object at an arbitrary memory location
pObj.reset((someObj *)1);
assert(pObj);
// release before unique_ptr is destructed!
// Else we would get an Segmentat... |
73,632,216 | 73,633,287 | Improve the performance of a method used to convert an std::string into an std::wstring? | I have the following method used to convert an std::string object into an std::wstring one:
#include <string>
#include <type_traits>
#include <locale>
#include <codecvt>
template <class CharT>
inline std::basic_string<CharT> StringConverter( std::string input_str )
{
if constexpr( std::is_same_v <CharT, char> ) ret... | You can clearly avoid copy/move in case you don't do any conversion (std::string -> std::string) and just pass and return by reference:
template <class CharT>
std::conditional_t<std::is_same_v<CharT, char>,
const std::basic_string<CharT>&,
std::basic_string<CharT>>
StringConverter(... |
73,632,337 | 73,646,023 | Performance improvements of a method which check if a string is an ANSI escape sequence? | Let's suppose I have a class with a private method is_escape which check if an input string is and ANSI escape sequence. This method is then used in another public method, into an if/else condition:
#include <string>
enum class ANSI { first, generic };
template <class T_str>
class foo
{
private:
template <typen... | At the end, I improved the performances of the function with this signature:
template <typename T>
static constexpr bool is_escape( const T& str, const ANSI& flag )
{
if constexpr( std::is_convertible_v <T, std::basic_string_view<T_str>> && ! std::is_same_v<T, std::nullptr_t> )
{
switch( flag )
{
c... |
73,632,611 | 73,637,922 | Nested Requirements for Tree Data Structure with heterogeneous Nodes | Objective:
I want to implement a tree data structure with non-identical nodes to manage my data. In general, the tree consists of 2 different type of nodes, namely, "Nodes" and "LeafNodes". Those nodes which have no children are considered to be "LeafNodes", which will be used to store data. Within the tree all nodes a... | There are two problems with the definition of the NodeLike:
template<class T>
concept NodeLike = requires(T) {
is_object_v<T>;
requires T::Header;
};
First, the requires-clause only checks the validity of the expression, so is_object_v<T> is useless here because it is always valid, you should use the nested requir... |
73,632,664 | 73,637,026 | Generated parser code with antlr4.11.1 contains error | I create a compiler with antlr and llvm in c++. I've created the two .g4 files and in my CMakeLists.txt I call the antlr jar to generate the lexer and the parser. Then I compile all my files with the same CMakeLists file and I got these errors :
Filc/src/generated/FilParser.cpp:803:16: error: invalid use of member func... | I tried the c++ target on one of my project and it compiled correctly in 4.9.3.
Are you sure you didn't mix the version of the runtime you use and the version of antlr4 you used to generate the parser? You need the same version for both.
|
73,632,839 | 73,635,362 | How to create a manifest file for a C++ project? | I'm trying to add DPI awareness per monitor v2 to a C++ application, using VS2022. Microsoft recommends to do this using the application manifest. So far I have been using an automatically generated intermediate manifest file (using the setting under linker -> generate manifest: yes). However, this file is not actually... | By default, the manifest is embedded into the compiled application (exe or dll). You can access it with a resource viewer. There is an option to control that in Manifest Tool -> Input and Output -> Embed Manifest.
All manifest files included in your project are merged and added to the application manifest (maybe the fi... |
73,633,209 | 73,635,807 | Unable to Debug C++ Application in VS 2019 | I have a C++ project that I am able to build and run as an exe just fine.
However, when I try to debug the project in Visual Studio 2019 I get the following error:
"Unhandled exception at 0x75D7C66B (shell32.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0x00000004"
It also says: "Source Not Available... | I fixed it.
In Visual Studio under:
Options -> Debugging -> General
I disabled the option: "Load debug symbols in external process (Native only)"
I still don't really understand why this fixed the problem. If someone could explain I would be grateful.
|
73,633,579 | 73,744,769 | C++ [QT 5.15.2] : virtual keyboard shift button is disabled until I click on my textField | I'm developping an app using QT 5.15 LTS (5.15.2). I have the following QML item that I use to handle virtual keyboard interactions :
//InputScreen.qml
import QtQuick 2.3
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.2
import QtQuick.VirtualKeyboard 2.3
Rectangle
{
id: inputScreen
property var target: u... | I finally managed to find a trick that enabled that shift key without requiring to click on my already focused TextField, and it's actually very simple.
I simply added the following line in the onClicked event of the MouseArea inside the "myField" TextField :
MouseArea
{
anchors.fill: parent
onClicked:
{
... |
73,633,682 | 73,633,683 | What programing languages does Memgraph support? | From which programming languages can I connect to Memgraph? Which protocol is used? I know that Python is for sure supported since there is GQLAlchemy (a fully open-source Python library). What about other languages?
| f you want to query Memgraph programmatically, you can do so using the Bolt protocol. The Bolt protocol was designed for efficient communication with graph databases and Memgraph supports versions 1 and 4 of the protocol. You can use the Bolt protocol drivers for the following programming languages:
Python
C/C++
Rust
... |
73,634,271 | 73,635,329 | Iterate over json and change first character of Json keys to upper case | I want go throw all json keys and convert the first character to upper case.
i understand that i cant change json keys so crate a new json from the old one
i using json::Value,
void change_keys(Json::Value& oldJson, Json::Value& newJson) {
for (Json::ValueConstIterator it = oldJson.begin(); it != oldJson.end(); ++i... | I think it should be something like:
void change_keys(Json::Value& oldJson, Json::Value& newJson) {
if (oldJson.isObject()) {
for (Json::ValueConstIterator it = oldJson.begin(); it != oldJson.end(); ++it) {
std::string newKey = it.name();
newKey[0] = std::toupper(newKey[0]);
... |
73,634,556 | 73,645,324 | How to test a string for containing emoji characters? | I'm using ICU4C and trying to find the clusters in a UTF-8 string that are emojis. This is the closest I've gotten so far but it incorrectly qualifies the simple character '#' as an emoji (because '#️⃣' begins with '#' and is "potentially" an emoji so '#' does carry the property UCHAR_EMOJI).
I think the best would be ... | Looks like u_stringHasBinaryProperty will give you access to UCHAR_RGI_EMOJI. Note that this method is not available in ICU versions < 70.
I think that you need to distinguish between basic emojis that consist of a single code point (e.g. U+1F600 ), and emoji sequences (e.g. U+0023 U+FE0F U+20E3 #️⃣). The basic emoji w... |
73,634,751 | 73,634,892 | C++ - What underlying type would an enum with more than 18,446,744,073,709,551,616 elements have? | This is more of a hypothetical question than a practical one. Of course there would be memory issues if we actually tried to compile a program with that large.
Enums in C++ will take on an underlying type to fit the maximum element of the enum. Also, if I specify no integer values, then each element is always 1 more th... | There's no loophole. You'll just get a diagnostic in a conforming compiler.
[dcl.enum]
7 ... If no integral type can represent all the enumerator values, the enumeration is ill-formed. ...
Or more practically, you'll get an error and compilation will halt.
It might even halt sooner, due to implementation defined limi... |
73,634,903 | 73,635,260 | How to determine a number wether it's prime or not using while | i am a first semester university student. I am trying to make a program that determine wether the number is prime or not (Ex : if i input 2, there will be an output saying it's a prime number). To make this program, is it possible if i use while loop?
Here's a thing i have tried :
#include<iostream>
using namespace... | Some remarks/directions:
Your program currently has only one outcome. So, without looking at your logic, it will either run forever or will say it's prime.
Your brute-force method can and should stop at square-root of a.
a % b is the remainder of a divided by b. The remainder becomes 0 when a is a multiple of b (i.e... |
73,635,072 | 73,638,126 | Passing a pointer to a vector | I'm exploring a c++ library and cant figure out why its examples are written as they are.
In the example they do the following
std::vector<unsigned int> vec(count);
someFunc(&vec[0]);
while the fucion is define as
void someFunc(unsigned int* a);
why are the examples passing a reference to the first element of the... | The reason they have written their example like they have is that someFunc() takes in a unsigned int* type (a pointer to an unsigned int). The reason they call it as:
someFunc(&vec[0]);
and not
someFunc(&vec);
is because a std::vector is not like a C-style array (say unsigned int arr[]) where arr can be boiled down a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.