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
68,692,337
68,752,679
Cmake and PugiXML in Github Actions
i try to get pugixml running in github actions. And i would be happy with any solution that is working... I added the download to the cmake.yml run: sudo apt-get update && sudo apt-get install libsystemd-dev libpugixml-dev Ubuntu inside github action is installing 1.10-1: Get:1 http://azure.archive.ubuntu.com/ub...
I solved it by using vcpkg to install pugixml: - name: Install pugixml via vcpkg run: sudo vcpkg install pugixml && sudo vcpkg integrate install - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generat...
68,692,453
68,692,510
std::map<int,bool> wrong result of insert?
#include <iostream> #include <map> using namespace std; int main() { std::map<int, bool> set; cout << (int)set.insert({ 5,false }).second << endl; return 0; } I don't know why the result is 1 instead of 0, while second is false.
std::map::insert's return value is an std::pair<iterator, bool> where the bool denotes whether insertion took place. cout << (int)set.insert({ 5,false }).second << endl; will only print whether insertion successfully took place. To do what you want, you'll want to use the first value in the returned std::pair which is ...
68,692,525
68,692,571
How I can I get the mirror reflection of a glm::mat4?
So I'm using a shader to draw in OpenGL a 2D scene that so far looks like this To get this image I have a camera that I use in the shader to multiply the coordinates of the vertex. Camera code: glm::mat4 projection = glm::perspective(glm::radians(45.0f), app.aspectRatio, 0.0f, 100.0f); glm::vec3 camera = glm::vec3(0...
Mirror the y axis of the camera with glm::scale. The scale must be (1, -1, 1): glm::mat4 projection = glm::perspective(glm::radians(45.0f), app.aspectRatio, 0.0f, 100.0f); glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -2.0f)); view = glm::scale(view, glm::vec3(1.0f, -1.0f, 1.0f)); glm::m...
68,692,975
68,693,894
Providing an array by a literal into function in c++
I am a beginner in c++. I have faced a problem. When I provide an array into a function like this: void foo(const int a[2]) { // some code... } int main() { foo({ 23, 63 }); return 0; } I get errors: E0146 Too many initializers C2664 "void foo(const int [])": cannot convert argument 1 from "initializer ...
When you use {23, 63} as the argument, it is not an array. But a C++ compiler will be able to initialize a std::initializer_list with it. see the example #include <iostream> #include <initializer_list> void foo(const std::initializer_list<int>& a) { // some code... } //array overload void foo(int(&a)[2]) { } //tem...
68,693,420
68,693,494
Allowing multiple threads to read at once given a condition variable, but only one thread writing
I have a situation where I have multiple threads reading from a map which is written to only in thread A. The issue is that the multiple threads reading from the map are each looking for a unique value in the map to continue, a id. "Thread A" Note: Payload is a simple struct holding some information std::map<unsigned ...
it's because unsigned int jobId = ...; // item in map this thread is looking for std::unique_lock<std::mutex> ul(mutexJobStatus); auto jobTaken = jobStatus.find(jobId); //wait for item to become available in the map sced->cv.wait(ul, [jobId, &jobTaken] { jobTaken = jobStatus.find(jobId); return jobTaken != jobStatus.en...
68,693,835
68,694,460
Example of gtkmm 4 FileChooserNative code
I can't find code examples using Gtk::FileChooserNative to help me understand how to work with this class. Documentation from here isn't that helpful. My goal is to create a function which opens a native file chooser dialog and after the user selects the folder, prints the path to the folder into a terminal. When I try...
I don't have Gtkmm 4 here, but from the documentation you posted, it seems you need to use a factory method instead of a constructor to create such a dialog: static Glib::RefPtr<FileChooserNative> Gtk::FileChooserNative::create( const Glib::ustring& title, Window& parent, FileChoose...
68,693,949
68,694,083
Pointer to methods problems
Well, as I stated in the question: pointers to members methods My question: msvc++ is throwing me errors. If we have: class A { bool one, two; typedef void (A::* RunPtr)(int); public: RunPtr Run; A() : one(false), two(false) { Run = &A::RunOff; } void SetOne(bool value) { ...
The correct syntax to call the member Run (which holds the pointer to the member function) with argument is A* a = new A(); (a->*(a->Run))(10); ^^^ ---------> argument(s) ^^^^^^^^^ -------------> class member "Run" ^^^^^^^^^^^^^^--------------> call to member function pointer syntax // delete a aft...
68,693,967
68,694,041
std::bind() doesn't bind arguments
I'm trying to create a queue of methods which are bound to objects using std::bind(). The parameter (object of another class) of the method is bound when std::bind() is called. For some reason I cannot get it to work. parser.h #ifndef PARSER_H #define PARSER_H class File_Descriptor; class Parser{ public: void parse...
If you have a function with two arguments, and you bind both of them, how many are left? Not one, zero. So your std::functions are wrong and should be std::function<void()>. Nothing is wrong with std::bind. Also std::queue<T>::pop returns void, not the popped element. You have to use front, then pop. int main() { F...
68,694,154
68,694,290
File not being received properly?
I'm using sockets to send an EXE file like this: PVOID dll_image = get_dll_by_file(L"C:\\file1.exe"); if (!dll_image) printf(_("invalid dll\n")); send(Connections[conindex], reinterpret_cast<char*>(dll_image), sizeof(dll_image), NULL); PVOID get_dll_by_file(LPCWSTR file_path) { HANDLE h_dll = Crea...
There are multiple bugs in the shown code. send(Connections[conindex], reinterpret_cast<char*>(dll_image), sizeof(dll_image), NULL); The first bug is: if you read the documentation for send, you will find that it gives you absolutely no guarantees, whatsoever, that the requ...
68,694,451
68,706,424
Can not open file "fltkd.lib" error in Visual Studio 2019
#include <FL/Fl.H> #include <FL/Fl_Window.H> #include <FL/Fl_Box.H> int main() { FI_Window window(200, 200, "Window title"); // error: FI FL_Box box(0, 0, 200, 200, "Hey, I mean, Hello, World! "); window.show(); return Fl::run(); } I build the above code in VS 2019 and and get an error code LNK1104 | ...
LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library If you compiled one file to use one kind of run-time library and another file to use another kind (for example, debug versus retail) and tried to link them, you will get this warning. You should compile all source files to use t...
68,694,847
68,694,937
Why is my struct constructor, which contains other structs, not working?
I'm trying to create a basic physics' simulation that calculates rectilinear movement. When I tried to add a constructor to the Body struct, it showed the following error: no matching function to call to 'Vector::Vector()' Here's the code: struct Point{ int x,y; Point(int _x, int _y) : x(_x), y(_y) { ...
Members are initialized before the constructor body is executed. Hence, the constructor body is the wrong place to initialize members. Use the member initialization list instead: Body(std::string _ID = "NONE", int _m = 0, Point _pos = Point(0, 0)) : ID(_ID), m(_m), v(0,0), a(0,0), pos(_pos) { } In your code, because y...
68,695,423
68,700,123
How do I rotate 2D matrix properly?
I am given a square matrix size n and characters that the matrix contains. For example: 3 one two row I have to rotate the matrix by 45 degrees. | | |o| | | |o|n|e| | |t| |n| | |t|w|o| -> |r| |w| |e| |r|o|w| | |o| |o| | | | |w| | | I get | | |o| | | ...
Hm, in my understanding, your algorithm using a rotation matrix will not work. You will always have problems with rounding. And with the correct placement of the values at the correct position in the destination matrix. And it is even not needed, because the indices for the 2 dimensional can be calculated really simply...
68,695,437
68,695,633
How do I use UINT64_MAX standard library macro?
While learning C++ I recently came across the usage of macros and learnt that there are many standard macros such as this one (and many others for Integers) : #include <cstdint> UINT64_MAX (from https://en.cppreference.com/w/cpp/types/integer) I don't really understand what it is even though the name speaks for it...
UINT64_MAX is used to return the maximum value a uint64_t can contain. A common scenario would be to cast a double into a uint64_t. We would : make sure that the uint64_t variable it is casted to is greater than or equal to zero. it's less than or equal to UINT64_MAX (std::numeric_limits would apparently work too.) H...
68,695,527
68,696,202
How to use designated initialization of derived aggregates in C++?
I have an aggregate structure B derived from another aggregate A. I would like to initialize it and there are two options: ordinary aggregate initialization and C++20 designated initializers: struct A {}; struct B : A { int x; }; int main() { [[maybe_unused]] B x{{},1}; //ok everywhere [[maybe_unused]] B y{.x=...
Is there a way to use designated initializers here and calm down GCC at the same time to eliminate the warning? No. GCC's warning is correct: you are missing an initializer for the base class, A. Now, in this case you happen to want to initialize from = {} anyway (which is what happens when you don't provide an initi...
68,695,573
68,698,053
MsgBox event loop and .show()
I currently have a problem where my QMessageBox has to be closed twice before it finally goes away. I was wondering if the local event loop QMessageBox::exec() is being triggered twice by the QApplication::exec() but I am not sure if that's right assumption to make. I then decided to switch the QMessageBox::exec() to ....
As is turned out during the discussion in the comments: Either on_actionAbout_triggered should be renamed, possibly into something not matching the on_childObject_signal pattern or the manual connection connect(ui->actionAbout, &QAction::triggered, this, &TextEditor::on_actionAbout_triggered); should be removed. The re...
68,696,198
68,696,232
Creating a std::map containing 2d arrays?
I was trying to create a map to associate 2d arrays to characters. I tried to do it in this way: map<char, bool[6][4]> m; bool charA[6][4] = { 0,1,1,0, 1,0,0,1, 1,1,1,1, 1,0,0,1, 1,0,0,1, 1,0,0,1 }; m.insert(make_...
Since you are using c++ and have access to c++11 compiler or newer versions, use std::array instead of the c-style array. In your case, you can replace it with std::array<std::array<bool, 4>, 6>. Now you can do as follows: See a demo #include <array> // std::array std::map<char, std::array<std::array<bool, 4>, 6>> m; ...
68,696,476
68,696,732
Cross-platform library using platform-specific dependency
I am curious about how it would be possible to create a cross-platform library (built with CMake) that has seemingly platform-specific dependencies. For example, say I create a library using GLEW or OpenGL, and during development I download their windows adaptation (glew_x64-windows or opengl_x64-windows for example), ...
Best option: Generally you would just ask cmake to find the library for you, via find_package. This will get the platform-specific version of that library that's already installed on the system that's doing the compilation. You won't have to worry about what platform you're on in this case. Less-good option: If you've ...
68,696,561
68,704,796
How to send a string from c++ app to a message only window in java (LPARAM to String conversion)
I am trying to send a String to a message-only window that I have created in java using JNA. I am using SendMessage to send a message. (I know that it is not recommended to use FindWindow every time I send a message, but this is just for this example here) SendMessage(FindWindow(NULL,"jnaWnd"), WM_USER + 10, 0, (LPARAM...
If the message-only window exists in a different process, then you can't send a string via a raw pointer across process boundaries in the manner you are trying. The sent pointer is only valid in the context of the sending process, it will not point at valid memory which exists in the context of the target process. So...
68,696,585
68,696,701
How to use "else if" with the preprocessor #ifdef?
In my project the program can do one thing of two, but never both, so I decided that the best i can do for one class is to define it depending of a #define preprocessor variable. The next code can show you my idea, but you can guess that it does not work: #ifdef CALC_MODE typedef MyCalcClass ChosenClass; #elifdef USER_...
Here's a suggestion, based largely on comments posted to your question: #if defined(CALC_MODE) typedef MyCalcClass ChosenClass; #elif defined(USER_MODE) typedef MyUserClass ChosenClass; #else #error "Define CALC_MODE or USER_MODE" #endif
68,696,990
68,697,018
no matching function to call 'strlen'
I'm trying to allocate memory for my pointer char array but I keep getting no matching function to call 'strlen' int ItemList::getItemNames(char ** & itemNames) const{ int counter = 0; int MAX_NAME = 50; char buffer[MAX_NAME]; for (int i = 0; i < size; i++){ int length = strlen(list[i].getItemName(buffer));...
getItemName doesn't return anything (void as a return type means a function returns nothing). It modifies its argument. So you need to pass the buffer argument to strlen. list[i].getItemName(buffer); int length = strlen(buffer);
68,697,051
68,697,097
Convert first line of file into array C++
I have a file called file.txt 1 2 3 ugjfnuwd gjufjfg and I want to extract the first line of this file "1 2 3" and turn it into an array in c++ so the end result would look something like this [1, 2, 3] I've been experimenting and researching for around 2 hours with little progress. Please help
I would read the line into an std::string, then use an std::istringstream to parse the integers out of the line, something on this general order: // open the input file: std::istream infile("file.txt"); // read in the line std::string line; std::getline(infile, line); // put the line into a stringstream std::istrings...
68,697,196
68,697,227
Why do x+0 and x|0 have different results?
Why do x+0 and x|0 have different results? Below is my code. My environment is WSL (Debian Sid) + GCC 10.2.1. #include <stdio.h> /** * Do rotating left shift. Assume 0 <= n < w * Examples when x = 0x12345678 and w = 32: * n = 4 -> 0x23456781, n = 20 -> 0x67812345 */ unsigned rotate_left(const unsigned x, const int...
If x is an integer type with at most 32 bits, then x>>32 is Undefined Behaviour, which means that the result can be absolutely anything (and it can be a different anything in different programs). (Also true of x<<32.) [Note 1] From §6.5.7 para 3 of the C standard, concerning << and >> operators, emphasis added: If the...
68,697,228
68,697,700
Get result from array of member functions in c++
This is a part of Arduino program(C++). MCU is ESP32. I have defined a class. Inside it I have created an array of member functions. class IRDN_Padidar_Zone { bool callAnimation(); uint16_t Animate_None(enum_Effect inOut); uint16_t Animate_Print(enum_Effect inOut); uint16_t Animate_Print_Random(enum_Effect inOut); ui...
A non-static class method needs an object to run on. Like the first error message says, you must use the .* or ->* operator when calling a non-static method via a pointer-to-method. Also, when used as a class member, the array needs to specify how many elements it has, even though it has an inline initializer. Try thi...
68,697,325
68,697,371
C++ templates pointer-to-reference-type tomfoolery
I have the following struct static method: template<typename Edge1, typename Edge2, typename... Edges> requires std::derived_from<Edge1, Edge> && std::derived_from<Edge2, Edge> && (std::derived_from<Edges, Edge> && ...) [[nodiscard]] static constexpr bool are_multi_edges(const Edge1& edge1, const Edge2& edge2, const Ed...
Use std reference wrappers. References are not regular, and are unsuitable for use in std containers. Reference wrappers are half way between a reference and a pointer, but are regular enough to be container contents.
68,697,401
68,700,516
How does memory usage of thread_local scale with number of threads?
I presume C/C++ standards do not say anything about complexity so I am curious about specific implementations (I presume they all have same behavior). Assume I have the following C++ function. void fn() { thread_local char arr[1024*1024]{}; // do something with arr } And my program has 80 threads, 47 of them a...
This is likely largely implementation dependant though you can verify the behaviour of your implementation fairly easily. For example running the following program on windows (using a debug visual studio build to avoid optimisations removing the unused code): #include <iostream> #include <array> #include <thread> stru...
68,697,665
68,697,820
Is the const return type required in both function declaration and definition?
const int test(); int test(){ return 5; } int main(){ return 0; } Above does not compile in C++ with this error message: error: ambiguating new declaration of 'int test()' However it does compile fine in C. Knowing these are 2 very different languages, I was wondering if there's a specific feature in C++ which req...
I was wondering if there's a specific feature in C++ which requires it to have const return types in both the definition and declaration? No. Actually, it's the other way around. There is a specific feature in C that drops that requirement. From C documentation of function declarations @ cppreference.com: The return...
68,698,069
68,698,507
cin running only once inside while loop
I have seen another post with nearly the same title but it didn't help at all since they had a mistake in there code. I just want to get as many values as the client puts in and add them but it only takes the first input #include <iostream> #include <string> using namespace std; int issa_def() { int issa[] = {}; ...
What is the size of your arrays? You initialize them with {} so they are just an int* without any memory allocation. As soon as you insert values to issa[i] you will overflow. For a similar reason you cannot iterate from 0 to sizeof(issa) (including the latter). First, sizeof gives you the size in bytes, not the number...
68,698,240
68,698,288
c++ Std::accumulate for unordered map
I have a function which should accumulate all the values in an unordered map: int sum_val(std::unordered_map<char, int> vm){ auto addition = [](int a, std::unordered_map<char, int>::iterator b){ return a + b->second; }; return std::accumulate(vm.begin(), vm.end(), 0, addition); } However, when I try to comp...
You should have passed "dereferenced" iterator type. int sum_val(std::unordered_map<char, int>& vm){ auto addition = [](int a, const std::pair<const char,int>& b) { return a + b.second; }; return std::accumulate(vm.begin(), vm.end(), 0, addition); } @rjc810 you were looking in the wrong place imho: T...
68,698,430
68,698,497
find the frequency of a multi array
problem: Given a matrix of integers, count the amount of times each number 0-9 appears. Print out your results on one line in the following form: 0:number of zeros;1:number of ones;2:number of twos;3:number of threes;4:number of fours;5:number of fives;6:number of sixes;7:number of sevens;8:number of eights;9:number o...
The code you show gives output based on the frequencies for the specific array init visible in the shown code. That array init contains no zeros, so the output should start with "0:0" and it does. (Actually required for the shown array init would be "zeros:0", but I stick with your codes basic concept of output and on...
68,698,641
68,698,670
emplace_back() vs push_back() for vector
I knew this has been asked quite a lot, and I have seen many explanations quoting "emplace_back construct in place, push_back() construct and copy". Some posts asked why emplace_back calls the copy constructor because they did not reserve the memory for the vector. But for the below case, I cannot figure out what empla...
emplace_back constructs the element in-place by forwarding the arguments to the constructor of element type, so you can v.emplace_back(1); // forwarding 1 to Int::Int(int) to construct the element directly push_back always expects an element, i.e. an Int. When you pass 1 to it as v.push_back(1);, implicit conversion h...
68,698,769
68,699,085
use of ! operator before a function call
I encountered a code with the function arithmetic(), basically, for multiplication, the thing that bothered me was the use "!" the NOT unary operator before the function call. code goes like:- #include<iostream> using namespace std; int arithmetic(int,int); int main() { return !arithmeti...
return !arithmetic(11,9); applies the ! (not) operator to the result of arithmetic(11,9). That is, it converts the result of arithmetic(11,9) to a boolean value and inverts it. Thus it's true when arithmetic(11,9) returned 0 and false in any other case. This boolean value will be converted to an integer again, because ...
68,698,800
68,698,844
Why does std::map::operator[] assignment require an argumentless constructor?
I have the following minimal example reproducing an error in my code: #include <unordered_map> #include <iostream> class B { public: B(int b) : m_b{ b } {} int m_b; }; int main() { using std::cout, std::endl; std::unordered_map<int, B> ab{}; ab[1] = B(3); //ab.insert(std::pair<int, B>(1,...
Why is [a constructor for B without any arguments] needed? This is because std::map::operator[] required the mapped_type (i.e. in your case B) to be default constructable. Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second; ...
68,698,897
68,699,016
Call of overloaded function is ambiguous... But Why? Template problem
I've been writing a simple program that would swap integers or arrays using templates. I am not sure why, but when I try to run this program it shows me that the function is ambiguous, although function swapping arrays takes three arguments and the one swapping numbers takes 2. Here's the code: #include <iostream> usi...
As mentioned in the comment you should do some changes to remove the ambiguity between the std::swap and yours. remove using namespace std; and use std:: before cout: #include <iostream> template<typename T> void swap(T &a, T &b) { T dummy = a; a = b; b = dummy; } template<typename T> void swap(T a[], T b[...
68,699,339
68,710,687
Must aggregate field constructor be public to use aggregate initialization in C++?
Please consider the code with aggregate struct B having a field of class A with a private constructor: class A { A(int){} friend struct B; }; struct B { A a{1}; }; int main() { B b; //ok everywhere, not aggregate initialization //[[maybe_unused]] B x{1}; //error everywhere [[maybe_unused]] B y{}; //ok in G...
... with aggregate struct B ... For completeness, let's begin with noting that B is indeed an aggregate in C++14 through C++20, as per [dcl.init.aggr]/1 (N4861 (March 2020 post-Prague working draft/C++20 DIS)): An aggregate is an array or a class ([class]) with (1.1) no user-declared or inherited constructors ([cla...
68,699,383
68,700,060
Unable to get result of std::string function in C++ to C# Interop
What I am trying to achieve: I am trying to access a C++ application's functions through its DLL in a C# (Interop). Issue which I am facing right now: When i create a std::string return type function in C++ and calls it through its DLL in C# code there is now output at all. Code which I have written for C++ APP extern ...
std::string will never work here as the marshaller does not know how to free it. Instead, you need to pass in a buffer from the C# side, like this class Program { [DllImport(@"CPPSample.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi,EntryPoint = "SM_Interop_API_Add")] ...
68,699,696
68,699,812
Which of these two approaches is more cache friendly?
I have a set of multiple vectors on which I need to perform exactly the same actions in a for loop. And I am not sure what is a better way to do it: for (/*...*/) { std::rotate(/*...*/); // Vec1 std::rotate(/*...*/); // Vec2 std::rotate(/*...*/); // Vec3 std::rotate(/*...*/); // Vec4 std::rotate(/*....
Which of these two approaches is more cache friendly? If a successive iteration operates on elements that are near to those on the previous iteration, then the second approach is potentially cache friendlier. Which is more efficient approach? The one which you can measure to be more efficient.
68,699,806
68,699,849
Strange C++ Type Casting
While following an openGL tutorial, I came across this piece of code: unsigned char header[54]; // [...] unsigned int dataPos = *(int*)&(header[0x0A]); I don't understand the use of *(int*)&. Why not simply use (int) ?
Why not simply use (int) ?' Because (int)header[0x0A] would convert only a single byte at address 0x0A when the intention is to reinterpret a sequence of sizeof(int) bytes instead. That said, the example has undefined behaviour because it violates "strict aliasing" rules. Also, I don't know why they cast to int* and ...
68,700,336
68,700,440
My code is showing 'true' as output instead of 'False'
So there is a question in Leetcode in which we need to tell whether two binary trees are identical or not. So my function is working correctly for the inputs [1,2,3] and [1,2,3] but it is printing 'true' for the inputs [1,2] and [1,NULL,2] instead of printing 'false'. Please can anyone tell me what have i done wrong in...
You're completely ignoring the results of those recursive calls. The point using recursion here is that two trees are the same if: Their values are the same AND Their respective children are the same. You're testing the former, but never reaping the results of the latter. In reality, what you really should be trying ...
68,700,633
68,700,763
Template specialization issue
There is an error when including "x.h" below from multiple C++ source files. x.cpp:(.text+0x0): multiple definition of `void f(A&, B const&)' /tmp/ccdXc4Sz.o:main.cpp:(.text+0x0): first defined here collect2: error: ld returned 1 exit status What happens here? How can it be rewritten to work? x.h #pragma once #includ...
Specialized templated function is not template anymore, it should be treated as normal global function. So, place it to .cpp file, or declare as static or inline. – answer by Alex F
68,700,716
68,701,221
Linking LLVM IR Libraries
I am following along with the LLVM Kaleidoscope Tutorial (Ch. 3), and am encountering errors (undoubtedly from my Makefile) after attempting to link LLVM IR libraries. My Makefile and project structure: CPP=clang++ CFLAGS=-g -Wall -std=c++14 LDFLAGS:=$(shell llvm-config --cxxflags --ldflags --system-libs --libs core) ...
Your question is, in fact, a duplicate of the #2 answer there. When you want to create an object file you MUST use the -c option. That's what the -c option means. If you don't want "a plethora of warning messages saying the linker inputs/arguments are unused" then, you know, don't add the linker inputs and arguments w...
68,701,202
68,770,401
Problem turning 2D array into 1D how to convert matrix of vertexes into matrix of xy values
I want to turn a 2D array like this [ [x, y], [a, b], [z, e] ] into [x, y, a, b, z, e] I have tried multiple thing with indexes and for loops but most of them don't work and the one that did was very buggy and sketchy how do I do that i c++ i am a beginner, and I am trying to learn about matrices
The best approach would be to create a new array. Use the following code which is quite simple and clear as well int arr[rows*columns]; int a=0; int array[rows][columns]={assign values}; for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ arr[a]=array[i][j]; a++; ...
68,701,360
68,705,960
How to calculate chroma image in Halide?
I am currently evaluating if Halide is a good choice for my programmes. As a short Hello Halide example, I wanted to convert an rgb image to hsl space. However, when trying, I got stuck at the first stage. In order to convert to hsl, I would need to calculate the chroma image first. This is the difference between the m...
Here's an example Halide program for converting from RGB to HSL: #include <Halide.h> #include <halide_image_io.h> using namespace Halide; using namespace Halide::Tools; int main(int argc, char *argv[]) { Buffer<float> input = load_and_convert_image(argv[1]); Func max_channels, min_channels, chroma, result_hsl...
68,701,398
68,702,076
Build error on connection of signal_response of gtkmm4 FileChooserNative to the function
I need to connect signal_response of FileChooserNative to the function, but I got an error when I try to use code from example from Programming with gtkmm 4 book. When I try to compile this (g++, XCLT, macOS Big Sur): void MyWindow::on_button_browse_clicked(){ auto dialog = Gtk::FileChooserNative::create("Please choose...
You have a build error because the type of the extra argument you provide is not Gtk::FileChooserNative*, but rather Glib::RefPtr<Gtk::FileChooserNative> (this is what hides behind auto). So you should have: void MyWindow::on_folder_dialog_response(int response_id, Glib::RefPtr<Gtk::FileChooserNative>& dialog) instead...
68,701,403
68,701,595
Destructor crashes when working with pointers in Visual Studio
When I'm using a pointer to an instance to this class, for some reason it crashes when it comes to the destructor. It works when I'm not using pointers The weirdest part is that it works in VC Code but not in Visual Studio. Polynomial.h class Polynomial { private: int32_t* coeffs; uint32_t deg; public: P...
Your overload of the << operator takes its argument by value; so, in the line, std::cout << (*p); a copy of *p is made and, when the output is done, that copy is destroyed. However, as pointed out in the comments, you haven't implemented a proper copy constructor, so the compiler provides a default, which simply copies...
68,701,570
68,703,505
How to check if a filesystem::path is a file?
I have a function that should write binary data, the path is supplied by the user. How can I check if a given filepath is a writable file path? is_regular_file() returns false for a given file path: D:/SomePath should be a writable file (note the missing / at the end) D:/SomePath/File.txt is also a writable file D:/So...
D:/SomePath should be a writable file (note the missing / at the end) D:/SomePath/File.txt is also a writable file D:/SomePath/File is a writable file D:/SomePath/SomeSubDir/ is a directory. I would argue that the term "writable file" does not apply some of these. What you're asking for is if the path has a filenam...
68,702,530
68,702,580
Converting string to integer using stoi() and atoi()
C++ compiler g++ 17 GCC 9.1.0 I was trying to convert the digts that are present in the string and sum them up but i was not able to do it, on geeksforgeeks article I found out that they used atoi and coverted the string to c style string using c_str(). After reading about atoi and stoi I found out that atoi does not r...
If you have multiple non-digits in a row in the input, you'll try to convert an empty string to an integer. You need to check if temp is empty before trying to convert it. #include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; // s has 1xyz23000 int n = s.size(); int i = 0; ...
68,702,927
68,702,979
How is this struct initialisation working?
I came across a piece of code that had structs and I am now thoroughly confused about how automatically the constructor of the struct is being called. I made a dummy code just to understand the concept. For example, struct obj { int a = 0, b = 2; obj (int aa) { a = aa; } obj (int aa, int bb) {...
You can use a braced initialization list to invoke the constructor: calcSum({5, 3}); A somewhat broad term for this feature of C++ is called "implicit conversion". If the type of the object being "assigned to" (or constructed, which in this case is a function parameter) does not match the type of the object being "ass...
68,703,443
68,748,557
Unsharp mask implementation with OpenCV
I want to apply unsharp mask like Adobe Photoshop, I know this answer, but it's not as sharp as Photoshop. Photoshop has 3 parameters in Smart Sharpen dialog: Amount, Radius, Reduce Noise; I want to implement all of them. This is the code I wrote, according to various sources in SO. But the result is good in some stag...
First of all, judging by the artefacts that Photoshop left on the borders of the petals, I'd say that it applies the mask by using a weighted sum between the original image and the mask, as in the answer you tried first. I modified your code to implement this scheme and I tried to tweak the parameters to get as close a...
68,703,702
68,704,088
ARM, how the content of the specified section name is not overwritten?
I am working on a fw written in C++ with mbed-os for a STM32F4 series MCU. There is a portion of code that should be executed only at the first boot. To achieve this goal, the developer uses a memory section named mysection for storing a flag, named MAGIC_INIT_CODE. mysection is defined in the ARM_GCC compiler linker f...
this line place uint64_t object into .mysection section and initialize it to MAGIC_INIT_CODE. If .mysection is placed in flash it will be permanently there. It is being programmed when you upload your program to your micro. Ihis value will be the permanently (it cannot be changed by the standard C operations. You can o...
68,703,817
68,708,697
why input events are not being captured at sometimes, in c++
#include <Windows.h> #include <vector> using std::vector; class event_handler{ private: DWORD n_evnts_read=0,n_evnts=0,evnt_type=0,mode=0; public: int rec_indx = 0; vector<INPUT_RECORD> inrec; KEY_EVENT_RECORD kev; MOUSE_EVENT_RECORD mev; HANDLE hndlin = GetStdHandle(STD_INPUT_HANDLE); HAN...
You are not processing every event that is read. Your code has the potential to throw away a lot of events. Each time you call cap_evnt_...(), if there are any new events available to read, you throw away any events you have already read into the vector that have not been processed yet. Try something more like this in...
68,704,052
68,704,078
Why can I not pass 'this' to an inner class's method in this case?
I have a class containing an inner class that looks somewhat like this: class Foo { class Bar { public: void update(const Foo& f) { //Updates using public getters of Foo } }; public: void doStuff() const { b_.update(*this); } private: Bar b_; }...
doStuff is const therefore b_ is also const in this context so calling the non-const update function is not allowed. If doStuff needs to modify b_ it should not be marked const, you could mark b_ as mutable but that's rarely the correct thing to do.
68,704,115
68,713,878
C++: How to pass the object from a unique_ptr into a function by value?
I would like to use the cereal library from this github page to load xml into objects. Up to this point everything is fine. But in my application, it is a bit more complex: the object that needs to be loaded/filled by the xml file, have to be accessed through polymorphic pointer. Therefore, if a use a raw pointer, the ...
The problem is that you don't load the file the same way you write it. If you write it using smart pointers, then the file contains additionnal data including a node polymorphic_id. You would have a file similar to this one: <?xml version="1.0" encoding="utf-8"?> <cereal> <value0> <polymorphic_id>2147483649...
68,704,309
68,885,780
What is causing fstream::open to fail here?
The Problem I'm working on a simple Notepad app in Win32 C++. However I've run into a problem opening a file to save to. There is quite a bit of code (which you can find here) but the line causing the error is in the file Event Handlers.cpp. Specifically, line 25 wnd.file.open(wnd.filePath, std::ios_base::out); throws...
After a lot of digging and experimentation, I finally found the answer. The problem was in the TopLevelWnd constructor. TopLevelWnd(int x, int y, int ncX, int ncY, int width, int height, int ncWidth, int ncHeight, DWORD styles, DWORD exStyles, const wchar_t* className, const wchar_t* name, HINSTANCE hInstance = GetModu...
68,704,640
68,704,654
Why does this simple use of SFINAE & type traits to overload a function template leads to ambiguous call?
I'm trying to use type traits to provide a couple of overloads for a specific function, so that I don't have to specify the template parameter when calling said function, and it can work for any data type and different types of containers: #include <type_traits> #include <vector> #include <initializer_list> template< ...
This should be std::enable_if_t not std::enable_if. Or since you tagged C++11, you can do std::enable_if<...>::type std::enable_if<false> is not a substitution failure, only std::enable_if<false>::type is.
68,704,952
68,705,054
I don't want the character "a" to be compared more than once if its already matched string comparison C++
I have two strings: string alphabet = "abcdefghijklmnopqrstuvwxyz"; string input = "abc"; You see how after the i loop executes, the first character of abc_letters is 'a', comparing that to the j loop character input_letter after it executes is also 'a', which is a match. That character gets stored into the matched st...
Once you find a match, you need to break the j loop, so you can then continue the i loop. Try something more like this: string listMissingLetters(string input) { string missing, matched; const string alphabet = "abcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < alphabet.length(); ++i) { b...
68,705,120
68,706,526
Converting String to Hex Throws Error: 'std::out_of_range'
I have a really simple program that converts a hex string to it's int value. The code seems fine, but it throws a runtime error: terminate called after throwing an instance of 'std::out_of_range' what(): stoi Here is the code where the error is being caused: int dump[4]; string hexCodes[4] = {"fffc0000", "ff0cd044",...
stoi will throw out_of_range if the value is not in the range that int can represent. The number 0xfffc0000 (4294705152) is not in that range for a 32-bit int as it is greater than 2^31-1 (2147483647). So throwing the exception is precisely what it must do. unsigned would work, but there is no stou, so use stoul. Yo...
68,705,368
68,705,387
Is there any predefined function in C++ to find the minimum and maximum element from a given array?
I have an array double weights[]={203.21, 17.24, 125.32, 96.167} I wish to calculate the minimum and maximum element by using a function if there's any? Please help
Yes, there is: std::minmax_element. There's also std::max_element for finding just the max and std::min_element for finding just the min. As applied to your code: #include <algorithm> #include <iterator> int main() { double weights[]={203.21, 17.24, 125.32, 96.167}; auto minMaxIterators = std::minmax_element(s...
68,705,604
68,705,694
Changing function return value in C++ (In runtime)
i want to change the return value of an external function (in runtime) which is inside another dll which gets loaded when the program starts. Pratical example of what i want to do: Function inside the dll: int numberOfMoney() { return 0; } My main program: HMODULE handle = LoadLibraryA("/myDll.dll"); auto ...
You can alter a function or the return of a function at runtime through hooking. There's several different techniques of hooking a function. The most common is called hot patching which in x86 overwrites the first five bytes of a function with a relative jump instruction to the middleware function. The middleware funct...
68,705,856
68,706,028
Vector is not filling with the information in my text file C++
Hi I am trying to fill a vector with the information from a text file. The text file looks something like this: 10 8 5 6 15 4 I wrote some code in C++ trying to do this and it is not being filled. Here is my code: #include <iostream> #include <fstream> #include <vector> void duplicate() { ifstream in("Measured-Is...
So it turns out the problem was that my first row in the text file was a label that was a string so because I made my vector 2 ints it was getting messed up and not filling. I deleted the label and now it fills fine.
68,706,095
68,706,133
Pass multidimensional array with variable size as argument of function
I have this code: int m, n; cin>>m>>n; double A[m][n]; //read values for A How can I pass A to a function?
Variable length arrays are a C feature and not supported in standard C++. However some compilers such as gcc support it as an extension. On those compilers that do support it, you would need to pass the array dimensions as parameters and use those parameters as the array size: void handle_array(int m, int n, double A[...
68,706,290
68,734,374
How to reduce flickering/lag on curses?
Currently trying to solve an issue with flickering in a very small game I'm making in ncurses with C++. The flickering isn't abhorrent but I could imagine it being far more annoying when more entities are being rendered/moving at once. Code below. There's also a header file but I don't believe it's relevant here. #incl...
This chunk is the main contributor to flicker: erase(); if ((ch = getch()) == ERR) { drawEntity(player); } The erase modifies the whole screen, and the following getch does a refresh (actually clearing the screen) before your code follows up by repainting the screen. If you change the way it's organized so that th...
68,706,372
68,708,103
Is there any way to make a keylogger in linux without root?
What I'am trying to do I made a keylogger by reading the event file, but it needs root permission to work.I want to make a keylogger that can work without root permission. My device ubuntu16.04 using X11 ubuntu21.04 using Wayland My thoughts I understand that it is feasible on windows, and it can also be implemented ...
It may be possible, but any non root solution will depend on the keyboard virtualization tool. Let us look how (modern) OS work: the hardware is under the exclusive control of the kernel and its drivers. It is possible to implement a keylogger at that level that would only be kernel dependent but it requires admin pri...
68,706,585
68,706,680
Guaranteed copy elision and deleted copy/move constructor when throwing an exception
Since C++17, the meaning of prvalue has changed, which makes copy elision guaranteed in some cases. From cppreference, the copy/move constructors need not be present or accessible in that case. When an exception is thrown, the exception object is copy-initialized, and the copy/move may be subject to copy elision. But i...
Your understanding of the standard is correct, in so far as your analysis of that paragraph actually applies. But it doesn't apply, because no constructor is ever considered for copy-initialization. Guaranteed elision is something of a misnomer; it's a useful explanation of the concept, but it doesn't reflect exactly h...
68,707,076
68,721,539
Understanding how to read UID from RFID Arduino
I was wondering if someone could help comment on each line and go through the process of this code I found online? I seem quite confused especially with the ternary operator used. I would like to use it for my project but I don't like to use code that I do not properly understand. This code prints out the UID of the R...
The vast majority of what's going on here is happening inside the MFRC522 class, which we can't see because it's included from some header file. For an explanation of that you should probably go to the documentation of wherever you got MFRC522.h However you specifically asked about the ternary, seen here: void printHe...
68,707,433
68,707,476
What is the difference between using an operator overload for << and cout?
I genuinely do not understand the difference. Here's a few examples: Using the std::cout #include <iostream> #include <list> using namespace std; void print(std::list<std::string> const &list) { for (auto const &i: list) { cout << i << endl; } } int main() { std::list<std::string> list = { "bl...
You insert the list into the character stream like this: cout << list << endl;. That calls your overload, which inserts the list into the character stream like this: os << list << endl;. That calls your overload, which inserts the list into the character stream, which calls your overload, which inserts the list into th...
68,707,755
68,708,876
Visual Studio debugger sets the upper half of AVX registers to zero
When debugging some code using AVX, I was getting results which made no sense. I reduced my program to the following: #include <iostream> #include <immintrin.h> int main() { while (1) { static float v[] = {1, 2, 3, 4, 5, 6, 7, 8}; __m256 v8 = _mm256_load_ps(v); std::cout << v8.m256_f32[...
Visual studio 2017 15.9.7 fixes a bug which corrupts AVX/MPX/AVX512 registers while Debugging, you should update to the latest version, 15.9.3 is nearly 3 years old.
68,707,790
68,707,915
Converting QString to PCWSTR on Windows
Why does the following code from this answer work: QString username = "Bond"; std::wstring username = username.toStdWString(); PCWSTR username = username.c_str(); When the following does not: QString username = "Bond"; PCWSTR username = username.toStdWString().c_str();
The temporary object gets destroyed, the result of the c_str() is invalid after that point.
68,707,926
68,709,083
How do I make CMake find a library at a custom location (cross-compile raspberry pi 4)
How do I point find_package() to my "custom" directory $SYSROOT/usr/lib/arm-linux-gnueabihf/ so it can find libz.so ? I have a library in this location: /home/user/bla/sysroot/usr/lib/arm-linux-gnueabihf/libz.so With a header that can be found here: /home/user/bla/sysroot/usr/include/zlib.h With CMake I try: cmake_mi...
A handy way to check if your variable is as expected. message(STATUS "sysroot_dir: ${sysroot_dir}") You should change sysroot's value by set(CMAKE_SYSROOT /your/path) instead of set(sysroot /your/path) which directly set the variable inside cmake. Reference here
68,708,076
68,711,566
How to add compile options to a CMake FetchContent-dependency?
I have a C/C++ project in which I want to use CppUTest. So I include the dependency of CppUTest with: include(FetchContent) FetchContent_Declare( CppUTest GIT_REPOSITORY https://github.com/cpputest/cpputest.git GIT_TAG latest-passing-build CONFIGURE_COMMAND "" ...
Do not use set(CMAKE_<LANG>*. Use *target* interfaces. If you do not want all stuff to be compiled with a specific option, do not set them globally. Instead: set_target_properties(mytests PROPERTY CXX_STANDARD 11 etc. ) target_compile_options(mytests PUBLIC -option1 -option2 ...) Anyway, SET(CMAKE_<LANG>_* aff...
68,708,352
68,708,387
Why memset works wrong in apple clang compiler?
I found something strange doing problem solving with c++. Initializing an integer array with loop works nice, but initializing it with memset function works wrong. Below is the sample program. #include <cstdio> #include <limits> #include <cstring> using namespace std; const int SIZE = 10; const int INF = numeric_li...
memset converts the second operand (argument) into unsigned char and copies it into all destination bytes. In your case, this resulting unsigned char is 0xFF, which copied into all elements of type int gives their values -1. Documentation link: https://en.cppreference.com/w/cpp/string/byte/memset. Recommendation: Don't...
68,708,441
68,708,516
Why can a reference declared with constexpr be bound to an Indeterminate value variable?
int aaa; int& v = aaa; int& rf = v; constexpr int& crf = rf; int main(){ } I'm wondering why all compilers do agree on this example is well-formed? Isn't a constexpr variable should have a value that can be known during compiler time? Since the value of aaa has an Indeterminate value, why can this example be accepeted...
For this example, it appears to me it's equivalent to ask why the variable rf could be used in a constant expression. As per [dcl.constexpr#10], the full-expression of the initialization of crf should be a constant expression. According to [expr.const#11] A constant expression is either a glvalue core constant express...
68,708,567
68,708,779
C++ Buffer Overflow, strcpy, fgets, sprintf showing runtime error
#include <stdio.h> #include <stdlib.h> #include <string.h> int check_authentication(char* password) { int auth_flag = 0; char* password_buffer; char* dept; password_buffer = (char*)malloc(16); dept = (char*)malloc(10); printf("Your department?"); fgets(dept, 10, stdin); //line 11 strcpy_...
The program doesn't request password, because it expects it to be passed as an argument like this: 'c:\yourapp.exe yourpass'. If you want it to request a password, you should modify it a bit. Add following lines before if (check_authentication(argv[1])) line in your main function. char password[16]; printf("Password: "...
68,708,614
68,709,148
Is it valid to overload function with extra non-deducible template parameter?
The following code compiles and works fine with gcc (9), clang (11) and msvc (16.28): template <class A> struct X { A a; constexpr X(A a) : a{a} { } }; template <class A> constexpr auto fn(X<A> const& x) { return X<A>(x.a - 1); } template <class Xs, class A> constexpr auto fn(X<A> const& x) { return...
There are two fn functions with identical declarations except for the extra Xs parameter in the second one. That's fine, you can overload function templates using different arguments or different template arguments. in the call fn(x1), Xs cannot be deduced so the second overload of fn is discarded gently (SFINAE?)?...
68,709,314
68,709,354
I'don't understand leet code variable declaration
Correct Solution class Solution { public: int pivotIndex(vector<int>& nums) { int rightsum = 0; int leftsum = 0; // this problem point for(int i = 0; i < nums.size(); i++){ rightsum += nums[i]; } for (int i = 0; i < nums.size(); i++){ ...
This int rightsum, leftsum = 0; // this problem point is equivalent to int rightsum; int leftsum = 0; rightsum is not initialized, it has an indeterminate value. Then here rightsum += nums[i]; you are reading from rightsum before initializing it. That is undefined behavior. It is possible that in a debug build right...
68,710,010
68,710,141
Understanding size() method of std::list iterator
std::list<std::vector<unsigned long> >::const_iterator it; // ... std::vector<unsigned long> non_mf; non_mf.reserve(it->size()); What's the meaning of it->size() above? Size of iterator, what does it mean?
You aren't calling a member function if the iterator because you don't use the operator .. Operator -> is an indirecting member access operator. It indirects through the left hand operand and accesses the member of the indirection result. When you indirect through an iterator, you get the object that the iterator point...
68,710,099
68,710,434
C++: Simplifiying a #define
I have a #define with generates a enum class and a corresponding output operator the the generated enum class.(see below) #define ENUM(N, T, N1, V1, N2, V2, N3, V3, N4, V4, N5, V5, N6, V6, N7, V7)\ enum class N : T {\ N1 = V1,\ N2 = V2,\ N3 = V3,\ N4 = V4,\ N5 = V5,\ ...
Sticking relatively close what you have right now, you can take advantage of the BOOST_PP_SEQ_FOR_EACH macro from Boost.Preprocessor, which could look something like this: #include <boost/preprocessor.hpp> #define ENUM_FIELD(I,_,F) F, #define ENUM_OUTPUT_CASE(I,N,F) case N::F: os << BOOST_PP_STRINGIZE(F); break; #def...
68,710,283
69,344,725
What Should Be The Logic To Print Intermediate Steps Of QuickSort
I am working towards displaying intermediate steps of sorting while my program on quicksort executes. In Essence, after every iteration the console window must show the current situation of the sorting of the array in progress. I was able to add the total counts of Swaps and Comparisons in my Program but am not able to...
I have an implementation in Java where the console displays steps of literally everything that is going on within the program. Since it also includes printing intermediate steps of arrays while sorting, I am sure it will be helpful to you. import java.util.Arrays; public class QuicksortDemo { //Passes an array, the s...
68,710,826
68,710,872
How to print exception message in C++ with catch(...) {..}
This is the sample code int main() { string S; getline(cin, S); try { int val = stoi(S); } catch(...) { // cout << //exception message ; I want to print the exception message. } return 0; } Is it possible to print an exception message in this case ?. The message will show what k...
All C++ library exceptions inherit from std::exception. So the simplest thing to do is to catch a reference to it: catch (const std::exception &e) { std::cout << "Caught " << e.what(); << std::endl; } This will catch all exceptions thrown by stoi.
68,710,983
68,711,670
Find all cyclic permutations of a string in O(n)
Given the problem: Find all cyclic permutations of a string For example: given a string: "abcd" All the cyclic permutations of a string would be: "abcd", "dabc", "cdab", "bcda" Here's what I have tried out: for(int i = 0; i < str.size(); i++){ permu.push_back(str); str.insert(0, 1, str[str.size()-1]); str.e...
Here's another approach if you don't want to create another string: for(int i = 0; i < str.size(); i++) permu.push_back(str.substr(i) + str.substr(0, i));
68,711,107
68,713,488
Dangling reference when returning reference to reference parameter bound to temporary
This question refers to Howard Hinnant's answer to the question Guaranteed elision and chained function calls. At the bottom of his answer, he says: Note that in this latest design, if your client ever does this: X&& x = a + b + c; then x is a dangling reference (which is why std::string does not do this). The parag...
I like to keep an example class A around for situations like this. The full definition of A is a little too lengthy to list here, but it is included in its entirety at this link. In a nutshell, A keeps a state and a status, and the status can be one of these enums: destructed = -4, self_move_assign...
68,712,199
68,712,415
isssue about creating my own templated function to sort
I'm practicing using templates and lambdas. I decided to make sorting function which will sort vector of any type by declaration in lambda(very similar to std::sort()), but I came up with an issue. My issue is in this line: void sorting(vector<T>& files, int beginning, int end, s...
Issues with: template <class T> void foo(std::vector<T>&, std::function<bool(T, T)>) is that T is deducible from several place and should match lambda is NOT a std::function, even if convertible to. One possibility is to get rid of std::function and take any callable (Possibly use concept in C++20) template <typenam...
68,712,232
68,712,488
Why won't this object-oriented OpenGL code draw a triangle, but the expanded version does?
The code is too long to put on Stack Overflow, so I put it in a Gist. To use the code, you need to use only one of the main.cpp files. I am learning from learnopengl.com and I am at the point where I draw the triangle. However, my Object Oriented code does not draw the triangle. When I expanded my code (like macros, ...
Not sure about other problems, but this is definitely wrong: inline static void data(float vertices[], GLenum usage = GL_STATIC_DRAW) { glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, usage); } inline static void data(const float vertices[], ...
68,712,376
68,712,618
0x7C29F7A9 ( ucrtbased.dll )Exception thrown at (Project3.exe):0xC0000005: access violation while writing location 0x00740000
I'm studying C++, I ran these codes in Visual Studio, but I got an access violation exception, VS told me the exception happened at line:24, in strcat() in func mystring& operator+(mystring& z). Could you please help me find out the reason? #include <iostream> #include <string.h> #pragma warning(disable:4996) using nam...
On line 47: t1 = i + s3; You are concatenating i onto the buffer that underlies s3. However, the buffer that underlies s3 is i itself. So you are concatenating a string onto itself. This wont end well. As https://en.cppreference.com/w/c/string/byte/strcat notes: The behavior is undefined if the strings overlap. (Note t...
68,712,964
68,713,157
Can C++ struct static member variables shadow non type template parameters?
msvc compiles the following code(with /permissive- compiler switch), clang and gcc do not: template<auto val> struct S{ static constexpr auto val = val; }; int main() { return S<4>::val; } I presume that this is just a msvc bug, but I am curious if maybe standard is ambiguous here.
The standard is unambiguous on this, a template parameter can't be redeclared for any reason, see [temp.local]/6: A template-parameter shall not be redeclared within its scope (including nested scopes). A template-parameter shall not have the same name as the template name. [ Example: template<class T, int i> class Y ...
68,713,302
68,714,383
Can a lambda instantiate a template function?
Questions regarding the use of C++14 generic lambdas or C++20 template lambdas are typically about generating lambdas with the appropriate parameterized types. My question is, is it possible for a lambda parameter, or its evaluation, to force the instantiation (or specialization) of a template, e.g., a template functio...
The answer to your question is technically yes, lambda bodies can instantiate template functions. The actual example doesn't work, because int n as a parameter can't be used that way. There is an easy workaround template<auto x> using constant_t = std::integral_constant< std::decay_t<decltype(x)>, x >; template<auto x...
68,713,317
68,713,590
Using ParseDelimitedFromCodedInputStream for reading from file?
I have a file with multiple protobuf messages in it, and look-up-table telling me where which message starts in the file. The messages are written delimited. In C#, I can just do something like fileStream.Position = message_start_index; ProtoMessage msg = ProtoMessage.Parser.ParseDelimitedFrom(fileStream); and be done...
The protobuf API makes heavy use of inheritance, so instead of looking at the constructors of ZeroCopyInputStream and CodedInputStream, you should be looking for their subclasses. The one you are looking for is google::protobuf::io::IstreamInputStream, a subclass of google::protobuf::io::ZeroCopyInputStream that adapts...
68,713,501
68,714,681
Read a file line by line in C++
I wrote the following C++ program to read a text file line by line and print out the content of the file line by line. I entered the name of the text file as the only command line argument into the command line. #include <iostream> #include <fstream> using namespace std; int main(int argc, char* argv[]) { char buf...
Apart from the errors mentioned in the comments, the program has a logical error because istream& istream::get(char* s, streamsize n) does not do what you (or I, until I debugged it) thought it does. Yes, it reads to the next newline; but it leaves the newline in the input! The next time you call get(), it will see the...
68,713,513
68,714,091
Convert a double to time point using std chrono library
I have a double value that represents an epoch time but added the accuracy of a micro second. So a number like this: double time_us=1628517578.547; std::chrono::time_point time(time_us); The above code doesn't;t work as I am getting the following error: no instance of constructor "time_point" matches the argument lis...
std::chrono:: is a lot to write everywhere, so I'm going to assume: using namespace std::chrono; time_point is not a concrete type, it is a class template: template<class Clock, class Duration = typename Clock::duration> class time_point; This means that you have to supply at least the first template parameter, and i...
68,713,608
68,714,323
C++ placement new after memset
Suppose there's a struct whose constructor does not initialize all member variables: struct Foo { int x; Foo() {} } If I memset some buffer to 0, use placement new on that buffer to create an instance of Foo, and then read x from that instance, is that defined behavior? void bar(void* buf) { memset(buf, 0, sizeo...
As a supplement to the other answer: On the off chance that anyone feels like handwaving this away as "technically undefined behavior, but safe enough for me", allow me to demonstrate how thoroughly broken the resulting code can be. If x is initialized: struct Foo { int x = 0; Foo() {} }; // slightly simpler bar()...
68,714,566
68,714,730
C++ What exactly happened here?
While doing a program, I came up with an unintended behaviour in dynamic arrays. After I did a few tests, I ended up with this code. #include <iostream> unsigned long index; template<typename T> class A { public: void Set() { T* target = new T[index]; for (unsigned int i = 0; i < index; i++) ...
Just look which values index will have. It is initialized with 0. So in the first test.Set(); you create an 0 length array. To even read it later is wrong and leads to so called undefined behavior. In the second call of set, index will have a value of 1, so you create an array of length 1 and initialize that first elem...
68,715,136
68,715,963
wxWidgets: Frame size is not changing in Image panel
I am using wxWidgets 'An Image Panel' code. Here I made only one change. I want frame size should be equal to image size, My Image size is 762x463, but my frame size is different. frame SetSize function is not working. wxImagePanel::wxImagePanel(wxFrame* parent, wxString file, wxBitmapType format) : wxPanel(parent) { ...
To make the frame sized to display the image, you need to make 2 changes: In the constructor wxImagePanel::wxImagePanel, you need to add a line to set a minimum size for the image panel. wxImagePanel::wxImagePanel(wxFrame* parent, wxString file, wxBitmapType format) : wxPanel(parent) { image.LoadFile(file, format...
68,715,478
68,727,680
PyImport_Import fails to import module that contains imports
I'm working on a c++ project that needs some functionalities included in a python library (scipy.stats). I created my python script that uses the libray and my idea is to pass the data from c++ to the python script, call the function and get the return value from python. But then when I do PyImport_Import(pName), it re...
I found the solution. This happens because the debug symbols of numpy and scipy are missing. Setting visual studio in release mode solved the problem
68,716,285
68,716,682
Take substring from a regex capture group
I have this piece of C++ code: std::string s ("%r34 = add i32 %r33, 1\n"); std::regex e ("\\b(r)([^ ]*)"); // matches words beginning by "r" std::cout << std::regex_replace (s,e,"r$2"); The output I get is: %r34 = add i32 %r33, 1 My first question is there a way to remove the last character in the capture group $2 ...
To remove the second last digit after 'r', you may use: \\b(r)(\\d*)\\d ...and substitute with: r$2 Regex demo - C++ demo If the chars that follow 'r' are not necessarily digits but you want to exclude the comma, you may use the following instead: \\b(r)([^\\s,]*)[^\\s,] To match only if 'r' is preceded by '%', use:...
68,716,831
69,663,040
run-vcpkg and run-cmake in github actions: The system cannot find the path specified on windows only
I try to make a new setup using github actions with CMake and vcpkg. All the configurations are working except the windows one. A strange error occurs and I'm not sure why it happens and I'm not sure how to fix it: ► Run lukka/run-cmake@v3 tool: D:\a\_temp\909795809\cmake-3.21.1-windows-x86_64\bin\cmake.exe tool: D:\a\...
The problem has been reported here and it has been fixed: https://github.com/microsoft/vcpkg/issues/19552 Context: when run-cmake launches CMake on Windows with the vcpkg toolchain, unless CC/CXX env vars are already defined, the environment is setup for the MSVC toolset by running the vcpkg env --triplet <triplet> com...
68,717,308
68,717,435
Can a friend function in C++ have a default argument whose type has a private destructor?
In the next example the class U with private destructor has a friend function foo. And this friend function has argument of type U with default value U{}: class U{ ~U(); friend void foo(U); }; void foo(U = {}); Clang and MSVC accept this code, but GCC rejects it with the error error: 'U::~U()' is private within this c...
C++20 [class.access]/8 provides as follows: The names in a default argument (9.3.3.6) are bound at the point of declaration, and access is checked at that point rather than at any points of use of the default argument. Access checking for default arguments in function templates and in member functions of class templat...
68,717,312
68,717,465
How to remove a string in a list of list of string
I tried to follow the erase example for sample iterator over list but I can't make it work. Here is the code so far: for (list<list<string>>::iterator itr = listOfList.begin(), ; itr != listeOfListe.end(); itr++){ if (condition) { for (list<string>::iterator it6 = itr->begin(); it6 != itr->end(); it6++) { ...
You are trying to call erase() on an iterator itself, not on the list that the iterator refers to. That is why you are getting the compiler error. You need to dereference the iterator via operator* or operator-> to access the list to call erase() on. Also, your inner loop is not accounting for the fact that list::era...
68,717,970
68,718,034
Problem with deleting a line, that consists the searched word
Data.txt file: John Smith Freshman U2010001 Kirti Seth Freshman U2010002 Nick Johnson Freshman U2010003 Alan Walker Freshman U2010004 Peter Foster Freshman U2010005 As soon as a user enters his/her ID, the program finds the line number, where the ID, that has been entered exists, and a new file NEWFILE.txt should stor...
You are misusing the ifstream::eof() method. More importantly, you are using 2 separate loops, 1 loop to find the ID to delete, and 1 loop to copy all lines AFTER that ID, ignoring all lines BEFORE the ID. Using 1 loop for everything will suffice instead, eg: #include <iostream> #include <stream> #include <string> u...
68,718,078
68,718,105
C++ Inheritance: Variable with Type of a Base Class
Let's imagine we have two classes. class Base {}; class Derived : public Base {}; In another part of my code I want to have a variable of type Base which can also hold an object of type Derived. Base b1, b2; b1 = Base(); b2 = Derived(); In languages like Java or C# this is possible. In c ++, however, I get a slicing...
In languages like Java and C#, object variables are reference types. The actual objects are stored somewhere in dynamic memory, and the variables just refer to them, like pointers. But in C++, objects can be created in automatic memory, static memory, dynamic memory, etc. So when you have an object variable, that is ...
68,719,051
68,719,469
How to avoid copy assignment operator c++ for a shared pointer
Consider the line below to create an object foo of class creature: foo = creature(choice); This creates a temporary creature object before assigning it to foo. Which also means that the destructor will be called. If I don't want this to happen, and I don't want to implement a copy assignment operator, I will then crea...
The object creation part should be: std::make_shared<creature>(choice); The make_shared uses perfect forwarding to forward the arguments to the constructor of the template type -- this is the whole reason for make_shared existing. Also you can avoid the possibility of typoes (DRY principle) by using auto: auto creatur...
68,719,081
68,727,449
MSVC ifstream performance issue with unsigned datatype
I made some tests with std::ifstream on MSVC, when reading binary files. I have big performance differences between char and unsigned char data types. Results when reading a 512 MB binary file: Duration read as signed: 322 ms Duration read as unsigned: 10552 ms Below the code I used to test: #include <vector> #include...
The performance issue disappears when you set a read buffer like this : { std::basic_ifstream<unsigned char> fileStream{ filePath, std::fstream::binary }; std::vector<unsigned char> data; data.resize(fileSize); unsigned char buf[8192U]; fileStream.rdbuf()->pubsetbuf(buf, 819...