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 |
|---|---|---|---|---|
67,265,389 | 67,266,750 | Link error with static library in C++20 module | I'm learning the C++20 modules feature, but whenever I try to include a header file inside a module and then try to link it, I get a link error. I got the error when working with the GLFW library, but I made a minimum reproducible example so you can help me more easily.
Here are the steps to reproduce this issue:
Get ... | You've put #include below module, which probably declared libraryFunction as a module function. It makes sense, since linker looks for something like test-libraryFunction.
MS sources on modules (what a time to be alive to use MS as credible source) say you can include "global" headers but it should be done before 1st m... |
67,265,538 | 67,266,792 | Oracle SSL authentication wallet no longer working | I'm running test to connect to locally installed Oracle DB using SSL Oracle wallet.
I was able to create the wallet and use them for authentication successfully around two weeks ago. But this no longer seems to be working. Here is how I created the wallets.
Create Server wallet and export certificate:
orapki wallet cre... | Ok, it seems I just missed one more settings in the Server's listener.ora
This time I was creating wallet in different location than previous test.
WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
(DIRECTORY = C:\app\TestWallet\Server)
)
)
Changing this follow by:
LSNRCTL> stop
LSNRCTL>... |
67,265,933 | 67,266,028 | dereferencing void pointers to objects | Given the following piece of code as a minimum working example:
#include <iostream>
class Object_A
{
public:
int attribute_a,attribute_b;
Object_A(int a,int b){
this->attribute_a = a;
this->attribute_b = b;
}
int object_method(){
std::cout << "Hello from Object A: " <... | You cannot indirect through a pointer to void. And there is no need for a pointer to void.
The simplest solution is this:
int number = 1;
std::cout << input
? obj.alpha.object_method(number)
: obj.beta.object_method(number);
For the edited question: The above still works, but you can get rid of the repetition ... |
67,266,150 | 67,266,535 | How to compare two objects by class name or type (equivalent of Java's `getClass()` in C++) | I'd like to compare two objects by their class name. The first object is of type Card* which points to a MagicCard object, and the second is of type MagicCard - a child class of Card. When I compare them with typeid it doesn't work:
if (typeid(*(this->cards[index])) != typeid(card)) {
//the first object is of t... | It's almost always incorrect to be looking at typeid.
You can get a MagicCard * from a Card * with dynamic_cast, and it will be a null pointer if the Card * doesn't point to a MagicCard object.
if (auto * magicCard = dynamic_cast<MagicCard>(cards[index])) {
// do something with magicCard
}
However it is often bett... |
67,266,240 | 67,275,829 | please can someone explain me why this quick sort code is not working as expected | I have made quick sort for the first time without seeing any code just by seeing the animation, but the solution is not what I am expecting. can any one tell me what I am doing wrong in this code? because as per me the algorithm should work, but it's not working. please point out my mistake. if you can it would be very... | In your partioner() function, it should have been:
int piv = array[low];
Instead of :
int piv = array[0];
Further reading : Quick sort - Geeksforgeeks
Side note : If you're using C++, maybe take a look at sort() : sort() - cplusplus.com
|
67,266,252 | 67,266,902 | Why did it show "InvMod: inverse undefined" when used CRT algorithm in NTL library? | I tried to use NTL library to implement my cryptographic algorithm. However, it showed me someting wromg about CRT algorithm. CRT is short for Incremental Chinese Remaindering and it is defined as following:
long CRT(ZZ& a, ZZ& p, const ZZ& A, const ZZ& P);
long CRT(ZZ& a, ZZ& p, long A, long P);
// 0 <= A < P, (p, P)... | From ntl/ZZ.cpp:1307, the following comments are given for the CRT function:
// Chinese Remaindering.
[...]
// This function takes as input g, a, G, p,
// such that a > 0, 0 <= G < p, and gcd(a, p) = 1.
[...]
long CRT(ZZ& gg, ZZ& a, long G, long p)
In your case, we need gcd(p, q) = 1, but with your values, gcd(p, q)... |
67,266,355 | 67,267,092 | How should I fix this code wherein I need to print the first n numbers in the Fibonacci Series?(C++) | This particular Code was made on Dcoder on Android...
My question is,How am I still able to execute it if my input for n is less than 6..(Condition i>=6 is not fulfilled for the for loop right..)Also using this code I always get the answer as 1,2,3,5,8... and the number of terms printed is always more than the input of... | Your use of the comma operator is a problem and is leading you to believe that the condition is actually enforced.
This statement
i>=6,i<=n;
ignores the result (false if n==6) from i>=6, despite evaluating it and then proceeds to check if i<=n because that's how the comma(,) operator works in this context. Thus your l... |
67,266,373 | 67,266,497 | C++ Class is not being Initialized | In C++ you can't include Header Files in each other because of recursion. So you have to make use of Predefined Classes right? So I want to get the value of num in C.hpp and print it out in B.hpp.
C Class gets initialized before B Class which is expected.
Console Output
But when I'm trying to call A::instance->c it is ... |
C Class gets initialized before B Class which is expected.
No, it's not expected, the order of evaluation of function arguments is unspecified.
But even if that's the case as in your example output, you've created new C class object, and now you are trying to create B class object and during that, you are trying to a... |
67,266,558 | 67,266,670 | Is constructor called if nothrow new return nullptr? | If I use new and get std::bad_alloc compiler do not call constructor because of exception. But how does it works with the nothrow new cause we get pointer in every case? Is there special paragraph in standard for this case?
|
[expr.new]/16 ... if the allocation function returns null, initialization shall not be done, the deallocation function shall not be called, and the value of the new-expression shall be null.
|
67,266,841 | 67,267,195 | Running a task in a separate thread which shold be able to stop on request | I am trying to design an infinite (or a user-defined length) loop that would be independent of my GUI process. I know how to start that loop in a separate thread, so the GUI process is not blocked. However, I would like to have a possibility to interrupt the loop at a press of a button. The complete scenario may look l... | As far as i know, there is no standard way to terminate a STL thread. And even if possible, this is not advisable since it can leave your application in an undefined state.
It would be better to add a check to your MyClass::runLoop method that stops execution in a controlled way as soon as an external condition is fulf... |
67,267,282 | 67,268,295 | NSight Compute - expecting bank conflicts but not detecting any | I was trying to detect shared memory bank conflicts for matrix transposition kernels. The first kernel performs matrix transposition without padding, and hence should have bank conflicts, while the second kernel uses padding, and should not have bank conflicts.
However, profiling with NSight Compute in the memory workl... | For a block dimension of 32x32, I wouldn't expect either kernel to demonstrate bank conflicts. Bank conflicts are covered in many resources including many questions here on the cuda tag, so I shall summarize briefly.
Bank conflicts arise when two or more threads in the same warp (and during the same instruction) are d... |
67,267,414 | 67,275,320 | How to serialize sparse matrix in Armadillo and use with mpi implementation of boost? | I've been trying to serialize the sparse matrix from armadillo cpp library. I am doing some large-scale numerical computations, in which the data get stored in a sparse matrix, which I'd like to gather using mpi(Boost implementation) and sum over the matrices coming from different nodes. I'm stuck right now is how to s... | I hate to say so, but that answer by that sehe guy was just flawed. Thanks for finding it.
The problem was that it didn't store the number of non-zero cells during serialization. Oops. I don't know how I overlooked this when testing.
(Looks like I had several versions and must have patched together a Frankenversion of... |
67,267,701 | 67,267,831 | How to set a custom variable name through a function argument | So what i am trying to do is basically get the second argument of a function, and making the second argument the name of a variable so i can easily store the users input. Here is my code
`
#pragma once
#include <iostream>
using namespace std;
void askAndStore(string question, string variable)
{
cout << question ... | You can't do this in C++.
You could have a std::map<std::string, SomeType> that you populate with your read-in names.
#pragma once
#include <iostream>
#include <map>
#include <string>
class Values
{
std::map<std::string, std::string> values;
public:
void askAndStore(std::string question, std::string name)
... |
67,268,109 | 67,268,263 | How can make white background of the picture with texts in C++ | I want to crop the text on a 1280x720 image and put the text back on a 1280x720 white image. I want the places outside the writings to be white.
Actually, I cropped all the texts in the picture and made a collage, but the size of the texts changes, I don't want this.
I want the position and size of the text in the pict... | here is the python code:
import cv2
import numpy as np
def get_white_image(img, crops):
image_sizey, image_sizex, c = img.shape
white_image = np.zeros([image_sizey, image_sizex, 3], dtype=np.uint8)
white_image.fill(255)
for crop in crops:
white_image[crop[0]:crop[1], crop[2]:crop[3]] = img[crop... |
67,268,556 | 67,270,874 | SSL implementation over limited AT Commands (ESP32, AI Thinker A9G) | I'm working on a project on the ESP32 connected to an AI Thinker A9G through serial. Right now I'm using the AT commands the A9G is shipped with. I have to connect to a Google App Engine endpoint over https, but there is no AT command support for SSL on the A9G.
Is there a way to wrap the A9G at commands in a c++ ssl l... | AT commands are a rather limited interface for talking to Internet. If they work, it's a great shortcut. If they don't, well, they don't.
The ESP32 can support a ppp dialup stack natively, talk to Internet, do HTTPS requests etc. Just use the modem as a regular dumb old modem, a terminal to establish a data connection.... |
67,268,747 | 67,268,830 | Two Images on one Object in OpenGL | I have two textures. One is jpg and the other is png. I have rendered a cube and I want to use the jpg image as a background in every face of the cube and then have the png on this background. I tried mix() but i can see the background through png and I don't want that. Is there any function that can do this for me?
Fr... | You need to mix the color depending on the alpha channel of the PNG texture. Assuming texture1 is the JPG and texture2 is the PNG, mix texture1 and texture2 depending on texture2's alpha channel:
vec4 color_jpg = texture(texture1, TexCoords);
vec4 color_png = texture(texture2, TexCoords);
vec3 color = mix(color_jpg.rgb... |
67,268,904 | 67,269,594 | I've found this code to change the font but it doesn't work | I've just found this answer to change the console font and size. But it didn't work: Either the font stays at Consolas or changes to Courier new. I would like to use Lucida Sans Typewriter.
CONSOLE_FONT_INFOEX cfi{};
cfi.cbSize = sizeof(cfi);
cfi.nFont = 0;
cfi.dwFontSize.X = 0; // Width o... | It's a bug that hasn't been fixed yet. If the font name contains more than 16 characters it won't be set through the API (but it works from the console).
The call to SetCurrentConsoleFontEx() returns success regardless of if the specified font was set or not.
Read more here:
https://github.com/microsoft/terminal/issues... |
67,269,318 | 67,269,488 | Memory will not release in C# singleton mode | I have a puzzle about singleton mode freeing object memory in C# between in C++;
Here C++ Code:
#include<iostream>
using namespace std;
class Rocket
{
private:
Rocket() { speed = 100; }
~Rocket() {}
static Rocket* ms_rocket;
public:
int speed;
static Rocket*ShareRocket()
{
if (ms_rocket ... | In C# Dispose mainly is used to release unmanaged resources as soon as they are not needed and not to free the memory occupied by object itself - it is handled by garbage collector which will free (when GC will decide that it needs to run) it only when it will become unaccessible from so called GC roots (and static var... |
67,270,156 | 67,270,210 | A use-case for r-value members | I've discovered an interesting piece of code and I wonder if it is UB or not? At least, according to cppreference it should not be. Is it a valid case for using an r-value reference?
The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference...
Something simila... | TL;DR: This won't work the way you want it to. It likely won't be UB though, as long as instance_ references something that lives long enough to support an operator=(...) call from load(...).
Explanation
References of any kind, whether rvalue or lvalue, cannot be rebound once initialized, and cannot be left uninitializ... |
67,270,234 | 67,270,795 | Is there a way to simplify/consolidate this send function | Is there a way to simplify/consolidate this send function for example:
int __fastcall HSend(void* _this, void* unknown, BYTE* buffer, int len) {
if (len > 0)
{
std::cout << std::hex << "[Packet]" << std::endl;
std::stringstream EncrpytedPacket;
for (int i = 0; i < len; i++) {
... | Don't use endl. Just output \n to write a newline character. It is rather slow, and output to console is "unit buffered" anyway.
Doing all the iostream mode changes, fill, width, etc. for every single byte in a loop is slow. Which of those are remembered between calls anyway? Or, use an efficient function to conver... |
67,270,242 | 67,270,306 | How to find the index of the first character in a matching regex? | This is my first question here, I hope that It doesn't sound stupid. So I'm trying to find a way to get the index of the first character from a string that matches the regular expression. I made my research in the regex reference in cplusplus.com but I wasn't able to find anything (probably my fault). For anyone that s... | What you are looking for is the position() function of match_results, so something like that should work:
if (rematch.size() > 0)
cout << "It matches at position " << rematch.position() << "\n";
|
67,270,266 | 67,270,875 | Passing Multiple Strings in Concatenation Attempt to an ostringstream Parameter | I am trying to create a method that will accept a stream (i.e. ostringstream) parameter that will be logged to a file.
In the header file, it is declared as:
static void Log(const std::ostringstream& message, LoggingSeverity severity = LoggingSeverity::info);
However, when I try to call the method from another class, ... | Well the problem here is you are passing a string to a stringstram constructor, the idea is ok but the constructor is defined explicit so there is no automatic conversion to from string to stringstream, explicit stringstream (const string& str , ios_base::openmode which = ios_base::in | ios_base::out); , you can find d... |
67,270,447 | 67,693,086 | VSCode LLDB on MacOS error when starting debugging session | I'm trying to configure VSCode for compiling/debugging C++ programs on MacOS. I am using the following launch.json file:
When I try and start a debugging session, I get the following error:
Warning: Debuggee TargetArchitecture not detected, assuming x86_64.
ERROR: Unable to start debugging. Unexpected LLDB output from... | I had the same problem and I found that VScode does not support a debugger for ARM64 binaries yet. Here is the issue link.
However, it works if you use another extension. Install CodeLLDB and set "type": "lldb" on launch.json like below.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view... |
67,270,904 | 67,271,030 | Overload left shift operator << to object | I am not able to overload the left shift operator "<<" so I can use the following code:
Foo bar;
bar << 1 << 2 << 3;
My class Foo looks like this:
class Foo{
private:
vector<int> list;
public:
Foo();
void operator<<(int input);
};
And the implementation like this:
void Foo::operator<<(int input)
{
// h... | To enable chaining you must return a reference from the operator. When you write
bar << 1 << 2 << 3;
That actually is
((bar << 1) << 2) << 3;
ie operator<< is called on the result of bar << 1 with parameter 2.
The problem is I can't. I am missing a object reference of the object bar.
You seem to miss that your oper... |
67,271,566 | 67,306,851 | WRL::ComPtr causes object leaks in d3d? | I am making a simple d3d 11 application and I'm using the Microsoft::WRL::ComPtr to release the resources automatically. For some reason though when the applications exits I'm getting 30-40 Live Object warnings from d3d. I could have missed one or two, but this seems more like the count of all objects I have. I'm obvio... | Getting a 'clean exit' can be a little challenging. It's not likely to be ComPtr if used correctly. Per the comment, a good place to start is object naming. Remember that the output happens when the Direct3D Device is released, so you may need to look at the 'release order' to get it to cleanly exit. There are also 'in... |
67,271,892 | 67,271,936 | pop_back function in custom vector class | So I've been looking at code from this website: https://www.geeksforgeeks.org/program-to-create-custom-vector-class-in-c/. But I'm having a problem understanding this part:
template <typename DT>
DT GenericMyVector<DT>::pop_back()
{
return arr[length-- - 1];
}
I understand that this lowers int length by one, and w... | length-- evaluates to the value of length (decrementing after evaluation). So the item you're accessing is arr[length - 1]. You need the -1 because array indexes start at zero.
It's easier to think of the code as:
template <typename DT>
DT GenericMyVector<DT>::pop_back()
{
DT value = arr[length - 1];
length--;
... |
67,271,902 | 67,282,142 | How can I correctly open my WxFrame loaded from an XML resource file? | I'm relatively new to both C++ and Wx, so I've been doing a lot of blundering around trying to get this to work over the past few hours, but I seem to have hit a figurative brick wall with this issue.
This code compiles with no errors, but when run, it does nothing. It simply remains running until terminated (e.g. with... | Your MainFrame gets destroyed when you reach the end of the function, which is not at all what you want for a frame which is supposed to exist for a long time. The simplest correct thing to do is
wxFrame* MainFrame = wxXmlResource::Get()->LoadFrame(NULL, "MainFrame");
if ( !MainFrame ) {
wxLogError("Failed to load ... |
67,272,008 | 67,272,996 | format floating point number to a char array of limited size with optional decimal point | I need to print out floating point numbers to a fixed number of chars. This is used in a strictly text-based data protocol (yes I know). Decimal is inclusive in character count. Ignore null terminator. There is no min padding requirement. Decimal precision can be 0 to (buffer size - 2) while max number of real num... | Here is a C++ 17 version:
#include <iostream>
#include <charconv>
std::string to6(float f) {
std::string s;
s.resize(10);
auto ec = std::to_chars(s.data(), s.data() + s.size(), f, std::chars_format::fixed);
s.resize(6);
if (s.back() == '.')
s.resize(5);
return s;
}
int main()
{
std... |
67,272,067 | 67,272,228 | C++ Union Curly Bracket Initinitializer: "error: expected member name or ';' after declaration specifiers" | I'm new to C++ and read about curly bracket initializer which is available in C++ 11. I try to create a simple union which looks like this
union UExample {
UExample(const uint12_t value = 0) : raw{value} {}
uint12_t raw;
};
When I try to compile the file I get this error
./stack.h:18:57: error: expected member ... | I found a solution for this problem. It relates to the g++ compiler on MacOS. clang++ should be used instead.
Before (not working):
g++ stack.cpp -o stack
After (working):
clang++ -std=c++11 -stdlib=libc++ stack.cpp -o stack
|
67,272,262 | 67,272,440 | Unresolved external symbol of constructer when using STL vectors | So, I have a pretty simple project in VS2019 that includes three files:
a.h
#pragma once
class A {
public:
A();
};
a.cpp
class A {
public:
A() {}
};
main.cpp
#include <vector>
#include "a.h"
int main() {
std::vector<A> va;
va.emplace_back();
return 0;
}
It works fine without vectors. But this c... | The compilation unit with main sees only this declaration
class A {
public:
A();
};
and indeed the constructor is not defined.
The declaration of the class A in the module a.cpp breaks the one definition rule. That is the class declared in a.cpp is not the same as the class declared in a.h.
In the case of this def... |
67,272,372 | 67,272,577 | How to extract the first digit of a 16 digit number? | I have this code right here that compiles just fine getting the first digit of a 10 digit number.
I am wondering how to get my code to get the first digit of a 16 digit number?
I have tried changing 10 to 16 in the while loop and my program does not count the first digit. Here is my code down below:
#include <iostream>... | int has at least 16 bits. The exact size is implementation defined. Even with 32 bits the maximum value is 2147483647. You cannot store a 16 digit number in an int.
You can store numbers with more digits than any integer type can hold in a std::string. Because just reading some string from the user and printing the fir... |
67,272,421 | 67,272,449 | Finding largest Integer C++ |
Given an array A of N integers, return the largest integer K>0 such that both values K and -K(the opposite number) exist in Array A. If there is no such integer, the function should return 0.
Example:
Given A = [4,-4,-4,2] the function should return 4
Given A = [ -2,0,0,-3], the function should return 0, as there is... | if (A[first] = -A[last])
is wrong, you probably want:
if (A[first] == -A[last])
(the first one is a assignment, the second one is a comparison)
|
67,272,498 | 67,273,157 | SIGNALSEGV (segmentation fault) out of vector pushback method | I am making a shell using linux (WSL).
For some Unkown reason, when I pushback a struct pointer (that I made) into a vector it calls SIGNALSEGV.
These are the main classes of the problematic code,
class TimeoutCommand : public BuiltInCommand {
public:
bool background;
std::string line;
int pid;
int dura... | The problem was that i instialized a pointer to an instance of TimeoutList without allocating a new istance.
|
67,272,771 | 67,402,783 | Read access violation when inserting into unordered map | I am messing with a small ECS implementation found here. I slowly copied the code to understand it and it works fine. However, instead of one big namespace, I'm trying to separate the functionality out into different classes and abstract everything with a "coordinator" class before I try to add the "system" part of ECS... | The answer ended up being due to static order initialisation fiasco. The solution was to access the static template variable in the Coordinator via a getter to ensure its initialisation:
class ECSCoordinator {
//....
template<class Component>
ComponentContainer<Component>& get_registry();
//...
};
te... |
67,273,079 | 67,273,349 | C++ object deletion crashing | I tried to include all necessary code that may be causing these problems.
The program crashes the second time this code is run:
for (int i = 0; i < player.projectiles.size(); i++)
{
bool temp = player.projectiles[i].move(begin, WIDTH);
if (temp == true)
{
... | You are not storing Projectile* pointers in your vector, you are storing actual Projectile objects (as evident by the fact that your loop is accessing members of the Projectile class using operator. instead of operator->). So, calling destroy() on any of those objects is absolutely the wrong thing to do, because you ... |
67,273,112 | 67,273,200 | Visual Studio C/C++ extension shows error message even if the code is correct | My Visual Studio compiler is showing me error messages even when the code is correct.
Even on a simple code like,
#include<stdio.h>
int main(){
int add(firstNumber, secondNumber){
int result=firstNumber+secondNumber;
return result;
}
int out=add(10,30);
printf("%d", out);
return 0;... | Neither C nor C++ Standard allows nested function definitions as in this program
#include<stdio.h>
int main(){
int add(firstNumber, secondNumber){
int result=firstNumber+secondNumber;
return result;
}
int out=add(10,30);
printf("%d", out);
return 0;
}
where the function add is def... |
67,273,235 | 67,273,313 | Using Ninja as a generator with MSYS2 + MinGW on Windows 10 x64 | I am using MSYS2 + MinGW x64 + CMake as my development setup on windows. Currently, to initialize my projects, I open a "MSYS2 MinGW 64-bit" shell and invoke CMake as follows:
cmake .. -G"MinGW Makefiles"
This works nicely, but I'd like to use ninja instead of make. Therefore, I installed mingw-w64-x86_64-ninja via my... | In my company we use mingw64 + ninja on windows 10 on a daily basis. I am not sure what is going wrong in your setup, here's a few tips:
Run cmake from the mingw64 shell, not the msys2 shell (usually C:/msys64/mingw64.exe)
Make sure you installed mingw-w64-x86_64-cmake, not just cmake or mingw-w64-cmake.
Make sure you... |
67,273,591 | 67,273,626 | Crash when returning a char array from a function | A freind and I are working together on an ESP32 webserver, and we have hit a wall. My buddie has pretty much given up on it, and I am less skilled than him.
We have the following functions, which compile fine, but cause the ESP32 to crash.
After lots of debugging I am pretty certain the crash occurs when trying to retu... | You are returning a pointer to an automatic (i.e. stack-based) variable. That variable goes away when sdcard_list_files returns, leaving the pointer 'dangling`.
One solution is to declare c as static. Another (in C++) would be to return a std::optional <std::array<std::string>, 6>>.
|
67,273,730 | 67,274,169 | Use Qt Signal and Slots when object is not defined in main class | My code has following structure:
include
-> myserver.h
-> mythread.h
-> mainwindow.h
src
-> myserver.cpp
-> mythread.cpp
-> mainwindow.cpp
main.cpp
MyServer class creates a new thread for each connection. In that thread, I am reading the data from the client and want to send it to mainwindow.cpp. For this, I am th... | Create a signal
void newDataRecieved(QVector<double> x,QVector<double> y);
In MyServer class and then connect the signal newDataRecieved form MyThread to the same signal of MyServer. Then in mainwindow connect a slot to the signal form MyServer.
Is there a way trigger a signal from another signal in Qt?
[EDIT]
Somethi... |
67,273,867 | 67,279,332 | Building nlohmann/json as a bazel library gives 'nothing to build' error | I have a very simple bazel project where I'm trying to add https://github.com/nlohmann/json as a dependency. To accomplish that, I cloned the json repo locally and added a BUILD file in the repo's root dir to generate a cc_library containing the single include json.hpp file. But when I build that, it always complains t... | It is better to fetch external dependencies using http_repository/git_repository mechanism, because they do not clutter the history of the repo, they are easier to update and they are not even fetched, if you do not build anything, which depends on it.
# /WORKSPACE file
http_archive(
name = "com_github_nlohmann_jso... |
67,273,973 | 67,274,028 | C++ Assertion Failed: cannot increment value-initialized map/set iterator | I have been doing some training in C++, and last time I tried to run my code on another computer. There, I build in debug, and the execution stopped due to an assertion failed. I am manipulating containers, and when I use map, it seems removing an element is not possible. The removeItem() methode is triggering the asse... | Rewrite this for loop
for(auto it = m_shoppingList2.begin(); it != m_shoppingList2.end(); it++)
{
if(it->second == f_item)
{
m_shoppingList2.erase(it->first);
}
}
the following way
for(auto it = m_shoppingList2.begin(); it != m_shoppingList2.end(); )
{
if(it->second == f_item)
{
it ... |
67,274,057 | 67,274,415 | Parallelizing a 1D matrix multiplication using OpenMP | I'm new to OpenMP and I'm trying to parallelize a 1D matrix multiplication (only multiplying the upper triangle of the matrix). My solution now is fast, but it's currently only using approximately half of the available threads, so I'm supposed to further parallelize it but I don't know where to start (I know saving dat... | First of all, you can start by removing the continue in the loop and start the i-based loop at the value j. Then, you can focus on the load-balancing issue between the threads.
One simple solution to balance the work between threads is to work simultaneously on the beginning and the end of the matrix (in each thread). ... |
67,274,161 | 67,274,771 | Generic logger vs. exception pattern | Consider a class foo which has one or more functions which can report failure either through a logger or by throwing an exception if no logger was provided:
struct logger
{
// ...
};
struct foo
{
void set_logger(std::shared_ptr<logger> logger) { m_logger = std::move(logger); }
bool bar(const std::filesyst... | Since your error case handling seems to follow the same structure, you could add a simple function that will do just that:
bool log_or_throw(logger * logger_, std::string const& message, std::exception const& exception) {
if (logger_) {
logger_->warn(message);
return false;
}
else {
... |
67,274,676 | 67,276,062 | Count number of matching bytes between two _m128i SIMD vectors | I'm developing a bioinformatics tool and I'm trying to use SIMD to boost its speed.
Given two char arrays of length 16, I need to rapidly count the number of indices at which the strings match. For example, the two following strings, "TTTTTTTTTTTTTTTT" and "AAAAGGGGTTTTCCCC", match from 9th through 12th positions ("TTT... | You're probably doing this for longer sequences, multiple SIMD vectors of data. In that case, you can accumulate counts in a vector that you only sum up at the end. It's a lot less efficient to popcount every vector separately.
See How to count character occurrences using SIMD - instead of _mm256_set1_epi8(c); to sea... |
67,274,889 | 67,275,117 | Trying to Create a game where the will be a Regular User and an Admin, in C++ but Stucked when I have to get the inheritance correct. Who to Inherit | In C++ I am trying the subject of OOP in the line of creating a console-based game with a regular user and the admin. Where admin can add new users, add game rules, and more. While the user can only play the game without having access to the ability of the admin.
Now I am trying to get a way to have the user to inherit... | What it seems to me is that admin should inherit from user as admin has more abilities. Your code should look like this:
class user{
string name
string password
void play();
void login();
void quit();
}
class admin: public user{
changePAssword();
changeRules();
addNewGames();
};
You don't need to restate name and p... |
67,274,905 | 67,275,036 | C/C++ resolving docker compose services to same IP | I'm trying to resolve the IP addresses of some docker compose services from another container within the docker compose network running a C/C++ socket program.
Here is my docker-compose.yml
version: "3.9"
services:
grad_calc_1:
image: worker:1
ports:
- "8080:8080"
environment:
... | Building on @KamilCuk's comment, here's one possible fix:
#include <string>
std::string resolve_host(const char* host_name) {
struct hostent *host_entry;
const char *IPbuffer;
host_entry = gethostbyname(host_name);
IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]));
return IP... |
67,275,018 | 67,275,070 | Why does my Anti-Virus think that my C++ program is a virus and how can I fix it? | When compiling and running my program, my antivirus (Kaspersky Security Cloud) automatically deletes the executable and tells me to restart my computer so that it can disinfect my computer. I have a few questions.
Why does the AV think my exe is a virus?
How can I stop it from thinking it's a virus?
How can I retrieve... | Your anti-virus should put the executable into a quarantine where you can tell it whether or not the quarantined file is actually malicious. This video might help you with that: https://youtu.be/NA6HrN-gO5A.
As mentioned before, adding your build folder or project directory to the AV's exception list is also a solution... |
67,275,908 | 67,275,966 | Failed to use namespace correctly in my .cpp file | I declare a namespace MYTIME in mytime.h file.
#include<ostream>
#ifndef _TIME_H
#define _TIME_H
namespace MYTIME{
class time
{
...
};
}
#endif
And try to use it in my time.cpp file,
#include"mytime.h"
#include<iostream>
using namespace std;
using namespace MYTIME;
time::time()
... | Your header guard is using a name that is already defined. As a result, your namespace and class is never declared.
A simple test demonstrates the problem:
#include <iostream>
int main()
{
#ifdef _TIME_H
std::cout << "Well, well, well...\n";
#endif
}
You would expect this program to have no output, but when comp... |
67,275,945 | 67,275,972 | auto & vs auto &&: Which one should we use in a for loop | I've read this link: What is the correct way of using C++11's range-based for?, I've known why we use auto && to loop a vector<bool>. But I still have one more question about auto & and auto &&.
class Test {};
vector<Test> vec = {Test{}, Test{}, Test{}};
vector<Test> vec2;
// case 1
for (auto &element : vec) {
vec2... | Unless there's a specific reason to write your own loop, I'd say none of the above. Instead, I'd use:
std::move(vec.begin(), vec.end(), std::back_inserter(vec2));
At least by my reading, this makes it fairly apparent both:
what you're trying to accomplish, and
that you're really doing what you want to.
|
67,276,289 | 71,398,031 | Cmake: undefined reference to included methods | I am learning to use cmake and I am trying to compile a simple set of tests using gtest for a very small project that I wrote.
my CMakeLists.txt looks like
cmake_minimum_required(VERSION 2.6)
project(circuit_sim)
include(FetchContent)
FetchContent_Declare(
googletest
# Specify the commit you depend on and update ... | Since you need external class, you should put that class "library" in target_link_libraries(), so that the last line of your CMakeLists.txt will become
target_link_libraries(test connector gtest_main)
Also, in another CMakeLists.txt which is in the same directory as Connector.cpp, your should declare them as one libra... |
67,276,463 | 67,289,970 | error: call to 'CrossProduct' is ambiguous | I have created a template class named Vector in a header file, say foo.h. Here is a MWE of how I defined the template class and functions operating on objects of the class
#ifndef FOO_H_ ... | The declaration of Point3D CrossProduct(const Point3D&, const Point3D&); inside namespace foo and the definition of Point3D CrossProduct(const Point3D&, const Point3D&) { /*...*/ } in the global namespace refer to different functions (the former one having no definition).
Note that using namespace foo; only affects nam... |
67,276,775 | 67,278,799 | How can remove this gcc flags from linker flags in cmake? | I made simple kernel for studying purposes. I cange MakeFile to CMakeLists.txt to automatically genreate my kernel form sources. But I encounter this relocation error.
/usr/bin/ld: CMakeFiles/x86_64-kernel.bin.dir/src/arch/x86_64/multiboot2_boot32.asm.o: relocation R_X86_64_32 against `.boot.32' can not be used when ma... | Finally I figure out how to remove useless linker argument from cmake. CMAKE uses compiler as an default linker. In my case, gcc is default linker because I build my source code with gcc. The important fact is that cmake also berings CMAKE_CXX_FLAGS with gcc in linking stage. So we have to use custom linker as like thi... |
67,276,940 | 67,276,993 | Is it possible to move a std::unique_ptr to itself? | I have a situation where I would like a unique_ptr that could be a class, or its decorator as follows:
std::unique_ptr<Base> b = std::make_unique<Derived>();
if (needsDecorator)
{
b = std::make_unique<Decorator>(std::move(b));
}
where
class Derived: public Concrete {...}
class DecoratorC : public Base {...}
Is mo... | You are creating a new unique pointer from an old one, not moving one into itself.
If this code ran:
pClass = std::make_unique<ClassDecorator>(std::move(pClass));
It would take the pClass, move it while constructing a ClassDecorator from it. However, your ClassDecorator class would need to have a constructor that tak... |
67,277,223 | 67,277,278 | Regarding #define macro after #ifndef | In a C program, one of the *.h file was written as follows :
#ifndef T2_A
#define T2_A
// code segment
// code segment
// code segment
#endif
The first line was trying to evaluate if macro T2_A is defined; if not, it should be defined. But the second line is just #define T2_A, and it does not assign any value to it... | As multiple comments have already said, the purpose of this structure is as an "include guard". This ensures that a header is not included twice in same translation unit.
Say you have a.h which includes t.h file, also b.h which includes t.h file.
When a foo.cpp include both a.h and b.h two copies of t.h file is include... |
67,277,693 | 67,278,228 | How to avoid Microsoft C26451 (arithmetic overflow) warning | How to code defensively against the Microsoft C26451 (arithmetic overflow) warning in my example? I feel like this should be trivial to fix. So frustrating!
// Linear interpolation
// target - the target point, 0.0 - 1.0
// x... - two values {X1} {X2}
inline static double Linear(float target, double... | The compiler warning doesn't make sense and newer Visual Studio versions does not give the same warning. I'd disable it for this line only:
inline static double Linear(double target, double x1, double x2) {
#pragma warning( push )
#pragma warning( disable : 26451 )
return (target * x2) + ((1.0 - target) * x... |
67,277,800 | 67,279,067 | run c++ script multiple times which reads csv file | I have a c++ console app to be ran multiple times. It reads a large csv file everytime it runs which doesn't change . It is a slow process.
Is there any way to just "load" the file in memory and not have to read everytime I run the file.
I was thinking in ways R and python works. You load a csv as dataframe and can us... | Assuming most of time is wasted on CSV parsing, and not on file-system operations, you can store your parsed data to a new file using fwrite. On second execution, read the other file using fread, instead of parsing the CSV-file.
Pseudo-code:
data = allocate()
open 'file.parsed'
if successful:
fread('file.parsed', d... |
67,277,912 | 67,288,488 | Link error when using a _com_ptr_t (auto-created by #import) only in a template | After #importing a .tlb file, I tried to use one of the generated _com_ptr_t objects in a function template. This works fine if the functions I use are also used outside of a function template. However if it's only used in a function template, I get a link error.
Can anyone explain why this happens? I'm guessing it's t... | As per the comments, I unearthed this archived
KB Article which talks about the #pragma implementation_key compiler directive, which is used to improve performance when a type library has a lot of methods (over 1000 it seems), which mshtml.tlb does. This directive appears in the generated mshtml.tlh and .tli files. The... |
67,278,189 | 67,278,826 | C++ background thread in class - instance scope | I have this simple class:
struct Foo {
void Run() {
this->bgLoader = std::thread([this]() mutable {
//do something
this->onFinish_Thread();
});
}
std::function<void()> onFinish_Thread;
std::thread bgLoader;
};
That is called from C-API:
void CApiRu... | You could return the Foo instance to the C program:
struct Foo {
~Foo() {
if (bgLoader.joinable()) {
run = false;
bgLoader.join();
}
}
void Run() {
run = true;
this->bgLoader = std::thread([this]() mutable {
while(run) {
... |
67,279,660 | 67,279,984 | How can I solve the error 'expected expression'? | The C++ code that gets an error is below. My g++ version is clang version 12.0.0 (clang-1200.0.32.27)
(The code is written by others many years ago, and may because of the version updates of the g++, I can not run it successfully now. )
typedef struct Cond{
int offset1;
bool (*comparator) (void * , void *, AttrTyp... | The quick fix is to add -std=c++17 to support this C++ feature.
The actual fix is to use C++ more effectively, like employing a std::vector plus using emplace_back to create entries as necessary:
// Malloc the list of conditions to be met
std::vector<Cond> condList;
for (int i= 0; i < numConds; ++i) {
condList.empla... |
67,279,662 | 67,285,755 | How do I use boost::icl::hull? | The following code doesn't work:
typedef boost::icl::interval_set<unsigned> bi_list_type;
typedef bi_list_type::value_type iv_type;
std::vector<iv_type> y;
iv_type x; // how to initialize this?
for (auto i : y)
{
x = boost::icl::hull(x, i);
}
The problem is, that x is default constructed and thus in the end 0 is al... |
"a better way to use boost::icl::hull"
That depends 100% on the desired goal.
"(the doc isn't helpful in this regard)"
The doc also doesn't know your goal; it only tells you operations you can use to reach the goal.
I don't know your goal, but to me it looks very much like it's working:
Live On Coliru
#include <boo... |
67,279,733 | 67,294,834 | How to save a QImage with transparency? | I want to create a PNG image with transparency.
QImage image(dim, dim, QImage;;Format_ARGB32);
And I set the
qRgba(qRed, qGreen, qBlue, alpha)
But the alpha channel does not modify the transparency/opacity of the color, instead modify the intensity color (from white to color).
Thus, how can I set the transparency of ... | How do you expect to see the transparency? Ordinary image viewers like photo viewers in Windows and Linux are painting the image on a white canvas. That's why the transparent pixels are being blended with white color. Look at the pictures below :
White background with no transparency on the circle:
The same circle wit... |
67,279,885 | 67,427,156 | WebRTC One to Many Connection | I'm building a personal project that makes a one-to-many connection with other users, this what my plan looks right now:
User Initiates a P2P connection with the C++ Server
The C++ Server Initiates a P2P Connection with other clients and forwards the stream of the broadcaster
I'm planning to use the WebRTC C++ API av... | "Firstly, is this possible?"
Yes
"secondly is this approach reasonable?"
Yes
That's exactly what media servers do.
|
67,280,270 | 67,280,547 | Why can't I use boost::adaptor::map_values outside a ranged-based loop? | I want to use boost's boost::adaptor::map_values to construct a vector of all values of a std::map. Take this example code (or try it at Godbolt):
#include <boost/range/adaptors.hpp>
#include <boost/range/adaptor/map.hpp>
std::vector<int> getValueVector(const std::map<int, int> & m)
{
auto valueRange = boost::adap... | I am not familiar with ranges, but this might be an answer, so I post it as answer.
At the top they write:
Syntax Code
Pipe rng | boost::adaptors::map_values
Function boost::adaptors::values(rng)
And indeed when I change your code to this:
#include <boost/range/adaptors.hpp>
#include <boost/range/adap... |
67,280,581 | 67,280,738 | Member is inaccessible when overloaded operator is friended | The code doesn't link when I try to compile, the error is "undefined reference to operator*" and I think this may be the problem.
This is my .h file:
namespace space{
class Number{
.
.
public:
friend Number operator*(double scaler, const Number& one);
... | The friend declaration is a declaration of a function:
namespace space{
class Number{
friend Number operator*(double scaler, const Number& one);
// ...
};
As this is inside a namespace, the function that is declared is space::operator*. Then you define ::operator* in the global namespace. Those are two dif... |
67,280,884 | 68,253,176 | Why is the braced-init-list not supported in an aggregate deduction but brace elision is supported? | Why is the braced-init-list not supported in an aggregate deduction but brace elision is supported?
#include <iostream>
template<typename T>
struct Test{
T t[2];
};
int main(){
Test t{{1,2}}; // #1
// Test t1{1,2} // #2
}
#1 is rejected by GCC while #2 would be accepted by GCC.
According to over.match.class.d... | This is a bug in GCC up to version 11.2, and fixed in GCC 11.3. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101344 for detailed explanation what caused this bug.
Even earlier versions of GCC can compile similar and even more difficult case A (as was mentioned in the comments to the question):
template<typename T, ... |
67,281,236 | 67,284,158 | boost/beast/core.hpp: There is no such file or directory | I need to write a server in C ++ and today I downloaded Boost via sudo apt-get install-f libboost-all-dev , but this sample code does not compile. Writes an error:
boost.cpp:16:32: fatal error: boost/beast/core.hpp: There is no such file or directory
#include <boost/beast/core.hpp>
And and /usr/include/boost/ no "beast... | According to the documentation,
https://www.boost.org/doc/libs/1_66_0/
Beast
Portable HTTP, WebSocket, and network operations using only C++11 and Boost.Asio
...
First Release 1.66.0
you need to upgrade to at least 1.66.0
Edit
In practice, you have a few options
Upgrade ubuntu release. Yes, some people consider i... |
67,281,249 | 67,288,124 | QT: Run a function as long as button is toggled | I want to implement a GUI that receives messages from an external device. The "advancedReceiveExample" is waiting for messages. Once it has received one, it does stuff with it, saves it and terminates.
I want to make my function wait for new messages after receiving one as long as the button is toggled.
I have tried th... | Note QT is event-based. If you keep your computer busy inside some function without returning to the main loop frequently, your GUI will freeze.
What you need to do is slice your action that you want to do into small bits that can repeatedly return to the main loop in order to keep the GUI responsive. (Another method y... |
67,281,350 | 67,281,371 | Class operators can not access member variables | I am working on an integer class that should be able to do basic arithmetic. The integer values are stored in an array where every array element holds two integer values. I convert this array of integers into the member variable integer.
class Integer {
private:
char* arr;
bool t;
int integer;
int arr_len;
pub... | You have to indicate that the operators belong to the class Integer.
To do so, add Integer:: before names of each operator.
Also the signature in the definitions of operator doesn't match to the declarations. They return Integer in the declarations, but they are defined to return Integer&.
Integer Integer::operator-()
... |
67,281,374 | 67,281,973 | interpolating values on 2D plane for planes of same bounding box but different mesh structure | I have simulated data provided on a computational mesh at each intersecting mesh line (i.e. node) and want to interpolate that onto a new 2D plane that has the same dimension (i.e. they both have the same bounding box) but for post-processing reasons I need a cartesian mesh rather than an arbitrary curvilinear one. The... | In python you can use scipy.interpolate.griddata. This accepts unstructured data and interpolates it onto a given points:
from scipy.interpolate import griddata
import numpy as np
# Generate some xy coordinates at random positions and some values at each coordinate:
xy = [(x, y) for x, y in np.random.random((100, 2))]... |
67,281,936 | 67,282,084 | conversion error from make_integer_sequence to integer_sequence | The following program does not compile:
#include <utility>
#include <iostream>
#define N 4
template <unsigned int I>
unsigned int g() { return I; }
template <unsigned int... I>
unsigned int f(std::integer_sequence<unsigned int, I...> = std::make_integer_sequence<unsigned int, N>{})
{
return (g<I>() + ...);
}
int ... | I admit, I do not understand the error message. The reason the second version compiles but not the first is that template parameters cannot be deduced from default arguments but from function parameters. Consider this simpler example:
#include <utility>
#include <iostream>
template <unsigned int>
struct foo {};
templ... |
67,282,073 | 67,283,194 | write_some: Broken pipe C++ | I have an issue with boost::asio. I'm trying to create basic chat, but have face write/write_some: Broken pipe error. Here's code
Client side
Message here it is empty vector<char> message, data = "Client"
createMessage(message, data) put data into message
void Client::connect()
{
int port = 9999;
boost::asio::i... | boost::asio::buffer(buffer.data(), buffer.size())
Could be
boost::asio::buffer(buffer)
And it doesn't work becuase buffer.size() is always zero. You should be using asio::dynamic_buffer or resize(n) instead of reserve(n)
Demo
I improvised a more complete example Live On Coliru
#include <boost/asio.hpp>
#inclu... |
67,282,119 | 67,289,820 | Echo command on unbind wont work with sudo, "Permission denied" | I'm creating a service in CPP that detect a connection of USB and block it if it's mass storage.
To do so, I'm using echo "{USB}-{PORT}" >> sys/usb/drivers/usb/unbind and it remove the USB.
the thing is, its only working after sudo -i and using CPP system command wont let me run it as root. Plus I am unable to use the ... | The shell interprets the >> within the current user prior to executing the sudo. That is, it tries to open the file as the current user and THEN executes sudo with the file open for standard out. That's why you get the access violation.
You could produce a shell script that does the echo >> part and sudo execute the sc... |
67,282,128 | 67,282,194 | C++ Does RVO works with auto[x,y] = my_func()? | I cant figere out if RVO (return value optimalization) is guaranteed to happen in case of std::pair assigment with [] syntax.
Exapmple:
std::pair<vector<double>,vector<double> > my_funct() {
std::pair<vector<double>, vector<double> > _result;
auto& [x, y] = _result;
// do some calculation and fill up x, y
... |
I cant figere out if RVO (return value optimalization) is guaranteed to happen in case
return _result;
You're returning an lvalue. RVO is not guaranteed to happen.
RVO would work with auto [x, y] = my_funct() in the case my_funct were eligible to guaranteed RVO.
|
67,282,164 | 67,282,366 | Error running a newly created MFC project | I created an MFC project in Visual Studio and tried to run it but it got the error as shown in the picture.
this is the code:
#include "pch.h" #include "framework.h" #include "MFCApplication1.h"
#include "ChildFrm.h"
#ifdef _DEBUG #define new DEBUG_NEW #endif
// CChildFrame
IMPLEMENT_DYNCR... | The program fails to build, so the executable is not created. That's why it can't be started.
From your screenshots it appears that you don't have MFC installed as part of visual studio. So you should launch visual studio installer and install the MFC component, then try again.
|
67,282,350 | 67,699,343 | mpirun with socwatch fails | On trying to measure energy consumption on my system with an OpenMPI program.
For OpenMPI, we can run with
mpirun -n 4 ./hello
This program will print hello from 4 processes.
Now, If it is a C++ program, we can run SocWatch with it as
sudo socwatch -m -f sys -f wakelock -t 35 -p ./hello
With OpenMPI, I try
sudo socwa... | The most likely reason would be mpirun is in your $PATH as a user, but is no more in your $PATH when sudo is used. Try using the absolute path to mpirun instead. Note you will need to pass the --allow-run-as-root option to mpirun.
|
67,282,426 | 67,282,528 | PHP-CPP returning a string results in the strlen instead of plain string | So i wrote a little extension with the help of php-cpp. In this function, i just simply calculate the pow, which works perfectly fine. After calculating the result, i return the string from the function. When i call this extensions function in php, i receive an integer which contains the strlen of my original string, i... | According to the docs (and comparing it to regular printf), your function works as expected:
— Function: int mpfr_printf (const char *template, ...)
Print to stdout the optional arguments under the control of the template string template. Return the number of characters written or a negative value if an error occurred.... |
67,282,864 | 67,282,891 | Difference between declaring 2d vectors by two ways | What is difference between these two ways of declaring 2d vectors:
vector<vector<int>> b(n+n-1);
and
vector<vector<int>> b(n+n-1, vector<int>(n+n-1));
| vector<vector<int>> b(n+n-1);
Allocate a vector b with n+n-1 elements and initialize the elements with default value (a vector with zero elements).
vector<vector<int>> b(n+n-1, vector<int>(n+n-1));
Allocate a vector b with n+n-1 elements and initialize the elements with the specified value (a vector with n+n-1 elemem... |
67,282,904 | 67,282,994 | C++ : Error while using TEXT() function windows.h | I recently switched from Visual studio code to Visual studio 2019 because I wanted to download C++ package using VCPKG.
My code worked on Visual Studio Code but do not work on Visual Studio 2019, maybe because it's not the same compilator.
The code I found on a StackOverflow post (Get Computer Name and logged user name... | According to the Windows.h header file, TEXT() is not a function, its a macro. Its purpose is to convert string/character literals at compile-time to either wchar_t or char literals, depending on whether the UNICODE conditional is defined or not, respectively.
Basically the definition of TEXT is something like this,
#i... |
67,283,433 | 67,283,593 | How to prevent calling a non-static function of an uninitialized C++ object | Below is a minimal example of problem that occurred in a huge legacy project I am currently working on.
I have a main function that should be creating a new object ob a global object pointer B* B.
Because of a configuration error this was not done and the non-static method b->do_something() was called.
My expectation w... | You cannot prevent a user from all possible mistakes and most of the time it is futile to even try (this isnt Java ;). Thou shall not call a member on a non-initialized pointer (actually in your code it is initialized because it is global, but with nullptr). Thats not specific to your class, but something one has to co... |
67,283,909 | 67,284,759 | C++ regex difference between platforms | I have the following code:
#include <string>
#include <regex>
#include <iostream>
int main()
{
std::string s;
s += '\x06';
s += '\x00';
std::regex r(std::string(1, '\x06') + '\x00');
std::smatch sm;
if (std::regex_search(s, sm, r))
{
std::cout <<... | According to the C++ ECMAScript regex flavor reference,
The decimal escape \0 is NOT a backreference: it is a character escape that represents the nul character. It cannot be followed by a decimal digit.
So, to match a NULL char, you need to use \0 literal text, a literal \ char and a 0 char. You can define it with a... |
67,284,318 | 67,301,822 | Add two numbers: LeetCode | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
I... | Your code turns the input linked lists to integers, but that poses two issues:
The input may have linked lists with up to 100 nodes (digits), which exceeds to the range of the integer data type.
Your code treats the first node as the most significant digit, while it should be treated as the least significant digit.
T... |
67,284,337 | 67,293,418 | AVX-512 - Debugging application with Intel SDE not working | I am trying to debug AVX-512 instructions on an emulated CPU using Intel® Software Development Emulator but it doesn't work as desired after setting a breakpoint. I followed this blog post: Debugging Emulated Code on Linux*
In window #1:
~$ g++ -g -O0 -mavx512f main.cpp -o main # compile main.cpp file
~$ sde -debug -- ... | It seems to be broken for PIE executables
(confirmed on Arch GNU/Linux with GCC 10.2, GDB 10.1, SDE 8.33.)
Build with g++ -O2 -fno-pie -no-pie -g -march=skylake-avx512 and everything works. (I had to run gdb ./a.out instead of bare GDB; without that it couldn't find the right file even after connecting to the remote.... |
67,284,403 | 67,284,664 | Why should I use the three-way comparison operator (<=>) instead of the two-way comparison operators? Does this have an advantage? | #include <compare>
#include <iostream>
int main()
{
auto comp1 = 1.1 <=> 2.2;
auto comp2 = -1 <=> 1;
std::cout << typeid(comp1).name()<<"\n"<<typeid(comp2).name();
}
Output:
struct std::partial_ordering
struct std::strong_ordering
I know that if the operands have an integral type, the operator returns a P... | It makes it possible to determine the ordering in one operation.
The other operators require two comparisons.
Summary of the other operators:
If a == b is false, you don't know whether a < b or a > b
If a != b is true, you don't know whether a < b or a > b
If a < b is false, you don't know whether a == b or a > b
If... |
67,285,302 | 67,286,871 | Syntax error: 'constant' and Missing type specifier - int assumed. Note: C++ does not support default-int | I am trying to create simple structure.
template <typename T>
struct Element
{
T eValue; // Element Value
Element <T>* next_element;
};
template <typename T, int size>
struct dynamic_array
{
Element <T> first_element;
Element <T>* last_element = &first_element;
add(2);
void add(int count)
... | As pointed out by interjay you need to add the code inside the constructor to have it executed when you create the object. But you should understand the basic fact that template or not, you are defining a struct , compiler will convert it into respective structure when its used ( think of a vector) .Now when you create... |
67,285,497 | 67,285,526 | Why variable does not change after changing it within a for loop? | This is my code
#include <iostream>
int main()
{
int j = 1;
for (int i=0, j=1; i<10; i++)
{
std::cout << j << std::endl;
j++;
}
std::cout << j << std::endl;
return 0;
}
This is my output:
2
3
4
5
6
7
8
9
10
11
1
I just want to know why the value of j does not change out
| You have two variables j:
int j = 1; // 1st "j" here
for (int i=0, j=1; i<10; i++) // 2nd "j" here
You are modifying 2nd j in the loop and printing 1st j after the loop.
|
67,285,587 | 67,285,684 | C++ move constructor multiple calls, in std::vector | I wrote simple code in order to understand move semantics and move constructor.
#include <iostream>
#include <vector>
using namespace std;
class Data
{
public:
Data(int sz)
{
cout << "ctor" << endl;
buffer = new int[sz];
size = sz;
}
Data(Data& other)
{
size = ot... | When a vector grows it has to reallocate. A vector starts out with capacity 0 and only increases capacity when needed. Typically capacity is increased by factors of 2 to ensure the time complexity promised by push_back. Other factors are ok as well.
What you see is the vector moving the elements to different place in m... |
67,286,288 | 67,286,488 | mask and apply numpy where function to a vector in c++ | I'm using C++ and want to combine the masking of a vector and the search for the indexes where a condition is verified, similarly to the numpy where function.
Here's an example:
std::vector<int> id = {61, 66, 68, 80}
std::vector<int> val = {0, 0, 2, 1};
std::vector<int> offset = {62, 65, 70};
std::vector<int> ma... | You can just use a simple loop. Note that you do not need the intermediate array masked. Here is an (untested) example:
std::vector<int> c;
c.reserve(val.size());
for(size_t i=0 ; i<val.size() ; ++i)
if(id[i] > Offset[val[i]])
c.push_back(i);
|
67,286,335 | 67,292,974 | what's wrong with my code [ Dfs , Dynamic programming ] | i tried to solve this problem with dfs and dynamic programming . then
i submit my code to my school grader but the answer is wrong .
am i implement something wrong with dfs .
what's wrong with my code.
PS.sorry for my bad english
The problem :
given a random number there's 2 different way you can do with this
number
... | The darkest place is under the lamp.
Look at the problem definition:
1.divide it by 3 (it has to be divisible)
Where do you test for the divisibility?
So, one error is here:
if(valid(st/3)){
This test should read:
if(st % 3 == 0 && valid(st/3)){
With this simple improvement, all three test cases pass.
A hint to imp... |
67,286,472 | 67,286,599 | Why is it ok in C++ to define a member function in a header but not a free function? | Let's say I have three files A.cpp, B.cpp, and B.h. A.cpp and B.cpp both include B.h. I defined a free function in B.h (for whatever reasons). Then I get a linker error:
ld: 1 duplicate symbol for architecture x86_64
Which makes sense. The compiler compiles A.cpp and B.cpp separately, and so there are two functions w... |
Why is it ok in C++ to define a member function in a header but not a free function?
It is not OK to define non-inline functions more than once. This is part of the "One Definition Rule".
It is OK to define inline functions in more than one translation unit. In fact, inline functions must be defined in every translat... |
67,288,099 | 67,288,236 | Generic function to serialize from std::any | I am trying to create a function that serializes an object stored as std::any. The idea is, object is stored in std::any along with a function that can serialize it, then that function is called on the object.
I am running into the following problem.
#include <iostream>
#include <any>
using namespace std;
template<ty... | F as a function parameter can't be used as a template argument. It's not a constant expression.
F would have to be a template parameter in order for this code to compile. Function arguments are never constant expressions.
|
67,288,233 | 67,304,548 | Qt virtualkeyboard assertion error in 5.15.2 vs 5.12.3 | I recently updated my Qt version from 5.12.3 to 5.15.2. I rebuilt an application that uses a qt virtualkeyboard in QML using InputPanel {}. The virtual keyboard is defined in main as qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));. Everything works in release mode but when I run in debug mode I get the follow... | There was already an existing bug report on Qt's bug tracker. Previously I only searched by virtualkeyboard and not InputPanel. The bug report is here. BTW, it looks like this is only an issue in debug mode and a workaround is to click the ignore button several times to continue in debug mode.
Edit: Qt responded that t... |
67,288,767 | 67,288,927 | g++ -I include all subdirectories with header files | I've just stumbled upon this post about compiling all .cpp files, including those in subdirectories using the linux find command:
g++ -g $(find RootFolderName -type f -iregex ".*\.cpp") -o OutputName
The problem with this is that all files need their relative path written out when doing #include for this to work. You c... |
Is it possible to use find again with some other regular expression to include all of the subdirectories?
Yes it is - some projects, like mbed and arduino, seem to include all possible directories to include paths. In shell assuming there are no whitespaces, you could:
find . -type f -iname '*.h' -printf "-I%h\n" | s... |
67,289,304 | 67,292,231 | Operator overloading confusion in c++ | While using cppinsights to see how C++ sees lambda expression. The following part confused me.
// C++17
int main(){
int x = 10;
auto ff = [](int a) constexpr { return 1.2; };
}
to this
int main()
{
int x = 10;
class __lambda_3_14
{
public:
inline /*constexpr */ double operator()(int a) const
... | A lambda expression with an empty capture list defines a ClosureType with the following member function
ClosureType::operator ret(*)(params)()
which is a conversion to a function pointer ret(*)(params), where ret and params are the return type and arguments of ClosureType::operator().
Your lambda ff takes an int and ... |
67,289,460 | 67,289,881 | template class destructor for non-trivial types | I'm playing with c++20 concepts
https://godbolt.org/z/931xaeY45
#include <type_traits>
template<typename T>
class Optional
{
public:
~Optional() requires (!std::is_trivially_destructible_v<T>);
};
#include <cstdio>
int main()
{
const char* bool_value[] = {"false", "true"};
bool is_trivial = std::is_... | My read of the standard, and MSVC, says that this is a compile error.
In C++20, this:
~Optional() requires (!std::is_trivially_destructible_v<T>);
is a "prospective destructor". It may or may not become the actual destructor based on a series of rules. But what really matters is this rule:
If a class has no user-de... |
67,291,121 | 67,291,915 | Loading DLL results in error 193, even though it can load in both ctypes and JNA | I'm porting a Python program to C++ (on Windows). Since said code depends on a DLL, I need to load the DLL. But, when I call LoadLibraryA specifying the full path of my DLL (with backslashes), it fails to load and GetLastError returns 193.
Here's a sample program to demonstrate:
#include <iostream>
#include <windows.h>... | An easy way to check if you're compiling 64-bit or 32-bit code is to use the following code (C++17):
#include <iostream>
using std::cout, std::endl;
int main(int argc, char* argv[]) {
cout << "Your compiler compiled for " << sizeof(void*) * 8 << "-bit systems." << endl;
}
The code above works by checking the size ... |
67,291,327 | 67,291,334 | Pass char pointer to push_back vector of strings | Is below code adding valid strings to the vector?
std::vector<std::string> Filesystem::getAllFiles(std::string name)
{
std::vector<std::string> files;
DIR *dirp = opendir(name.c_str());
struct dirent *dp;
while (NULL != (dp = readdir(dirp)))
{
files.push_back(dp->d_name);
}
closedir(... | Yes, this code is fine 1, and it will invoke the std::string(const char*) constructor as expected, since dp->d_name is a (null-terminated) char[] array that will decay into a char* pointer.
1: provided that push_back() does not raise an exception, otherwise the DIR* will be leaked.
Note that calling push_back() with a ... |
67,291,669 | 67,292,597 | error: implicit instantiation of undefined template 'llvm::yaml::MissingTrait | I am working on a project which uses the LLVM YAML I/O library. This is the documentation/tutorial that I am following:
https://www.llvm.org/docs/YamlIO.html
I am trying to replicate the example where you define a specialization on llvm::yaml::MappingTraits for a struct data type. This example is at the top of the pa... | Reading the documentation, it seems to me that support for your specific vector<Person> requires registration with a macro:
LLVM_YAML_IS_SEQUENCE_VECTOR(Person)
// or
LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(Person)
See, Utility Macros: https://llvm.org/docs/YamlIO.html#id22
|
67,291,756 | 67,291,927 | Inconsistent encryption and decryption with OpenSSL RC4 in C++ | First off, I understand that RC4 is not the safest encryption method and that it is outdated, this is just for a school project. Just thought I put it out there since people may ask.
I am working on using RC4 from OpenSSL to make a simple encryption and decryption program in C++. I noticed that the encryption and decry... | actualKey needs to be pointing to a buffer of appropriate size before you pass it to EVP_BytesToKey. As it is you are passing in an uninitialised pointer which would explain your inconsistent results.
The documentation for EVP_BytesToKey has this to say:
If data is NULL, then EVP_BytesToKey() returns the number of by... |
67,292,806 | 67,295,984 | Qt: Attempt to add Drag and Drop to Editable Tree Model example not working | I'm trying to learn how to implement Drag and Drop to model/view settings in Qt. As an exercise, I attempted to do that to the Editable Tree Model example available at the Qt web site:
To extend it with Drag and Drop, I followed the instructions in Qt's documentation on "Using Drag and Drop with View Items", more spec... | The model provided by the example only accepts setting data with role Qt::EditRole. See line 263 in treemodel.cpp
bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
return false;
...
}
Removing that part or adding Qt::DisplayRole and the data... |
67,292,984 | 67,304,349 | Max For Live Not Patch Not Updating Data on Arduino Display | I've been working on a project with an Arduino recently where I'm basically trying to get a small display hooked up to an Arduino to update with the name of a MIDI mapped knob in Ableton Live.
For example, let's say I map the knob to the reverb send on a track the display should read "A-Reverb". This works today, but o... | Okay I figured this out on my own; basically what was happening was my code was expecting a line feed in order to refresh the output on the display. I figured out that I could send a line feed over the serial connection by sending the value "10" which would basically terminate the string as it is sent to the Arduino.
A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.