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 |
|---|---|---|---|---|
63,286,914 | 63,290,099 | LLDB debugging - ignore variables of specific classes to speed up debugging | I'm new to c++ debugging and LLDB. I'm using VSCode with its c++ adapter, LLDB as the debugger, and bazel as the build system. My application deals with manipulating images. The application runs quickly but debugging it is very slow. That's because once I've loaded the images into memory, it takes about 20 seconds ... | The underlying debugger, lldb, doesn't fetch any variables unless explicitly asked. It's always the UI that requests variable values.
In Xcode, if you close the Locals View, Xcode won't ask lldb to fetch variables. That does speed up stepping in frames with big local variables.
Then if you need to keep an eye on one ... |
63,287,043 | 63,287,145 | Problem with loading a bitmap with the LoadImage() function | I develop an application in C++ on Windows CE 2013.
I want to load a bitmap from file and show it on-screen.
The problem is the LoadImage() function always returns NULL.
HDC hdcOkno;
hdcOkno = GetDC(hWnd);
HBITMAP hbmObraz;
hbmObraz = (HBITMAP)LoadImage(NULL, L"C:\\Users\\tykab\\OneDrive\\Pulpit\\bitmapy\\background_bl... | Update:
Since you are working on Windows CE platform, LoadImage() can not load bitmaps from files. You should use SHLoadDIBitmap() instead.
Original Answer:
From the LoadImage documentation:
name
Type: LPCTSTR
...
If the hinst parameter is NULL and the fuLoad parameter omits the LR_LOADFROMFILE value, the lpszName sp... |
63,287,220 | 63,287,619 | Difficulties in building socket communication between c++ and node.js (server) | I try to build a socket communication between c++ and a node.js server.
This is my index.js code:
'use strict';
const express = require('express');
const app = express();
const serverHttp = require('http').Server(app);
const io = require('socket.io')(serverHttp);
const port = 8081;
io.on('connection', ... | Your approach can not work because of the confusion made between socket.io, which is a protocol defined to work with other socket.io clients or servers, and the raw TCP socket created in C++, which will work with other TCP sockets.
What you are creating in the C++ code is a TCP socket, which sadly has nothing to do wit... |
63,287,230 | 63,291,478 | How to find DirectX loctation for d3dx9.h error | I don't nnow the location of my DirectX so is there a wway to find it?
I need it for fixing this : #include <d3dx9.h> error
| The d3dx9.h legacy utility library for Direct3D 9 is only available in the DirectX SDK. June 2010 is the last release of the DirectX SDK and is on Microsoft Downloads--although not for long per this.
Note that with Visual C++ 2012 or later, you must take special care when referencing the legacy DirectX SDK include/lib ... |
63,287,678 | 63,487,474 | Extract cursor size via WinAPI (Windows 10) | I need to extract the cursor image for using it in my swing application (Java).
Firstly, I found similar question, modified code snippet from an answer, and got this sandbox application.
Shortly, it gets cursor image via JNA and WinAPI, then shows this image on JFrame and sets custom cursor for this frame.
In most case... | Thanks @Rita Han - MSFT for giving the initial point to start searching.
You can get a real cursor size in two ways:
The first way is mentioned before: we need to get value from registry value CursorBaseSize under HKEY_CURRENT_USER\Control Panel\Cursors.
The second way was found here: we can get cursor size multiplier... |
63,288,140 | 63,292,458 | Force blocking syscall of other thread to return and set errno to EINTR | please view the following example source code:
void tfunc()
{
// Some blocking syscall that sets errno
if (errno == EINTR)
{
std::cout << "cleanup" << std::endl;
return;
}
// Do some other stuff
}
int main(int argc, char *argv[])
{
std::thread t(tfunc);
sleep(10);
return 0;
... | I suggest you use:
non-blocking operations
poll() (or select() or epoll())
a pipe
Before you spawn your thread you setup a pipe which will carry an "interrupt message". In your thread tfunc you setup poll such that it waits on both the file descriptor (socket) you want to work on and the read end of the pipe.
If you... |
63,288,488 | 63,288,757 | Trying to fix error in a program for removing duplicates in linked list | I am executing a program for removing duplicates from an unsorted linked list using two loops.
The program includes two structs for defining Node and newNode. Also, it includes two user-defined functions removeDuplicates for removing duplicates of linked-list and printList for printing the list.
struct Node {
in... | The issue is here:
while ((ptr1 != NULL) && (ptr1->next != NULL))
{
ptr2 = ptr1;
while (ptr2->next != NULL)
{
// delete if duplicate
ptr1 = ptr1->next;
}
}
You are moving ptr1 inside the loop that removes the duplicates, but it needs to be moved once per node in ... |
63,288,530 | 63,289,097 | How to get the half portion of 3D data in Digital Reconstructed Radiography | I have used ITKRayCastInterpolateImageFunction to generate DRR. I have given axial CT slices and rotated to sagittal and it is displaying fine. But i only need the half portion of the sagittal image(either left or right half).How can i select only a particular half part in the sagittal image?Is there any function in IT... | That sounds like a job for region of interest filter. It is up to you whether you want to generate DRR of the entire 3D image, and then crop it, or crop the 3D image and then generate DRR.
|
63,288,847 | 63,297,135 | How to set a BMP image as the background of a window in Windows API C++? | LATER EDIT:
I realised that what was wrong was not my code, but the image itself. Do not use online tools for converting from jpg to bmp, as they don't provide usable images. What I did instead was open the jpg in Paint and then save it as a 24-bit Bitmap (the only one which kept my original colours).
ORIGINAL POST:
I ... | I used the same code and created the simplest Windows Desktop Application.
And I use my own bmp image to test the background and static window image successfully.
I think the problem lies in your image format, if you just changed the suffix of an other image to .bmp, then your LoadImage will fail but GetLasterror will ... |
63,288,978 | 63,289,031 | How to reuse the code if only the base class is different in C++? | I have two classes, all the codes are the same, except for the base class. How could I refactor them and reuse the code? some_code_1 and some_code_2 are the same in two classes. I'm new to C++, thank you for giving me any suggestions.
<template class C>
class A : Base_1<C>
{
private:
using Base = Base_1<C>;... | Use a template:
template <typename Base>
class Foo : Base
{
public:
// some_code_1
Base::some_method(pa1, pa2, pa3);
// some_code_2
};
using A = Foo<Base_1>;
using B = Foo<Base_2>;
Here, using A = Foo<Base_1>; makes A a shorthand for Foo<Base_1>. Alternatively you can write Foo<Base_1> every time you ne... |
63,289,039 | 63,289,071 | K-means Cluster Centers Are the Same Every Run Although It Is Randomly Initialized | I have an application where I need to implement K-means myself. I was trying my implementation in a small program to see how things are going; however, I find it really confusing that I get the exact same cluster centers every time I run the program. I am surprised because my cluster centers are randomly initialized, a... | You need this line:
std::srand(std::time(nullptr)); // use current time as seed for random generator
at the start of your program to get different sequences from the rand function every time you run the program.
You can use some other seed if you want, but you still need to call srand with some source of randomness at... |
63,289,157 | 63,289,217 | How do I find the size of a char array? | How should I go about finding the length of a char array in C++? I've tried two methods already, but they both have resulted in the wrong number of characters in the array. I've used strlen and the sizeof operator so far, to no avail.
void countOccurences(char *str, string word)
{
char *p;
string t = "true";
... | sizeof(str) is wrong. It gives you the size of a pointer (str is a pointer), which is a fixed number, normally either 4 or 8 depending at your platform.
std::strlen(str) is correct, but strtok inserts a bunch of \0 into your array before you try to obtain the size. strlen will stop at the first \0, and give you the num... |
63,289,493 | 63,290,134 | How do I change the appearance of the address bar and tab in Chromium to be similar to the attached image | The top image is compiled Chromium and the bottom one is a design I made in Photoshop
I downloaded the gclient files and can now see all the components that make the Chrome build. The files are a lot though and I didn't find the file responsible for this. Any help?
| https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/ui/views/location_bar/location_bar_view.cc;l=1
most of the ui stuff you would want to customize is in chrome/browser/ui/views
and most of the ui graphics are in
ui/resources/default_100_percent/
200_percent is for the retina displays, basically 2... |
63,289,797 | 63,289,885 | Convert std::thread pointed by void pointer to object std::thread instead of pointer to object | I was looking to an exercise I did, specifically a class "threads manager" which manage threads (omg really? lol) by storing them inside an array of "typedef void *HANDLE;" declared inside a struct GROUP.
So I already made it working, but I saw that I was converting the "HANDLE", so "void*", by "reinterpret_cast" conve... | What you really need is
std::thread& ref_thr = *reinterpret_cast<std::thread*>(test);
// ^ declare a reference to a std::thread
and then you can use ref_thr just like you would use a normal object.
As you've found, the copy constructor for std::thread is deleted, so if you actually want to create a thread obje... |
63,290,129 | 63,291,657 | c++ function not catching vector subscript out of range execption | I am trying to split a string on the char ":" then see if index 2 exists. My split string function works good as ive been using it for quite some time, but after trying to try{} catch() this it doesnt catch the execption and instead displays a debug error on my screen.
std::vector<std::string> index = split_string(... | std::vector::operator[] does not perform any bounds checking, so it will not throw any exception if an invalid index is passed in. Accessing an index out of bounds with operator[] is undefined behavior (the OS may raise its own exception if the invalid index causes invalid memory to be accessed, but you can't use catc... |
63,290,538 | 63,311,071 | How to use conan to handle ImGui-SFML dependency in a cmake gcc project in Linux? | I want to handle the dependencies of a C++/cmake/gcc project in Linux using conan, and build an ImGui C++ demo as shown here: using imgui by Elias Daler
I have used conan to handle Boost dependencies successfully, but with ImGui-SFML I am having a linking error.
My conanfile.txt has the following instructions:
[require... | According to this reported issue, this solution for a similar question, and conan's basic setup documentation, in this case the CMakeLists.txt should include: adding the argument TARGET in the setup, and the call to conan_target_link_libraries instead of the usual target_link_libraries, as follows:
include(${CMAKE_BINA... |
63,290,694 | 63,292,727 | Trouble running a simple "Hello world" using Visual Studio code | I've recently started to learn C++ however I can't even get a simple program to even run. I am using Visual Studio Code and I used this tutorial https://code.visualstudio.com/docs/cpp/config-mingw to set up C++. I followed every step and have not gotten any errors even until this point. Whenever I try to run helloworld... | My suggestion is that you open the terminal and go to your folder using cd and the folder name, and compile the file with:
g++ filename.cpp
and run it with:
./a.out
For Unix systems for windows I think it is:
./a.exe
|
63,290,918 | 63,291,000 | Why am I getting no matching function for call to | I am getting these errors:
no matching function for call to 'Date::Date()'
Appointment(){
and
no matching function for call to 'Time::Time()'
Appointment(){
Appointment.h
// Appointment.h -- Class Appointment UPDATE as needed
//
using namespace std;#include "Time.h"
#include "Date.h"
#ifndef APPOINTMENT_H
#defi... | You assumed wrong, constructors are not inherited in C++. Here's what you need to do
Appointment::Appointment(int month, int day, int year, int hour, int minute, int howLong) :
Date(month, day, year), Time(hour, minute), howlong(howlong)
{
}
If the : syntax is unfamiliar to you (it seems to be unfamilar to every... |
63,291,008 | 63,291,391 | ostream: how are functions being called for this chained output? | Can anyone explain how the following iostream cout code is evaluated with each specific function including its declaration? Also, how the hex manipulator modifies the stream flags (my guess is it calls ios.flags()). For instance, I'm looking at ostream member functions and non member functions and am confused on what... | std::hex and std::endl are standalone functions that take a std::ios_base& and std::basic_ostream& as input, respectively:
std::ios_base& hex( std::ios_base& str );
template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );
These functions manipulate the... |
63,291,034 | 63,302,023 | Trying to extract a piece of html code using regex | I have some html code like
<tr class="class1">
<td class="class2">
<a href="some_address"></a>
<div id="id1">
<span class="class3"></span>
</div>
<span>Just a text</span>
</td>
</tr>
I need to extract the piece of code between <tr class="class1"> and </tr> tags. I us... | You need to escape the \ and take the final \n into account, or better yet, use regex_iterator instead of regex_match.
The following works for me in GCC 8, Clang 8 and MSVC 14:
#include <string>
#include <regex>
#include <iostream>
int main()
{
std::string str = "<tr class=\"class1\">\n"
"<td class=\"class... |
63,291,289 | 63,291,513 | What is this "/string" file CMake is failing on? | Using Visual Studio Code, I am getting the following odd error when running CMake:
[main] Building folder: CMake-test
[main] Configuring folder: CMake-test
[proc] Executing command: "C:\Program Files\CMake\bin\cmake.EXE" --no-warn-unused-cli -Dcmake.sourceDirectory:STRING=CMake -Dcmake.generator:STRING=Ninja -DCMAKE_... | The following section in your cmake command looks suspect:
-C c:\Devo\CMake-test\string
This loads a script file to pre-populate the CMake cache, but may have been erroneously set. To remove it, you can do the following:
Open Settings and search for "cmake cache" in the search bar.
Under CMake: Cache Init, click on ... |
63,291,544 | 63,291,699 | Attempting to create a threadguard with move semantics | the title is pretty self explanatory. I'm trying to get a minimal working example of a thread guard that can also support the move semantics that std::threads have.
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
class ThreadGuard {
public:
explicit ThreadGuard(std::thread input): t(s... | You need to convert the int to std::string:
tp[i] = ThreadGuard(std::thread(doWork, std::to_string(i)));
You also do not need to write your own move constructor and move assignment operator. Use the default:
class ThreadGuard {
public:
explicit ThreadGuard(std::thread&& input): t(std::move(input))
{}
Threa... |
63,291,546 | 63,291,804 | Why does the base class pointer point to the pure virtual method in the base class instead of the overidden method in the derived class? | #include <iostream>
class A
{
public:
virtual ~A() = default;
virtual void foo(void) = 0;
};
class B : public A
{
private:
int x;
public:
B(int a) : x(a) {}
void foo(void) { std::cout << "B: " << x << "\n"; }
};
class Foo
{
private:
A* a_ptr;
publ... | Yes, your suspicion is correct.
When the B object is passed by value into the Foo constructor, it becomes a local variable of the constructor. The constructor is saving a pointer to that local object, which goes out of scope when the constructor exits.
So, the call to a_ptr->foo() in Foo::dummy() is actually undefined ... |
63,291,805 | 63,321,469 | Unable to cross-compile Qt 5.14.2 for Raspberry PI zero w because it “requires a C++11 compiler” | This problem has already been encountered for previous versions of Qt5 : Stack-overflow post (non-answered yet). I'm having the same problem with a more recent version and I have followed several tutorials online :
https://www.raspberrypi.org/forums/viewtopic.php?t=204529
https://wiki.qt.io/RaspberryPi2EGLFS
Even if ... | The compiler you're using is just too old. The verison you're getting from the link you shared is 4.8.3, whereas you'll need at least gcc 5. (Check here: https://codereview.qt-project.org/c/qt/qtdoc/+/288825)
The Error you get might be a bit misleading, since gcc itself states that it fully supports C++11 from 4.8.1 as... |
63,291,847 | 63,291,996 | How to use resetiosflags to reset ostream flags? | I tried using this, but encountered a compilation error. Unfortunately, I'm new to the compiler and don't understand the message. I'm trying to get the default &ostream flags back. Does anyone know how to properly reset the flags and what the error is reporting?
#include <iostream>
#include <iomanip>
using namespace... | The key part is this:
candidate function not viable: no known conversion from
'std::ios_base &(std::ios_base &)' to 'ios_base::fmtflags'
that's telling you that resetiosflags takes a fmtflags instance but you tried to pass it a function that returns an ios_base. It's a bit confusing but std::hex is a stream mani... |
63,291,849 | 63,292,330 | Vulkan/VMA Change buffer size similar to `realloc` | Say I run into a situation where I would like to change a vulkan buffer's (VkBuffer) size. For example, if I wanted to add more vertices to an existing vertex buffer. How would I grow/shrink a VkBuffer? Would I be forced to just create a new buffer and abandon the old one, or is there functionality similar to C's reall... | There is no realloc in VMA nor Vulkan extensions.
Historically, there was vmaResizeAllocation(), but it was deprecated and is now defunct.
For grow you need to anticipate and preallocate some extra size, or get a new allocation. For shrink you can use the memory you already have, or get a new one.
If you get a new allo... |
63,292,077 | 63,292,106 | Default constructor error no matching function for call to | In main(), I am making an array myAppointments, and realize to make it work I would need to create a default constructor in Appointments.h, but when I do I get this error:
no matching function for call to 'Time::Time()'
Appointment(){
Here is Main:
/*
* Homework 4 -- UPDATE as needed
*/
#include <iostream>
#i... | This line:
Appointment myAppointments[19];
will call the default constructor of Appointment for each element.
Your default constructor doesn't explicitly call a constructor of Time, so the default constructor of Time will be called, which doesn't exist. Same with Date.
You can reinstate the default constructor like t... |
63,292,081 | 63,292,210 | Variadic functions arguments bad order in some cases | I was trying to reduce my code and I found something weird with variadic functions (it's most certainly due to my lack of knowledge though)
So I have that piece of code that works :
void Text::textTypePtr(Root* text, ...)
{
va_list args;
va_start(args, text);
Interact::ModifiedKey modKey = va_arg(args, Interact::... | The first version is correct. Statements are executed in order, so you can be confident the first variadic argument will be assigned to modKey and the second will be assigned to key.
The second version is depending on unspecified behavior. The relative order of evaluation of arguments to a function is unspecified. So i... |
63,292,698 | 63,294,997 | How to use more than one openGL state in an application? | I am aware openGL is a state machine, what I'm not aware of is how the state is stored.
I have a project where I have to render things off-screen to memory in a c++ dll/dynamic-library and pass the final image to a c# application that also uses openGL state to do any imaginable thing with(render whatever the applicatio... | If you want to pass the final render image to another application , you can pass it using PBO and the pointer to the pixel data using glMapBuffer.
This is the code where i am passing the pixel data to other application.
glReadBuffer(GL_COLOR_ATTACHMENT0);
writeIndex = (writeIndex + 1) % 2;
readIndex = (readIndex + 1) %... |
63,293,072 | 63,293,285 | C++ primer 5 ed. shared_ptr and associative containers | In C++ primer 5 ed. by Stanley lipmann chapter 15 OOP it is said:
std::multiset<std::shared_ptr<Quote>, decltype(compare)*> items{compare};
The elements in our multiset are shared_ptrs and there is no less-than operator for shared_ptr. As a result, we must provide our own comparison operation to order the elements (§... |
Why my code works although class A doesn't define less than operator?
Because it is irrelevant what operators A have when the set doesn't contain elements of type A.
The set contains shared pointers.
The thing is that after checking cppreference about class std::shared_ptr I've found out that it has overloaded relat... |
63,293,129 | 63,293,713 | Pointers and references in linked lists | struct node {
int data;
node* next;
};
int main()
{
int* p = nullptr;
std::cout << p << std::endl;
node* nu = new node;
std::cout << *&nu << std::endl;
}
The question: is nu a memory address, are pointers really just memory address or is there something that I am missing here. What significan... |
is nu a memory address, are pointers really just memory address or is there something that I am missing here.
nu is a pointer to a node and it means that nu "points to" a memory location (in this case on the heap) where the node has been constructed. The memory location is the address and so yes nu is essentially a m... |
63,293,660 | 63,293,689 | Why does my program compile successfully if I don't include <string.h>? | I've been puzzled by this for a while. To test this out, I made a simple program that just creates a std::string variable and prints it out to the screen. However, it doesn't include <string.h>.
#include <iostream>
using namespace std;
int main()
{
string name = "Test";
cout << name << endl;
r... | The reason you do not need to include the #include <string.h> header file is because when you include the #include <iostream> header file it includes std::string.
However, do not rely on it. What may work on your compiler may not work on another. Always include the proper header files.
To edit your example this is how ... |
63,293,661 | 63,295,765 | Regex works only on first occurance? | Update: Kindly read my comment on jignatius's answer
I wrote the following code to find specific matches in a string using regex and to delete them and replace with another value, but it doesn't work as expected.
For example given the following input:
f={a,b}+{c,d}
I would expect it to delete both {a,b} and {c,d} but... | There is a standard library function, std::regex_replace, in the header <regex> that does what to want to do: text replacement based on a regex. That will simplify things quite a lot for you instead of using a hand crafted loop.
You just need to supply the input string, the regex to match against, and the replacement s... |
63,293,700 | 63,293,836 | Why is if statement returning false when it should be true? | For example When I input a 8 3 2020 that should make the if statement true as 8 3 2020 are values that can be found in the array but instead it returns false
Here is main
/*
* Homework 4 -- UPDATE as needed
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "Appointment.h"
usi... | The bug here is not in incorrect condition within if (which should work perfectly), it's due to incorrect behavior of program.
You're going out of bounds here:
for (int i = 1; i < 20; i++) {
HW4DataFileHandle>>month;
HW4DataFileHandle>>day;
HW4DataFileHandle>>year;
HW4Da... |
63,293,792 | 63,294,575 | How to include multiple language development header in C++ | I want to include the Python.h and the ruby.h header in the same C/C++ file, as I want to work with both at the same time. Which would be the best way to include both and prevent the compiler/preprocessor to warn about multiple redefinitions of the same variables or there is another way to use those languages from C?
M... | An example to demonstrate not getting complaint for redefinitions in headers.
Though you may have to re-declare every functions you need in a wrapper header.
P.h
#define AAA 2
R.h
#define AAA 1
Pwrapper.h
int get(void);
Pwrapper.cc
#inclide "P.h" //include here, so Pwrapper.h won't conflict definition with R.h
int g... |
63,293,871 | 63,293,955 | compile error even though file was included | When I compile my C++11 on Unix I get the following error: (Even though it works fine on clion of my mac)
-bash-4.2$ g++ -std=c++11 -Wall -Werror -pedantic-errors -DNDEBUG main.cpp utilities.cpp utilities.h Graph.cpp Graph.h Exception.cpp Exception.h Edge.cpp Edge.h Calculator.cpp Calculator.h -o final
/tmp/ccLJAsey.o:... | Remember that C++' #include <regex> (or anything else, for that matter) just includes the (text, source code) file /usr/include/.../regex /(the ... will depend on your exact installation) into the file being cpompiled. If you take a peek a those files, they usually contain declarations of classes, functions, templates,... |
63,294,249 | 63,294,250 | (C++) Executing an instruction inside a game loop once (SFML) | The answer to this question came to me halfway through writing it and honestly I feel like I should finish what I started and document it since I've been stuck with this bug the whole day and it might come in handy later.
I'm using SFML and I have a number of buttons, and I want to play a blip sound-effect when the mou... | As it turns out, the reason collision resets to false every frame, is because I forgot that this whole set of instructions is contained within a for loop that tests every button, so the collision test happens for every button every single frame, and and every time the returned value is stored inside collision, meaning ... |
63,294,265 | 63,301,677 | MakeFile for C++ project | I wrote my own makefile -Which will be used to compile my C++ project-
But I had some issues with it:
I need to delete all temporary files; objects, executables and those for UNIX
I did the first two like this; but how may I implement the latter?
clean:
rm -f $(OBJS) $(EXEC)
I need to zip all files in a test.zip fo... | You want to delete all "temporary files", but a temporary file is a file that people don't intend to keep very long. There is no way for a tool like Make to know people's intentions without being told.
To create a zipped archive of Makefile and test.zip/ from the command line, you can use a command like:
tar -czvf arch... |
63,294,883 | 63,443,444 | OpenGL EGL returns 0x300c (EGL_BAD_PARAMETER) at eglGetDisplay in docker | I am trying to run a simple example to set up EGL context in a docker container. However, I keep getting this error message :
Detected 0 devices
terminate called after throwing an instance of 'std::runtime_error'
what(): EGL error 0x300c at eglGetDisplay
Aborted
Basically, eglQueryDevicesEXT returns 0, and eglGetPl... | OMG I finally solved this problem. Turned out I was linking to the wrong library on the server.
I found the answer in this post: https://forums.developer.nvidia.com/t/problem-with-opengl-visualization-without-an-x-server/73204/15
The key is to link to the libraries in /usr/lib/nvidia-410/, not the system default /usr/l... |
63,295,116 | 63,295,178 | How to give a file path instead of file name c++? | This code part is from a simple md5 hash generator.But here i can only give a file name to generate the md5.
LPCWSTR NameOfTheFile = L"Test.txt"; //Name of the file that user is scanning
But i want to give a file path here instead of the file name..Is there any way to do that.?
#include <iostream>
#include <windows.h... | You can use file paths with CreateFile. Try something like NameOfTheFile = L"C:\\Text.txt";
|
63,295,753 | 63,295,816 | Use structure binding when iterator a vector of std::pair<string, some_struct >* | the below code shows how a structure binding normally works.
It provides a more descriptive name comparing to "first", "second".
map<string, string> sites;
sites.insert({ "GeeksforGeeks", "Coding Resources" });
for (auto& [key, value] : sites)
{
cout << key.c_str() << " " << value.c_str() << endl;
}
Now I have a s... | You can do the following to the std::vector<pair<std::string, People>* > vec;
for (std::pair<std::string, People>* pairPtr : vec) // iterate via pair-ptrs
{
if (pairPtr) // if the pointer is valid!
{
const auto& [key, people] = *pairPtr;
// do something with the key and vale!
}
}
If the pair-point... |
63,295,986 | 63,307,870 | How to list in which function each thread is at with lldb? | I'm trying to debug a multithreaded function, and there are lots of threads that execute functions that take some time. The program works for a while and then hangs. I'd like to know what each thread is doing when this happens, to know which part of the code is hanging.
Is it possible with lldb?
| You can run thread backtrace all to list the stack for all threads. This command takes a -c/--count flag, which you can use to limit the output to the top frames. For example to see only the current function of each thread, run thread backtrace -c 1 all.
|
63,296,256 | 63,296,902 | Unresolved external symbol errors in Chilkat library dispite including crypt32.dll and ws2_32.dll in Qt 5.15.0 MSVC2015 64x | I try to use Chilkat in Qt for MD5 encryption, but I get lots of unresolved external symbol errors.
my .pro file:
LIBS += -L"C:\SDL\SDL2-2.0.4\lib\x64" -lSDL2 \
-ldxguid \
-L"C:\Windows\System32" -lcrypt32 -lws2_32 \
-L"C:\chilkat-9.5.0-x86_64-vc2015\libs" -lChilkatRelDll_x64
INCLUDEPATH += C:\SDL\SDL2-2.0.4\include \... | I edited the .pro file like this and it works for now.
win32:LIBS += -L"C:\Windows\System32" -lcrypt32 \
-lws2_32
LIBS += -L"C:\SDL\SDL2-2.0.4\lib\x64" -lSDL2 \
-ldxguid \
-L"C:\chilkat-9.5.0-x86_64-vc2015\libs" -lChilkatRelDll_x64 \
-lChilkatDbgDll_x64
INCLUDEPATH += C:\SDL\SDL2-2.0.4\include \
C:\chilkat-9.5.0-x86_... |
63,296,314 | 63,296,765 | What happens behind the scenes when manually calling a constructor in C++? | This is an educational question, I am interested in what happens behind the scenes when I do:
SomeClass x(arg1, arg2, arg3); // An instance of SomeClass is constructed.
x = SomeClass(arg4, arg5, arg6); // Intent is to create a new instance.
SomeClass does not have operator= implemented.
Does the space allocated to ... | This can best be explained with the help of a small example:
Live on Coliru
struct A {
A(int a) { cout << "A::ctor\n"; } //ctor
A(const A& a) { cout << "A::copy\n"; } //copy ctor
A& operator=(const A& a) { cout << "A::operator=\n"; } //copy assign
};
int main()
{
A a(2); ... |
63,296,500 | 63,873,060 | BIO don't flush data in OpenSSL | I am using BIO to compute the digest of some file with OpenSSL. My code is as following:
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
int main(){
BIO* bio_infile;
bio_infile = BIO_new_file("test.txt", "rb");
BIO* bio_md = BIO_new(BIO_f_md());
BIO_set_md... | The BIO chaining mechanism is meant for prepending filter BIOs to a source/sink BIO. It is not designed for connecting a source BIO with a sink BIO.
So what you can do:
Create a BIO chain of filters with a final BIO sink. When writing data to the head of the chain, the input will traverse each filter until it reaches ... |
63,296,581 | 63,297,445 | Interger not updating value in switch function in C++ | Kinda of a complete beginner here.
I am starting in C++, and programming in general, so, I'm trying to do a rough menu for a text RPG combat game, for practicing conditionals.
But, the values aren't updating themselves. Here is the code:
int main() {
cout << "Wild Ogre attacked!" << endl << endl;
int ogreHP = ... | When you write this syntax:
Stamina = - 10;
ogreHP = - 20;
You actually assigns -10 and -20 to Stamina and ogreHP respectively, they're not called 'reducing' here. Rather than that, if you could've written the following:
Stamina -= 10; // Stamina = Stamina - 10; -> previous - 10 = now
ogreHP -= 20; // ogreHP = ogreHP... |
63,296,606 | 63,296,780 | 2-D Array -- "Too many initializer values" warning/error | I'm new to programming. I tried looking at a bunch of similar questions to mine on here, but either they were too advanced for me to understand or didn't quite apply to/help me with my situation.
I just learned about 2-D arrays, so I am doing an assignment about them. (The assignment is about movie ratings, which will ... | the problem with your code is that you can only do the assignment bellow in the variable declaration, i.e, you can only do multiple assignment of the array, when you declare the array.
array[NUM_REVIEWERS][NUM_MOVIES] =
{ {3, 1, 5, 2, 1, 5 },
{4, 2, 1, 4, 2, 4 },//the beginning of this row is where I get ... |
63,296,692 | 63,296,848 | How to handle char * from packed struct in cgo? | Since Go doesn’t support packed struct I found this great article explains everything with examples how to work with packed struct in go. https://medium.com/@liamkelly17/working-with-packed-c-structs-in-cgo-224a0a3b708b
The problem is when I try char * in place of [10]char it's not working. I'm not sure how this conver... | You are writing ten (zero) bytes of GoPack.e into the packed.e which is of type char *. This won't work, because pointers will be 4 or 8 bytes depending on your system, so even if the bytes represented a valid pointer, you are overflowing the amount of memory allocated.
If you want to create a valid structure with a va... |
63,296,707 | 63,296,779 | Why will my elseif statment never executed | Any idea why the else if statment will be never executed ? The value of difference is constantly changing when the program runs.
double difference = abs(reale_x[0] - reale_x[1]);
if (0 <= difference < 45) {
timer_counter += 1;
if (timer_counter == 30) {
cout << "C... | That is not how comparation works in c++.
What this code
if (0 <= difference < 45) {
does is it first compares if 0 is smaller or equal to difference. It is then "replaced" by a bool value either true or false. And then a bool value (so either 1 or 0) is compared to 45. And it will always be smaller than 45. What you ... |
63,296,924 | 63,297,225 | Error for default parameter value of non-member template friend function | Why does the following code compile with GCC but not with Clang? Who is right and why?
class TF
{
private:
struct S
{
};
template <typename T> friend void F(T x, S s, int v = 5);
};
template <typename T>
void F(T x, TF::S s, int v)
{
}
I get following e... |
How do I resolve this?
As the error message says, you must define the function template to be able to have default arguments:
template <typename T>
friend void F(T x, S s, int v = 5) {
// ...
}
If you don't want that, you could remove the default argument and add an overload that acts as a proxy:... |
63,297,755 | 63,297,858 | Using a class variable as a default argument to the class member function | I am building a LinkedList in C++.
Signature for addNode function:
const bool LinkedList::addNode(int val, unsigned int pos = getSize());
getSize() is a public non-static member function:
int getSize() const { return size; }
size is a non-static private member variable.
However, the error that I am getting is a non... | The default argument is provided from the caller side context, which just doesn't know which object should be bound to be called on. You can add another wrapper function as
// when specifying pos
const bool LinkedList::addNode(int val, unsigned int pos) {
pos = pos == -1 ? getSize() : pos;
//whatever
}
// when... |
63,298,187 | 63,298,856 | How to find last occurrence of some character in the whole vector<string> then split the string to three separate elements | If I have vector of string vector<string> vec and want to find last occurrence of some character ',' in the complete vector then split the string to three separate elements in the vector in the same place.
vector<string> vec1 = { "string1","str,in,g2" , ",string3 " , "my,target" ," string4" };
vector<string> vec2 = { "... | Just use reverse iterators:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main() {
std::vector<std::string> vec = { "string1","str,in,g2" , ",string3 " , "my,target" ," string4" };
for (auto it = vec.rbegin(); it != vec.rend(); it++) {
std::string ... |
63,298,482 | 63,299,375 | How to replace lines in a text file? C++ | When using the replace line method I encounter the std::out_of_range exception I am not sure how to fix this. I know that the exception occurs when pos > length() but I am not sure how to modify my text file without this from happening. I am trying to replace delLine with replaceLine in the text file. Any help is appre... | getline read one line (if possible) but your management of start and end is like if line receive the full content of the file, because of start and end management you try to access out of the string.
Out of that do you really want to replace "something color = vec4somethingelse" by "something color = vec4("+red+", ... |
63,298,797 | 63,313,813 | Implementation of numpy.polyfit and numpy.polyval in C++ with Armadillo | I'm trying to reproduce the results of numpy.polyfit and the following application of numpy.polyval in C++ by using Armadillo.
This is my attempt:
using namespace arma;
vec fastLm(const vec& y,
const mat& X,
int order)
{
mat extended_X(X);
// Column bind the higher order regressors to the ... | For me it all looks good, have tried your function with
int main()
{
mat x=linspace(0,1,5);
vec y=1/(1+x);
y.print("Y");
mat Yhat = fastLm(y,x,3);
Yhat.print("Yhat");
}
giving the results
Y
1.0000
0.8000
0.6667
0.5714
0.5000
Yhat
0.9998
0.8008
0.6654
0.5722
0.4998
And the corre... |
63,298,877 | 63,298,994 | win 10 Qt C++ program calls Python program how to package and distribute | In win10 Qt environment, C++ program calls Python program how to package and distribute, can run this program on another machine without Python environment
| You can use pyinstaller to make a .exe file out of your .py. And a .exe file can run on every windows Pc.
|
63,299,013 | 63,299,298 | What's the best way to notify about malformed template instantiations? | How can I make forbidden template instantiations clearly visible at compile time? I was thinking about throwing an exception by inheriting it:
template<string message> struct exception {};
template<class T> struct non_void;
template<class T> using non_void_t = typename non_void<T>::type;
template<> struct non_void<... | I would suggest making the failing specialization non_void_t<void> a constrained partial specialization that triggers a static_assert on instantiation:
#include <type_traits>
template<class T> concept Void = std::is_void_v<T>;
template<Void T> struct non_void<T> { static_assert(!std::is_void_v<T>, "argument is void"); ... |
63,299,482 | 63,299,511 | Why the variable in lambda is not able to call the function | This is the class.
#include <iostream>
#include <string>
std::string strName = "ABC";
class BlueOut
{
public:
void printName() { std::cout << strName << std::endl; }
};
Now i create a object of this class
BlueOut blueout;
And i call the function printName() of the object in lambda
auto a = [&]() { blueout.pri... | In this line,
auto a = [&]() { blueout.printName(); };
the part [&]() { blueout.printName(); } is called a lambda expression. You bind it to some variable a. Now you have a function object a created by a lambda expression. In order to see the effect, this has to be invoked:
a();
|
63,299,544 | 63,299,809 | c++ multiple if statements. Why else statement also executes? | When I execute the if statement right before the else statement, the code will execute properly. But when I execute the if statement that is away from the else statement, the c++ will execute the chosen 'if statement' but the 'else statement' will also execute. What is happening there?
I know how to fix my code, withou... |
the c++ will execute the chosen 'if statement' but the 'else statement' will also execute. What is happening there?
These two if statements are separate and the else is part of the second if statement:
/* One if statement block ************************/
* if(h<=160){
* cout << "You are too small!";
... |
63,299,625 | 63,299,800 | Can you remove elements from a std::forward_list while iterating through it? | I'm trying to iterate through a forward_list manually, and erase certain elements.
My question is essentially the same as this one, but with a forward_list caveat.
The following code (for example only), despite not revisiting before after calling "erase after", does not work (it produces endless garbage).
#include <ios... | The problem is, after erase_after the iterator to the erased element, i.e. it becomes invalid; performing ++it later leads to UB.
erase_after returns the iterator to the element following the erased one, you can assign it to it. (And move ++it into the for statement to control it manually.)
typedef std::forward_list<in... |
63,299,651 | 63,304,338 | std::ws behavior on EOF | I stumbled across a difference in behavior between different compilers. Suppose the following code:
#include <sstream>
#include <iostream>
using namespace std;
int main() {
istringstream ss("100");
int val;
ss >> val;
cout << "fail: " << ss.fail() << " eof: " << ss.eof() << endl;
ss >> std::ws;
... | failbit should be set. It's done by sentry object, what ws constructs first thing.
[istream::sentry]/2
explicit sentry(basic_istream<charT, traits>& is, bool noskipws = false);
Effects: If is.good() is false, calls is.setstate(failbit). Otherwise, ...
|
63,299,964 | 63,302,699 | Why am I allowed to initialize object of class Test by assigning integer constant in C++? | Here is my C++ code
#include<iostream>
class Test{
int i;
public:
Test() { }
Test(int i){
std::cout << "Constructor called" << std::endl;
this->i = i;
}
void print(){
std::cout << i << std::endl;
}
};
int main(){
... | This syntax:
Test t = 3;
is a form of copy-initialization. The effect of this is that the best user-defined-conversion-sequence is selected to initialize t. In this particular case, you have provided a conversion constructor Test(int) which is the best match and gets called.
|
63,300,005 | 67,918,795 | G++ Compiler warning when using c++ 17 updates | I'm running g++ compiler on windows 10 with mingw.
On checking compiler version in cmd I get the following:
g++ --version- g++ (MinGW.org GCC Build-2) 9.2.0
same with c++ --version
When I compiled a cpp program making use of structured bindings I got a warning:
warning: structured bindings only available with '-std=c++... | As the warning itself says:
structured bindings only available with '-std=c++17' or '-std=gnu++17'.
Meaning, you are using cpp version 14 or lower as compiler. However, you also have cpp 17 or higher installed on your system to get such kind of warning.
Your program will still run but with the warning.
For Windows:
If ... |
63,300,205 | 63,303,381 | How to define macro which correctly sets the __declspec | Using Visual Studio 2017, I am trying to build my latest project which imports libraries, which in turn import methods and functions from .dll files.
When building my project, I get a list of errors like this:
error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl UserTracking(void *)" (__imp_?Us... | Turns out that although I added the paths to my libraries in the linker additional library directories, I had neglected to add the .lib files in the linker additional dependencies.
|
63,300,453 | 63,300,604 | how to call function throw an array of pointers in C | The task is to draw triangles with star pattern.
each triangle has a separate function
function must call through an array of pointers.
I made triangle patterns function. I cant call the function from array of pointers. When I am trying to execute, couldn't be able to print a triangle.
Code:
#include <iostream>
#inc... | This kind of code is so much easier with a typedef
typedef void (*func_ptr)(int*); // func_ptr is a function pointer
func_ptr fun[] = { triangle1, triangle2, triangle3 };
fun[choice](array);
|
63,300,749 | 63,301,788 | Is there any better way to implement the try..catch mechanism? | LinkedList.h
#pragma once
class LinkedList {
int size = 1;
struct Node {
int ivar = 0;
Node* next = nullptr;
};
Node* rootNode = new Node();
Node* createNode(int ivar);
auto getSize() const { return size; }
public:
LinkedList() = delete;
LinkedList(int val) {
roo... | What C++ exceptions are not
Exceptions are not an alternative way to implement if / else. Exceptions have totally different and much more complicated semantics and they are made solely for error handling. In fact, it is such a topic that until 1994 no one really knew how to write proper exception safe code.
What you sh... |
63,300,835 | 63,301,213 | Remove the required elements of string2 from string1 | Consider 2 strings string1 and string2.
The main objective of my code is to remove only elements of string 2 from string 1.
Here's my code
string sring1,string2;
cin>>string1>>string2;
for(int i = 0; i<string2.length(); i++){
string1.erase(std::remove(string1.begin(), string1.end(),string2.at(... | You can do:
#include <iostream>
#include <string>
int main() {
std::string s1 = "abbccdef";
std::string s2 = "abc";
for (std::string::size_type i = 0; i < s2.length(); ++i) {
for (std::string::size_type j = 0; j < s1.length(); ++j) {
if (s1[j] == s2[i]) {
s1.erase(j, 1)... |
63,300,966 | 63,306,693 | clang BlocksRuntime embeds 'obsolete compiler' warning in executable when using __block | #include <stdio.h>
#include <Block.h>
int main()
{
__block int x = 5;
^{printf("x is %i\n", x);}();
}
When I use clang to compile a c (or c++) program that uses both clang's blocks and the __block type specifier, no compiler warnings are produced, even using -Wall and -Wpedantic. The program also runs as expected.... | I've just realized that the warning is probably meant to be a runtime error stored as a string in the executable, which means that there is no problem. Disassembling seems to support this idea - radare2 shows the string in the .rodata section:
I really should have though of that earlier...
|
63,301,021 | 63,301,152 | Why do I get this error? "[variable] does not name a type" in C++ for std::string array even though it has been included and is in the same scope | I wanted to make a ASCII-Art that printed text with ASCII chars
and then I massively failed. because I've been trying to solve this error for an hour now and I couldn't find a solution.
code:
#include <iostream>
#include <string>
class prnter {
public:
void print(std::string text) {
if (text == "A") {
... | You can't have "normal" statements outside of functions. Only declarations and definitions.
In your case you can solve the problem by initializing the array when you define it:
std::string const lett[26][5] = {
// A
{
" _____",
"/ \\",
"| /_\\ |",
"| | | |",
"|_/ \\_|"
},
... |
63,301,504 | 63,302,236 | clang: error: unknown argument: '-fno-leading-underscore' | I am trying to compile my .cpp with -fno-leading-underscore option but it raises an error saying:
clang: error: unknown argument: '-fno-leading-underscore'
g++ -m32 -fno-use-cxa-atexit -nostdlib -fno-builtin -fno-rtti -fno-exceptions -fno-leading-underscore -o kernel.o -c kernel.cpp
How can I fix this I am new to Mac ... | In your terminal, type g++ and press enter. You will probably get:
$ clang: No input files
As you can see its still clang underneath.
To fix this, first cd into /usr/local/bin and type ls. You will see the binaries inside:
g++-9
...
Next, create a symlink to it so that you can invoke g++ directly
ln -s g++-9 g++
If ... |
63,302,191 | 63,302,206 | Why does the program terminate on startup without outputting anything? | I made a C++ user input that detects when no value is being input, but it terminates the program on startup without outputting anything. Why?
#include <iostream>
int main() {
bool entered = false;
while(entered = false) {
std::cout << "Please enter thy name: ";
std::string name;
std::getline(std::cin, ... | This loop condition:
while(entered = false)
is wrong. Instead of comparing false and entered, you are assigning false to entered.
Instead, you need to do:
while(entered == false)
If you turn on warnings, for example with -Wall, the compiler will tell you that you are likely making a mistake here.
|
63,302,231 | 63,393,979 | Debug vs Run in Qt Creator. Different numerical values | I work on C++ Qt project in QtCreator. There is some manipulation with data (for ex. std::double type). When I start debug without any breakpoint then my application shows correct data (-8.7357). But when I run already compiled program I've got (-8). What could be reason for this situation?
Below is a piece of my json ... | Here is I duplicate the answer from the comments.
My json-file uses ' . ' decimal separator. Qt uses the information from QSystemLocale i.e the locale information from the Operating System. Probably GDB debugger uses his own setting. That's why I've got correct data while debugging. I changed line in file /usr/share/i1... |
63,302,413 | 63,302,612 | Libcurl HTTP POST request | I'm currently trying to code an HTTP post request to be able to register on a website from my program.
When I run it I get no errors and even the CURLOPT_VERBOSE says that everything went successful.
I hope you guys can give me an advise or help, thanks in advance!
Verbose output:
* Trying 151.139.128.8:443...
* ... | Please notice this line in the response:
< HTTP/1.1 415 Unsupported Media Type
You probably want to use curl_easy_getinfo with CURLINFO_RESPONSE_CODE to retrieve and check the HTTP status code from the response.
Depending on the API, response 415 could have a different meaning. In this case it's likely that the server... |
63,302,825 | 63,302,910 | Returning an rvalue reference that is passed to a function as an argument | I want to understand whether I can safely return an rvalue reference that is passed as an argument to a function and it doesn't get destroyed with the stack unwinding.
struct Struct { int m; };
Struct& f(Struct&& rvalue)
{
std::cout << &rvalue << '\n';
return rvalue;
}
void main()
{
Struct& lvalue1 = f(S... |
I can safely do this kind of things?
No. Struct{ 1 } and Struct{ 2 } construct temporary objects which get destroyed after the full expression. That means the reference lvalue1 and lvalue2 are always dangled. Dereference on them leads to undefined behavior.
All temporary objects are destroyed as the last step in eva... |
63,303,049 | 63,303,216 | How are smart pointers of a derived class implicitly convertible to the base class? | From cppreference,
If T is a derived class of some base B, then std::unique_ptr<T> is
implicitly convertible to std::unique_ptr<B>
which it obviously must be for polymorphism to work as it does with raw pointers. My question is, if a smart pointer is not generally convertible to a pointer as we can see here, then wha... |
My question is, if a smart pointer is not generally convertible to a pointer as we can see here, then what is the mechanism used by the smart pointer to allow for runtime polymorphism?
Smart pointers are explicitly designed to make such conversion possible. As you can see in std::unique_ptr constructors documentation... |
63,303,628 | 63,303,797 | Random number example from Stroustrup has compilation error | I'm using this random number example from Stroustrup C++ 4th Ed Page 1182. The compiler is reporting an error on the line with auto, stating that auto cannot be used with non-static members of classes. I'm confused on what the type of this bind results in. Does anyone know how to resolve the error so the random numbe... | You can't use auto for the type of a non-static member of a class, so the code example is wrong.
Instead, you can do:
class Rand_int {
private:
std::function<int()> r = bind(uniform_int_distribution<>{p},default_random_engine{});
// ...
};
This converts the return type of std::bind to a void function returning... |
63,304,478 | 63,304,612 | Why is T not string* when template <typename T> string debug_rep(T *p) is called with debug_rep(&s) | I'm trying to understand an example from C++ Primer to do with template overloading.
They define two function templates:
template <typename T> string debug_rep(const T &t) { ... }
and
template <typename T> string debug_rep(T *p) { ... }
The following call is then made:
string s("hi");
cout << debug_rep(&s) << endl;
Th... | When the compiler sees this template:
template <typename T> string debug_rep(T *p)
and a call like:
debug_rep(&s)
the compiler will do its best to match the type of the argument to the type in the function declaration.
Since the type of the argument is string*, and the type in the declaration is T*, the simplest way... |
63,305,473 | 63,319,350 | How can I get direct access to a QWidget in a QTableView? | I know you can insert a QWidget (like QLineEdit) into a tableview.
For Example:
QSortFilterProxyModel *m = new QSortFilterProxyModel(this);
ui -> tblView -> setIndexWidget(m -> index(0, 0), new QLineEdit); // works fine
//another option
QLineEdit *le = new QLineEdit;
ui -> TblDataLeagues -> setIndexWidget(m -> index(i... | As the documentation says, this function returns generally a QWidget to fit any subtype in the table. So, you need to apply casting for the retrieved object using the generic qobject_cast<Target> if you're sure of the type at this index.
|
63,305,525 | 63,311,694 | Can't get OAuth 2.0 code in Qt app, but is seems to work in browser | I'm trying to configure communication with Google OAuth 2.0 in my Qt project. I was using this tutorial, although it seems to be a bit outdated. I configured everything in Google APIs site, used those data in Credentials/OAuth 2.0 Client IDs page:
Header file:
#ifndef GOOGLEAUTH_H
#define GOOGLEAUTH_H
#include <QObje... | I have tested the example and strangely it does not work for the "email" scope, after analyzing the http request I found that the problem is the encoding of the "code" received and that it is used to obtain the token. So my solution is to correct that parameter and that can be done override the requestAccessToken() met... |
63,305,639 | 63,305,744 | Unable to have proper C++ template deduction working (C++17) | I'm unable to have this code running properly on Ubuntu 20.04 (gcc), and I'm only able to have the template deducted for the else branch (integers), ignoring all the deductions for bool, double and std:string
I even tried the std::enable_if but to no avail...
What am I'm missing here?
#include <iostream>
#include <stri... | T is being deduced as a reference here. For example, when invoked with a double, the argument is double & && (which collapses to double &). T is double &, which is not the same thing as double. std::is_same_v<double &, double> is indeed false.
One solution would be to remove any reference from T before checking:
std... |
63,305,648 | 63,305,760 | Random number generation: compilation errors | I'm trying to adapt an example from Stroustrup C++ 4th Ed Page 1182, to call a function from operator()() vs the bind. Unfortunately, I'm getting a number of compilation errors. The code that worked before is // commented out. Does anyone know how to resolve the errors?
#include <iostream>
#include <random>
#include... | This line:
uniform_int_distribution<>{p}(re);
modifies the member re. So the operator() can't be marked const.
You need to do:
int operator()() { // non-const method
return uniform_int_distribution<>{p}(re);
}
Here's a demo.
|
63,305,732 | 63,306,222 | Flood fill algorithm uncovers all area (Minesweeper) | I'm implementing flood fill algorithm for minesweeper game on C++ and all is fine, but I'am not enjoyed the result of it's work. It's uncovers all area except bombs when in right version it needs to uncover some area with numbers, that represents amount of bombs nearby.
void floodfill(int x, int y)
{
if (x < 0 || y... | I looks like you are treating a spaced filled with a number the same as a blank space. If you assign a number to a tile you wouldn't need to floodfill() past it.
|
63,305,755 | 63,305,859 | Using '=' operator to make two arrays equal in C++ | #include <iostream>
using namespace std;
void Fun(int arr1[], int arr2[])
{
arr1=arr2;
for(int i=0;i<5;i++)
{
cout<<arr1[i]<<" "<<arr2[i]<<endl;
}
}
int main() {
int arr1[5];
int arr2[5];
for(int i=0;i<5;i++)
{
arr1[i]=i+1;
arr2[i]=i;
}
Fun(arr1... | In function arguments, int arr1[] has the same meaning as int *arr1.
arr1=arr2;
is an assignment of pointers and now arr1 and arr2 point at (the head of) the same array, so the same array is printed in Fun().
On the other hand, the assigment affect only the pointer and not the arrays pointed at, so it will not affect ... |
63,305,865 | 63,306,552 | Makefile: create a build directory | I have a C++ project with the source files spanning many directories, and with interdependencies in the headers (the headers of one directory include headers from other directory source).
I have a makefile looking like this :
CXX = g++
CFLAGS = -Wall -std=c++17
SRC = *.cpp ./num_utils/*.cpp ./shapes/*.cpp ./data_utils/... | This makefile is probably only dedicated to gnu-make (because of
the wildcard, patsubst, dir builtin commands and ifeq) in a unix environment (because of mkdir -p, rm -rf).
It recreates below the build directory the same directory hierarchy as the source files.
According to further questions in the comments, the abilit... |
63,305,961 | 63,306,032 | C++ function that returns an ostream | I have a number of operator<<() functions that start by doing something similar, so I want to abstract that. Here's a minimal reproducible case of what I'm trying to do (with all the complexity ripped out). Note that it doesn't compile. If it did compile, I would expect the program to print the number 3 on a line by... | You're using an incredibly weird and unique (ie bad) pattern for this, and the way to use it would be:
BaseFunction(cout, 3) << endl;
Note that you pass your input stream to your function as a parameter, and since you return the stream as an output, and there is no overload of operator<< that takes a stream on the lef... |
63,305,993 | 63,335,628 | Calling a method inside a method of a different class C++ | In my code, I have two classes. The first class has a private variable x. I'm trying to change its value by calling a method defined in a second class - setClass1X(). This method takes two parameters, the value that I want to set x to and an object of type class1. This method should call another method setX() of an obj... | As @MikeCAT has already pointed out a copy of class1 being pass and the changes made to the copy doesnt reflect into the original instance. So the solution is to pass the instance by reference.
However classes should be dependned on each other at the class level rather than at method level to mark clear dependnecy; unl... |
63,306,004 | 63,306,149 | Remove Duplicates from Sorted Array using O(1) Auxiliary Space (LeetCode) | This is my function
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
auto i = nums.begin();
int prev = *i;
i++;
for(;i!=nums.end();i++){
if(*i == prev){
nums.erase(i);
}
prev = *i;
}
return (i... | std::vector::erase will invalidate iterators and return new iterator, so you should catch the returned iterator.
Try this:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
auto i = nums.begin();
int prev = *i;
i++;
for(;i!=nums.end();){
if(*i == pre... |
63,306,352 | 63,306,385 | What n&1 and n>>=1 mean? | I was doing this exercise : https://www.hackerrank.com/challenges/30-binary-numbers/problem and I found this code, but I didn't understand what the condition with n&1 and n>>=1 do here.
//C++ program to convert a decimal
// number to binary number
#include <iostream>
using namespace std;
int main()
{
int n,count... | if (n&1)
checks whether n is odd by doing a bitwise and.
n>>=1;
shifts the bits of n to the right by one bit.
|
63,306,518 | 63,306,581 | Downcasting with reinterpret_cast | I am a person, who loves to go deep into nitty-gritty details. This time I created really simple functionality, which I called "Scenario" (look under for code). First I will present to you
my vision of it:
struct ScenarioContext
{ virtual ~ScenarioContext() = default; };
struct IScenarioStep
{
virtual ~IScenarioSt... | reinterpret_cast should never be used to cast down the class hierarchy because it doesn't do base pointer adjustment, which is going to bite really hard in case of multiple inheritance.
One can (and should!) use static_cast if they can be certain true object type matches the one expected through some means. static_cast... |
63,306,807 | 63,689,336 | CMake manage local dependecies | I have two libraries a and b. The last depends on functions defined in the other (a).
When I link a to b it has no effect.
MWE on wsl2 with g++9 and cmake 3.16:
[...]
add_library(a ${a_SRC})
target_link_libraries(a CONAN_PKG::<foo>)
add_library(b ${b_SRC})
target_link_libraries(b a CONAN_PKG::<bar>)
add_executable(m... | Actually, I misunderstood the issue I had.
In fact, b is a header-only library that depends on a.
The proper formulation is provided here:
Linking a library to a header-only one
Thanks to squareskittles, for his comments.
|
63,306,932 | 67,991,418 | Local variables not showing on CodeBlocks | In the following code, all the variables disappears except for c. If I hover over the value of c in watches, I can see all the local variables.
int x=61, i=0, sq=0, s1=0, s2=0;
char a='a';
I have tried both TDM-GCC-64 and minGW, both show the same problem. How do I fix this?
| The problem was with gdb trying to print CP65001 characters. The fix was to goto, settings->debugger->default->Debugger initialization commands and type,
set charset UTF-8. This fixed the problems for me.
|
63,306,948 | 63,307,090 | Random number generation, two different methods? | Does anyone know the differences between the two methods of random number generation used in the following code? My suspicion is the first case may be more computationally expensive because it's getting a new seed from /dev/urandom every time a random number is generated. Also appreciate any comments if I'm generatin... | The first method is bad practice, and the second is preferred. Although, in the second method, default_random_engine is typically not recommended unless it's for experimenting or some other non-important reason. The big reason is that's implementation-defined, so it will differ based on compiler, and it generally is no... |
63,307,132 | 63,307,360 | How do I (programmatically) ensure that a dll contains definitions for all exported functions? | Let's say I have this lib
//// testlib.h
#pragma once
#include <iostream>
void __declspec(dllexport) test();
int __declspec(dllexport) a();
If I omit the definition for a() and test() from my testlib.cpp, the library still compiles, because the interface [1] is still valid. (If I use them from a client app then they ... | No, it's not possible.
Partially because a dllexport declaration might legally not even be implemented in the same DLL, let alone library, but be a mere forward declaration for something provided by yet another DLL.
Especially it's impossible to decide on the object level. It's just another forward declaration like any... |
63,307,326 | 63,307,518 | How do you randomly generate a number from an array and then use that number in a switch statement in C++? | I am very new to c++ and I am trying to randomly pick one of my cases to use, but it is going straight to default. I would appreciate it if someone could tell me what I am doing wrong or maybe a better way to do it. This is my code:
class selectingTheVillain {
public:
void theRandomness() {
int theRandomChoice;
int v... | You have 2 issues in your code.
Firstly, on this line:
int randIndex = 1 + (rand() % 4) ;
you are generating indexes in the range 1 .. 4, but you need 0 .. 3. So simply remove the + 1 like this:
int randIndex = rand() % 4;
Secondly, this assignment:
villainArray[randIndex] = theRandomChoice;
doesn't modify theRandom... |
63,307,402 | 63,333,712 | Change application theme with C++ | I'm trying to implement a settings page (with XAML and C++), with three radio buttons: "Light", "Dark" and "Use system theme". How do I do Application.RequestedTheme? Thanks!
| Based on this document about Application.RequestedTheme, it mentions
The theme can only be set when the app is started, not while it's
running. Attempting to set RequestedTheme while the app is running
throws an exception (NotSupportedException for Microsoft .NET code).
If you give the user an option to pick a theme t... |
63,307,885 | 63,310,316 | Is there an option in Visual Studio that provides a simple view of how a file is included in my C++ code without building? | So I have below code in my file mine.cpp,
#include <iostream>
#define max INT_MAX
The identifier "INT_MAX" will be undefined if I remove "#include <iostream>". So, I know it is defined somewhere in iostream.
When I go to the definition of INT_MAX it is in limits.h file. So, I guess limits.h is nested include in iostre... | That's a strange requirement:
without building.
What exactly are you trying to avoid? Building the entire project/solution? To save time?
As noted by @dxiv and @Boris, you need to at least compile that file. More strictly - run a pre-processor on it to expand macros, conditional compilation, etc.
Compiling you file w... |
63,307,990 | 63,308,020 | How to update a while loop with multiple if statements? | I am working on the "checkout" process of my vending machine code. I want to write it so that the program will keep asking for the amount needed from the user until all the money is entered. However, this code segment does not completely work.
"Checkout" Segment of Code:
while (money < total) {
float amountOwed = t... | In this loop:
while (money < total) {
you are not modifying money or total so the loop will never exit.
You probably want to update money like this:
while (money < total) {
// ...
cin >> payment;
money += payment;
}
|
63,308,005 | 63,308,065 | Parse elements of a std::string into integers (C++) | I am getting an odd error in my code where I try to take the elements of a std::string and convert them into 2 seperate ints
An example of the string would be "A6". I would like to be able to convert this string into 2 integers. In this example, the integers would be 65 (because 'A' is 65 in the ASCII chart) and 6.
Cur... | The ascii code for 1 is 49, which is the result you are assigning to tempColumn. If you want the integer value, you need to do:
int tempColumn = userGuess[1] - '0';
This subtracts the ascii version of 0 which is 48 from the integer.
|
63,308,099 | 63,308,924 | Sudoku Solver Program - no change in output | solveSudoku function is called from main() function.
I have written the following function for solving sudoku :
bool isFull(vector<vector<char>>& board){
for(int i = 0 ; i < board.size(); i++){
for(int j = 0 ; j < board[0].size(); j++){
if(board[i][j] == '.') return false;
... | Imagine board contains a full sodoku, with only one cell blank ('.')
SolveSudoku will identify the cell, pos would have a single value, the for loop will do only one step (and do some weird thing to board !)
Then in the loop SolveSudoku is called recursively, as the board is full now, this recursive call will return at... |
63,308,118 | 63,308,682 | Recursive memory "tree": properly freeing memory | Fresh out of my first CS class, I wanted to get more practice with recursive memory allocation, so I decided to make a little game known as the "Recursive Dungeon." It simply allows users to roam through an infinite dungeon by recursively generating a new "room" every time a player enters an empty (NULL) room.
The new ... | Your algorithm would not work even if double delete was okay.
If you have two rooms connected to each other, they will recursively try to delete each other leading to stack overflow. I.e. you cannot delete cycles with simple recursion.
You have a design problem - who owns each room? Had this been written in a garbage-c... |
63,308,371 | 63,308,430 | Moving By Reference for strings? | In my class I wrote the following line:
string t1,t2;
MyClass(std::string tmp1, std::string tmp2) : t1(from), t2(to) {}
To improve performance I could change it to:
string t1,t2;
MyClass(const std::string &tmp1, const std::string &tmp2) : t1(from), t2(to) {}
But in that case won't the original arguments the the class... | Let's start from the end:
But in that case won't the original arguments the the class members share the same string? (Both point at same object)?
Each of your strings is a separate value. Nothing is being shared between them, regardless where you initialize them from. If you initialize a string from a const&, a copy ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.