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 |
|---|---|---|---|---|
66,183,045 | 66,183,803 | Pre-allocating memory for linked list | In a technical interview, the guy asked me that "he wants to pre-allocate memory for a linked list just like we can do for array", so how would he do that?
I have never felt the need to, neither came across this thought! I mostly code in C++, and I answered something like "just like we use the new command in C++ for m... | Interview questions are generally asked not to be answered directly, and it is expected that you narrow down the use-case and requirements.
he wants to pre-allocate memory for a linked list just like we can do for array
If that is actually the question, then the interviewer either intentionally asked it wrong or misl... |
66,183,106 | 66,183,160 | Explain behavior of default priority_queue::top()? | The std::priority_queue, by default uses a std::vector<int> and the std::less comparator. By default, priority_queue is a max heap.
The docs for top() states:
The top element is the element that compares higher in the priority_queue, and the next that is removed from the container when priority_queue::top is called.
... | You're using the wrong algorithm, you can read at https://en.cppreference.com/w/cpp/container/priority_queue/priority_queue
that std::priority_queue doesn't use std::sort, but std::make_heap.
If you use it in your example as well, you get the output you're expecting.
std::vector<int> queue{1, 3};
std::make_heap(queue.b... |
66,183,170 | 66,222,682 | How to correctly subscribe the pixel value over the pixmap in the QGraphicsScene (as it is in OpenCV namedWindow)? | I am trying to implement the same functionality in my widget as it is in cv:: namedWindow.
The goal is to enable zooming and to make the overlay with the grid and the values of pixel's colors directly over the original pixmap. Here is the example: сv picture zoomed:
I inherited the QGraphicsView widget, added to QGrap... | I finally watched through the openCV source code and found what I looked for.
The answer for me was the QTransform matrix. OpenCV developers show the image not by using the scene in the QGraphicsView, but actually painting the image directly on the viewport in the paintEvent.
The QTransform matrix is stored in the clas... |
66,183,338 | 66,183,594 | Remove trailing comma of macro expansion | I have a 'system' to generate classes using macros (there is unfortunately no other way).
In some cases, for example for an initializer list, this leads to a trailing comma
that I'd like to get rid of:
#define REMOVE_TRAILING_COMMA(...) ?what to put here?
#define FOO a, b, c, d, e, f, g, h,
REMOVE_TRAILING_COMMA(FOO) ... | I would be nice to use #define REMOVE_FIRST(a, ...) __VA_ARGS__, but that would require reversing macro arguments order. I do not see a way to do it (other then overloading it anyway). So overload the macro on count of arguments and enumerate each overload to remove trailing argument:
// example macro overoad for up to... |
66,183,715 | 66,183,901 | C++ Derived classes only using part of inherited base constructor | I am certain that this is a basic question but I have not been able to find the answer anywhere. Let's say I have a base class with constructor:
class Parent{
public:
double propertyA, propertyB;
Parent(double propertyA, double propertyB){
this->propertyA = propertyA;
this->propertyB = property... | You can simply overload the constructor. Code should be like this -
class Parent{
public:
double propertyA, propertyB;
Parent(double propertyA, double propertyB){
this->propertyA = propertyA;
this->propertyB = propertyB;
}
Parent(double propertyB){
this->propertyA = 1.0; // cons... |
66,184,092 | 66,184,223 | How to resize and print lesser values than what I have? | I want to reduce the vector of my program. Basically print out lesser values. For example, I manage to search for what I need but I cannot reduce it. I searched for first choice as CC and got it. I also manage to sort it by GPA. It gave me 5 outputs which is correct but I only need 3 with the highest GPA. I don't know ... |
Move the CC vector outside of the loop.
Push matching lines into `CC.
Break the loop once CC is size 3.
i.e.
while (File >> line) //parse all the lines
{
v.push_back(line);
}
sort(v.begin(), v.end(), greater());
cout << "\nCC Students: " << endl;
std::vector<std::string> CC;
for (auto str : v)
{
if (str.find... |
66,184,228 | 66,184,488 | ESP-IDF How to ckeck if task is already running? | I have a job that should be ran with minimum interval of 5 seconds. Trigger that starts this job can be executed in any moment and in any frequency.
What is the best way to solve such a case in RTOS environment?
I want to make a function that creates a task if it does not exist. Existing task should wait for minimum in... | eTaskGetState can be used to check if a task is already running, but such a solution can be susceptible to races. For example your task is technically still "running" when it's in fact "finishing", i.e. setting task_done = true; and preparing for exit.
A better solution could be to use a queue (or a semaphore) and have... |
66,184,384 | 66,184,452 | Linking to a Boost library | I'm new to the Boost library usage, and I cannot figure out why the following is not working.
I want to compile the following code from the library's documentation:
#include <boost/regex.hpp>
#include <iostream>
#include <string>
int main() {
std::string line;
boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" );
... | Presumably /usr/local/lib/ contains both a static library (libboost_regex.a) and a shared library (libboost_regex.so), if you just specify -lboost_regex on your linker command line gcc by default prefers the shared library over the static one. The only way to prevent this is to pass the -static flag but this then stops... |
66,184,517 | 66,184,772 | Warning of conversion using srand | I have int r_number = 0; as a global variable.
In the code below:
srand(time(0));
r_number = rand() % 1000 + 701;
It keep spamming this warnings:
1>: warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data
Whats wrong in the conversion?
| The VC++ Level 4 warning message means to say time_t is a larger type than unsigned int - probably 64 bits, so the value returned by time() need to be truncated to 32 bits to be passed to srand(). In this specific case it doesn't matter, but it may be an issue in other places (consider handling file size as unsigned in... |
66,184,672 | 66,185,144 | How to temporarily switch to the GUI thread | I have a program that takes a long action, I run this function on a different thread. Periodically I need to update the information for the user, so I send a signal to the GUI thread. But sometimes I need the user to make a choice, I need to display the QDialog on the GUI thread and pause the slow thread while the user... | you need to invoke the method with BlockingQueuedConnection before condition3 for checking which option that selected by the user.
bool updateGui ;
QMetaObject::invokeMethod(this, "showDialog",Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, updateGui));
if(updateGui)
{
//update GUI
}
|
66,185,219 | 66,192,192 | Is it safe to call std::cin.putback(), std::cin.unget() without preceding them with a read operation? | Is it safe to call std::cin.putback without receding it with a read operation?
std::cin.unget(); // is it safe?
char c{};
std::cin.putback('V');
std::cin.get(c);
std::put(c); // V
I wander what unget() does on an empty iinput stream?
Because as I may think the read pointer is already at the beginning of the input s... | It is not undefined. Similar to other abnormal behavior on the stream (like reading characters after EOF is reached), it makes the stream "bad".
You can try:
std::cout << std::cin.fail(); // 0
std::cin.unget();
std::cout << std::cin.fail(); // 1
|
66,185,799 | 66,204,367 | Import targets during build process with MSBuild | I am using vcpkg as package manager with Visual Studio C++ project. I have created initial target to basically set up vcpkg (clone vcpkg repo and download vcpkg.exe):
<Target Name="EnsureVcpkgBuild" BeforeTargets="PrepareForBuild">
<Exec Command="git clone $(VcpkgRepo).git ..\packages\vcpkg" Condition="!Exists('..\... | You can directly use nuget package to realize them all automatically.
What I think is that you wrote a target to download the reop project vcpkg into the local and then manually import the core target from the dowloadeded vcpkg project.
It could be done easily on the local area but on the cl pipeline, it is not suitab... |
66,186,133 | 66,186,324 | Qt state machine assignProperty does not work | I tried to get started with a qt statemachine example-code in qt-creator, but for some reason it does not seem to work. I can build and run the code, but the "label"'s "text"-property does not change/appear, when clicking the "upButton". Has anyone ideas how to debug or get this working?
BTW: I am using qt 4.8, because... | machine is local to the constructor, it's deleted just after machine.start();
You should declare it as a private member of MainWindow
|
66,186,306 | 66,190,121 | boost::asio::read() blocks forever | I'm trying to learn how Boost.asio works. I've written a basic server and client example as such:
server.cpp
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#define PORT 27015
using namespace boost::asio;
using ip::tcp;
std::string read(tcp::socket& socket) {
boost::system::error_code error;
... | Read with the completion condition transfer_all means it will just keep reading until the buffer is full or the connection becomes invalid.
The buffer will "never" be full (since it's a DynamicBuffer).
So that leaves the cause that the client never hangs up.
Everything works properly if I swap boost::asio::read with b... |
66,186,766 | 66,186,928 | How does std::vector::reserve actually work? | I understand that .reserve() reserves memory for the vector without actually modifying its size. But how is this implemented? How can you just reserve memory without allocating it?
EDIT: I'm asking specifically about how to reserve memory without allocating it, not about how std::vector works in general
| vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect. The point is that reserving memory can be done without changing the vectors size. Basically a vector has two sizes, it's size and it's capacity. reserve allocates memory and changes the capacity, but not the s... |
66,186,769 | 66,186,806 | I don't get why my .find function don't work | I have a problem with this code. My if statement for userInput.find("=") is always true :
std::string userInput;
while (1)
{
std::cout << "> ";
getline(std::cin, userInput);
if (std::cin.eof())
{
std::cout << "Program Exit" << std::endl;
return 0;
}
if (userInput == "exit")
{
std::cout << "Pro... | Read the reference for std::string.find.
http://www.cplusplus.com/reference/string/string/find/
Note it says it returns the position of the query, or if none, returns string::npos, which if you follow through will see string::npos = -1 = SIZE_MAX. (this is the only un-used number in the size_t number space, as a string... |
66,186,792 | 66,209,218 | "Property console is not allowed" Problem in VSC Ubuntu 20.04 | I'm trying to debug my cpp program in Visual Studio Code in ubuntu 20.00. Hence,I'm facing to following problem:
{
"resource": "/home/xxx/Desktop/Project/.vscode/launch.json",
"owner": "_generated_diagnostic_collection_name_#4",
"severity": 4,
"message": "Property console is not allowed.",
"startLin... | replace "console": "externalTerminal" with "externalTerminal" : true if you would like your code to execute in a external console window. Otherwise remove the line completly
|
66,186,872 | 68,956,394 | Write real binary to file | I am currently working on a project to read binary data from a file do stuff with it and to write it back again. The reading works well so far, but when I try to write the binary-data stored in a string to a file, it writes the binarys as text. I think it has soemthing to do with the opening mode.
Here is my code:
void... | With the help of "aschelper" I was able to create a solution for this problem. I converted the binary string to its usual representation, before writing it to the file. My code is below:
// binary is a string of 0s and 1s. it will be converted to a usual string before writing it into the file.
void WriteBinary(const st... |
66,187,288 | 66,255,364 | C++17, Intel C++ compiler: what is the library needed to use filesystem header in windows 10 platform? | I just need to do some filesystem operation using #include <filesystem>, however, I get the below link error ... I guess I am missing a library in the xlink command. Below is the error message.
Please let me know your valuable comments.
test_accuracy.obj : error LNK2019: unresolved external symbol wmemcmp referenced in... | I raised the problem with Intel C++ Community here and it turns out to be a reproducible issue, and they suggested to update my VS 2019 Community Edition. I updated to 16.8.5 and it worked. So may be it is probably the right solution. (at least worked for me.)
|
66,187,426 | 66,187,517 | Is there any member function defined with std::array in c++20? | As I realized so far, there are no members like(sort, accumulate,push_back .. ) with a standard array, right? I think all of these nice methods only work with vector
| There are many member functions in std::array, like begin, end, rbegin, rend, max_size, fill etc, like it is mentioned here
|
66,187,675 | 66,188,049 | cmake: GNUInstallDirs variable differs before installation | I have a cmake file:
cmake_minimum_required(VERSION 3.5)
set(APP_NAME "vihoman")
project(${APP_NAME} VERSION 1.0 LANGUAGES C)
include( GNUInstallDirs )
set(CMAKE_C_STANDARD 11)
set(TARGET tgt PROPERTY C_STANDARD 11)
add_definitions(-DTEMP_PATH="${CMAKE_INSTALL_DATADIR}/${APP_NAME}/templates/")
set(SOURCE_FILES mai... | Like any other CMAKE_INSTALL_<dir> variable, which is set by GNUInstallDirs module, the variable CMAKE_INSTALL_DATADIR could contain a relative path.
It is perfectly allowed to use this variable in the DESTINATION option for install command, because relative values of this option are treated relative to the CMAKE_INSTA... |
66,187,717 | 66,188,265 | CryptoPP generates invalid keys RSA | I'm trying to encrypt some text with RSA in c++,
when encrypting I'm generating n, e, d but when trying to decrypt, the private key initializer says the keys are invalid...
So I built a code that generates the keys and then tries to initialize a private key object right after that and it says the keys are still invalid... | You problem is that you modified the exponent after the key was already generated.
params.GenerateRandomWithKeySize(prng, 2048);
params.SetPublicExponent(65537);
Actually the key was generated in the first line with e = 17. Try to change the line order.
params.SetPublicExponent(65537);
params.GenerateRandomWithKeySize... |
66,187,829 | 66,187,855 | Oculus Rift / Vulkan : Write to swapchain with a compute shader | I would like to write to the swapchain generated by OVR with a compute shader.
The problem is that the images don't have the usage VK_IMAGE_USAGE_STORAGE_BIT.
The creation of the swapchain is done with ovr_CreateTextureSwapChainVk which ask for a flag BindFlags. I added the flag ovrTextureBind_DX_UnorderedAccess but st... |
The problem is that the images don't have the usage VK_IMAGE_USAGE_STORAGE_BIT.
Then you cannot write to a swapchain image directly with a compute shader.
The display engine that provides the swapchain images has the right to decide how you may and may not use them. The only method of interaction which is required is... |
66,187,950 | 66,242,761 | What does a value with e` mean in windbg | I was using windbg to analyze a crash dump, for one of the variable of type unsigned long long, in the locals I can see its value being "0x002a002e`002a0000". What does value before and after e mean. Also what e(acute) itself mean?
| The format is described in MASM numbers and operators. So the e is, just like the a part of a hexadecimal number. A 64 bit hex number is separated into two 32 bit parts by the accent for readability purposes. Using the accent may have more implications, as defined in the definitions for sign extension.
With all that sa... |
66,187,960 | 66,251,715 | C++ best way to use a bitmap | I have this very big vector<unsigned char> bitmap that I use as a bitmap. Most of time it has like millions or billions of entries. So every bit in a unsigned char stands for a free(0) or used(1) block in my program. My function to set those bits looks like this:
int setNextFreeIDX_In(std::vector<unsigned char> & bitma... | So i simply solved this by adding a static var int lastSettedBlockIDX this helps me to jump right at the last setted bit. Chances are high that the next bit would be 0 so I don't have to loop through all idx´s anymore. Still there could be cases where iterating through the whole list would be necessary. For example aft... |
66,188,572 | 66,188,661 | why does concersion from int to const char* break C++ | hi recently I was learning C++ in Visual studio when I stopped on a problem when I want to use my method to log an int i need to convert it to const char* but when I do it things just crash is my code:
#include <iostream>
#include <math.h>
#include <Windows.h>
using namespace std;
double pi = 3.14159265358979323846;
... | "hi" is a null terminated string literal. int x is not.
When you cast (incorrectly) int x to a const char * you are telling the compiler, here is a pointer to a contiguous set of bytes that has a null termination char at the end of the sequence. Of course, int is not a pointer - so its value 10 is probably a invalid ad... |
66,188,652 | 66,188,712 | Cannot access type aliases of a forwarded type when passed by reference | My question revolves around the code below:
template<typename T>
static void whatever(T&& container) {
typename T::value_type x;
std::cout << x << std::endl;
}
struct something {
using value_type = int;
const char* name;
};
int main() {
whatever(something{}); // passes by rvalue, perfectly fine.
somethi... | You have to drop reference from deduced T type, for example by using std::decay_t:
typename std::decay_t<T>::value_type x;
|
66,188,815 | 66,188,816 | MSB6006 error "CL.exe exited with code -1073741819" caused by errors in code | TLDR: Both IDE and compiler missed an error in code, it only got reported by this exit code.
After a minor edit to my code regarding virtual methods, I got the error above seemingly out of nowhere. Translating the exit code to hex gives 0xc0000005, an access violation. Same problem is being solved here and here. Accord... | I tried to go back to where the error suddenly started appearing, and I found it. I am not sure how, but this error was caused by an incorrect piece of code I had written.
One of my headers contained two classes, one of which (base) was stand-alone as it was, but the other (derived) also provided a specific wrapper for... |
66,189,335 | 66,189,485 | Why a big size of array cannot be generated while a vector can? | I have the following code :
#include <random>
#include <vector>
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
const int N=100000;
int main() {
default_random_engine Generator(time(0));
uniform_real_distribution<float> dist(0.0f,nextafter(1.0f, DBL_MAX));
array<float,N> a{0};
//vecto... | Because the array allocates it's memory on the stack, while the vector allocates memory on the heap. You can allocate the array on the heap as well, with new or by using a shared_ptr or unique_ptr like so:
shared_ptr<array<float,N>> a(new array<float,N>{0});
float v = (*a)[10]; // dereference for operator access
|
66,189,547 | 66,189,738 | Nested template (C++17) compilation fails on VS19 | Code:
(Note that template is not instantiated - that's not a mistake, compilation fails even without it)
main.cpp:
namespace mylib {
template<typename ...Params>
class SomeClass {
public:
template<typename ...NestedParams>
class NestedClass {
};
template<... | It seems msvc has issues with the template. This compiles
namespace mylib {
template<typename ...Params>
class SomeClass {
public:
template<typename ...NestedParams>
class NestedClass {
};
template<typename ...NestedParams>
NestedClass<NestedP... |
66,189,798 | 66,194,416 | Default value for the second element of the map STL? | what is the default value for second element in map STL if i am initializing it with an array?
for example:
#include <bits/stdc++.h>
using namespace std;
void countFreq(int arr[], int n)
{
unordered_map<int, int> mp;
// Traverse through array elements and
// count frequencies
for (int i = ... |
what is the default value for the second element in map STL if I am initializing it with an array?
When accessing a key-value pair (kvp) in a std::map with operator[], either the key already exists, or a new kvp is constructed and the mapped_type is value-initialised. A value-initialized int is always 0. This imposes... |
66,189,851 | 66,189,873 | why the array print at the end different elements? | #include <iostream>
using namespace std;
int *position(int N,int vet2[], int x, int pos){
N++;
for(int i = N;i>=pos;i--){
vet2[i]=vet2[i-1];
}
vet2[pos-1]= x;
return vet2;
}
int main(int argc, const char * argv[]) {
int N;
cout<<"insert the dimention of the array"<<endl;
do{
... | You make an array vet2 of size N
int vet[N],vet2[N];
but then your program assumes that it has a size of 2*N.
for (int i = 0;i<2*N;i++){
cout<<vet2[i]<<" ";
Change
int vet[N],vet2[N];
to
int vet[N],vet2[2*N];
EDIT
The position function is bugged. There's no need for it, change this code
for(int i = 0;i<N;i++){
... |
66,190,085 | 66,190,148 | Shared Global Variable Between Different Files | Before marking this as duplicate, I've already tried the "common header + extern variable" method.
From link:
In A.cpp (or) B.cpp write,
int gVariable = 10;
Remember to write the above definition in only one source file or else
linker will complain of multiple symbols if you write in both the
source files.
And in the ... | You're using the same include guard in test.h and shared.h
#ifndef SHARED_H //
#define SHARED_H //
extern int testVar;
#endif /*SHARED_H*/
Also, you're not including test.h in test.cpp, nor actually defining testVar
#include "test.h"
int testVar = 0;
void toOne() {
testVar = 1;
}
https://onlinegdb.com/vCXz53Dt... |
66,190,197 | 66,190,408 | using std::accumulate when there is pointer | Is this the only solution when there is a pointer that points to a vector and we would like to use accumulate to sum up numbers?
Is there any simpler solution rather than writing a lambda function and using a four argument type of accumulating?
Also, for using std::sort, will the situation be the same?
Here is the code... | To answer your immediate question:
std::accumulate(p->begin(), p->end(), 0);
The same syntax will work for other STL algorithms as well.
Other improvements to your code snippet:
Avoid using #include<bits/stdc++.h>, see this post. Similarly for using namespace std, it's considered bad practise.
const N=3 -> const auto... |
66,190,824 | 66,203,836 | Spying on the filtergraph of an application that cannot be recompiled | If an application such as TV tuner doesn't add its filtergraph to Running Objects Table and therefore GRAPHEDT.EXE cannot spy on the application's graph, are there any other ways to see the application's filtergraph, short of recompiling the application?
| If you regiter DirectShow Spy in your system, it starts publishing filter graphs automatically, so that you can use GraphEdit or GraphStudioNext to connect to remote filter graphs of applications that did not publish graphs in first place.
A few notes:
you need to COM register the DLL that matches bitness of target ap... |
66,190,901 | 66,190,932 | Access an undeclared struct? | I there a way to access a struct that has not been declared yet?
//Need to some how declare 'monitor' up here, with out moving 'monitor' above 'device'
//because both structs need to be able to access each others members
struct{
int ID = 10;
int Get__Monitor__ID(){
return monitor.ID; //obvioulsly 'moni... | In this particular case, you can define the function prototype in the struct, and the definition can come later.
struct device_t {
int ID = 10;
int Get__Monitor__ID();
} device;
struct monitor_t {
int ID = 6;
int Get__Device__ID();
} monitor;
int device_t::Get__Monitor__ID() {
return monitor.ID;
}
... |
66,191,110 | 66,193,208 | Thread safe ExpiringDeque data structure in C++ | I am trying to create a data structure, ExpiringDeque. It should be somewhat similar to std::deque. Let's say I need only push_back(), size() and pop_front(). The data structure needs to automatically expire up to N first elements every T seconds.
This data structure needs to manage its own queue and expiration thread ... | You can avoid an unnecessary wait in the destructor of ExpiringDeque by using a condition variable. I would also use std::condition_variable::wait_for with a predicate to check the running_ flag. This will ensure that you either wait for a timeout or a notification, whichever is earlier. You avoid using waitCounter and... |
66,191,555 | 66,191,579 | How to apply templates to multiple `std::array`s? | I have a set of sets where all the sizes are known at compile-time and will not be changed, and I want to pass this to a function.
Something akin to:
void someFunction(
std::tuple<std::array<float,SIZE1>,std::array<float,SIZE2>,std::array<float,SIZE3>> sets
) {
//...
}
With the number of inner std:arrays bein... | Usually, you'd go with a variadic template for this:
template<std::size_t... sizes>
void someFunction(std::tuple<std::array<float,sizes>...> sets) {
// ...
}
The ... will expand std::array<float,sizes> for all sizes inside the tuple
|
66,191,721 | 66,191,733 | no match for operator<, even though operator< is defined | Here is the relevant part of my code. In one source file I have:
bool HFolder::operator<(const HFolder &rhs) {
return name < rhs.name;
}
bool HMessage::operator<(const HMessage &rhs) {
return contents < rhs.contents;
}
void HMessage::save(const HFolder &f) {
folders.insert(f);
}
I keep getting an error ... | You need to declare your operator as a const-method, like this:
bool HFolder::operator<(const HFolder &rhs) const
Otherwise it can’t be called on a const-object.
|
66,191,960 | 66,192,399 | Global variable doesn't update prior to next loop | I'm trying to build a tachometer in C++ for my ESP32. When I uncomment Serial.printf("outside rev: %d \n", rev); outside of the conditional it works, but when I comment it I get values that are orders of magnitude greater than they should be (700 revolutions without, vs 7 revolutions with). My best guess is that the ... | I think the test is to blame. I had to rename and move things a bit to visualize the logic, sorry about that.
bool magStateOld = false; // initialize to digitalRead(digitalPin) in setup()
int incrementRevolutions(int runningRevCount, bool magState)
{
int newRevCount = runningRevCount;
// detect positive edg... |
66,191,963 | 66,222,940 | flooding the views with update requests issue in observer pattern(C++) | I have some MVC code, it uses the observer mode, such as below:
void Model::ChangeMethod1()
{
m_A = m_A + 1;
...
Notify();
}
void Model::ChangeMethod2()
{
m_A = m_A + 2;
...
Notify();
}
void Model::ChangeMethod3()
{
ChangeMethod1();
ChangeMethod2();
Notify();
}
void Model::ChangeM... | I thought of 2 possible approaches:
If the subject is completely under your control and this solution is not too invasive, you could add an optional parameter specifying whether the called ChangeMethodX is a top level function, like this:
void Model::ChangeMethod1(bool topLevel = true)
{
m_A = m_A + 1;
...
... |
66,191,992 | 66,192,240 | How to use Macros in c++? | Recently I came across inline in c++17 and how it been used as an alternative to #define but both have its downsides. However my question is that if I want to cramp the whole std::cout << x << '\n'; in one simple line called LOG(x).
A: What should I use and why?
B: What are the pros and cons of each and when to use wha... | The general consensus is that using macros is not a good idea. BUT what that really means is that ABUSE of macros is not a good idea.
Solution #2 is OK, but its usefulness is rather limited, since you can only print one value per line.
inline void LOG(const auto& x)
{
std::cout << x << '\n';
}
// use as:
LOG(x);
... |
66,192,174 | 66,193,336 | Combine Dynamically Linked Libraries into one Statically Linked Library | What if I am creating a library which is meant to be super easy to use, but its dependencies are a real pain to install? If my library depends on a bunch of libraries, is it possible to create one library which contains all of the dependencies, so my library user doesnt need to fiddle around with installing each depend... | You have a few options:
Remove the dependencies. A lot of projects have dependencies that they do not really need.
Ship the dynamically linked libraries you depend on, with your own built executables or libraries.
Use a package manager to provide your dependencies so users don't have to build them from sources.
T... |
66,192,551 | 66,194,086 | How can I fix to avoid a memory leak? | I have created the push_back function to add a number at the end of the array.
But I think there is some causes to leak in this code below.
Could you find the causes?
void ElasticArray::push_back(int item){
if(_max_size == _size){
int* tmpArray = nullptr;
tmpArray = new int[_size * 2];
... | Your whole function is coded all wrong. It has multiple problems due to mismanagement of your variables, thus causing a memory leak, a buffer overflow, AND undefined behavior.
If _max_size is 0, then presumably _size is also 0 (otherwise you have more bugs elsewhere in your code), and you end up allocating 0 elements. ... |
66,192,558 | 66,201,665 | Should templated classes be precisely as fast as untemplated classes? | I have a non-general-purpose object that only exists to be in collections. A library I'm writing that defines the object, let's call it Collected, and two implementations of the collection, that should have advantages in different scenarios. Let's call them Collection1 and Collection2. The collection is central to h... | Templated classes only overhead is because they generate a new class. This takes compile time, and compile memory, and can result in more program code being generated. Finally, the symbol length of templates can sometimes be longer than you'd write by hand.
The last, however, is only because having a template generat... |
66,192,610 | 66,192,812 | Passing javascript string to std::string prints garbage values | I'm playing with C++ and ElectronJS. I'm trying to pass a Javascript string to c++ dll using ElectronJS and node-ffi. The rest exposed functions are working fine aside from GetString.
Javascript Code:
window.onload = function () {
try {
// Call *.dll with ffi
let ffi = require('ffi-napi');
// ... | I tried C style string which is const char* instead of C++ std::string and it worked fine.
Below is the little adjustment i have made.
Wrapper.h
EXPORT const char* GetString(const char*);
Wrapper.cpp
const char* GetString(const char* a) {
FILE* fp;
fp = fopen("a.txt", "w+");
fprintf(fp, a);
fclose(fp);
return "The... |
66,192,781 | 66,192,805 | How to use a QVector? | Let's say I have a class with the following member
QVector<bool> m_vector;
Then on the constructor I can do
m_vector.resize(SIZE);
for (int i = 0; i < SIZE; ++i)
m_vector[i] = false;
or (shorter)
m_vector = QVector(SIZE, false);
The shorter approch is shorter and shorter is better? Or the assingment operator tel... | Either approach works fine, but the second/shorter approach is preferred, since it requires less code and therefore provides fewer opportunities for getting something wrong. As for performance, the "unnecessary copy" will almost certainly be implemented as a construct-and-move rather than a copy (since QVector(SIZE, f... |
66,192,797 | 66,192,807 | How to repeat and print 2 or more for loops? | I am trying to print out values from my txt file. I created a struct so that I can easily search for the element in the txt file. So for my first for loop I searched for "CC" as the first option and then I print. It works. However when I try copy the same loop and search for something else, lets say "SN" so that I can ... | The question doesn't show the initialization of it, but from the context it seems to be an iterator on v. The first loop exhausts the iterator, and terminates when it reaches v.end(). When you start another loop, you should reinitialize it to v.begin(), e.g.:
for (it = v.begin(); it != v.end(); it++)
// Here ^
|
66,193,071 | 66,193,190 | How can I simulate binary values using a vector of booleans in C++? | I want to be able to retain the same amount of bits to my vector whilst still performing binary addition. For example.
int numOfBits = 4;
int myVecVal = 3;
vector< bool > myVec;
GetBinaryVector(&myVec,myVecVal, numOfBits);
and its output would be:
{0, 0, 1, 1}
I don't know how to make a function of GetBinaryVector th... | This seems to work (although the article I added in initial comment seem to suggest you only have byte level access):
void GetBinaryVector(vector<bool> *v, int val, int bits) {
v->resize(bits);
for(int i = 0; i < bits; i++) {
(*v)[bits - 1 - i] = (val >> i) & 0x1;
}
}
The left hand side sets the i'... |
66,193,094 | 66,194,051 | Read a file that's constantly updated (C++) | Let me start with saying that I'm around 3 days old in C++.
Ok to the main question, I have a file that spans multiple lines, and I'm trying to print one specific line repeatedly, which is subject to change arbitrarily by some other process.
Example file :
line0
line1
somevar: someval
line3
line4
I'm trying to print t... |
The file I'm trying to read is some /proc/1234/io
That is the most important information.
Files in proc(5) are small pseudo-files (a bit like pipe(7)-s) which can only be read in sequence.
That pseudo file is not updated, but entirely regenerated (by the Linux kernel whose source code you can study) at every open(2)
... |
66,193,114 | 66,193,363 | Problem outputing ANSI escape code from a file (C++) | I am working on a toy project. Basically, it's a set of classes and functions for making games that run in terminal. I want to use ANSI escape codes to change text color, style, background color and etc. I am trying to input shapes and colors from text files. I'm storing them in a class, which contains an array of stri... | The problem is your interpretation of escape sequences. If you write \033 in a string literal then that will be interpreted as the escape character (ASCII 27). So
std::string seq = "\033[1;31;41m";
is a string of ten characters because the compiler interprets \033 as a single character.
But if you put the same token i... |
66,193,195 | 66,193,261 | Do volatile and mutex ensure memory ordering in C++? | Suppose I have two variables:
volatile int a = 0;
int b = 0;
they are shared between two threads. Now in first thread I modify these variables in next order:
a = 1;
b = 2;
in second thread I do:
while (true) {
if (b == 2)
assert(a == 1);
}
Is there a guarantee that second thread never fails? Meaning that... |
Is there a guarantee that second thread never fails? Meaning that
second thread reads-out written values of a and b in same order that
they were written by first thread?
No, there is no guarantee of anything at all, in fact. Unsynchronized writing of (non-atomic) variables from one thread and reading them from anoth... |
66,193,344 | 66,193,821 | I cannot delete an item in a QList <QByteArray*> | I am trying to delete (free memory) of all QByteArrays in QList of pointers to the QByteArrays. Here's my code:
in my .h file
QList<QByteArray*> GroupWord; //declare the QList
in my .cpp file
quint8 k = GroupWord.length(); //get the las... | GroupWord.at(k - 1)->~QByteArray(); destroys the object but doesn't deallocate memory of its dynamic storage. You never removed the pointer from QList. Storing objects themselves instead of pointers would.. actually QList would store pointers and begins to manage the objects if they are QObject (QList is too clever for... |
66,194,025 | 66,197,041 | Blank output screen when I run this searching algorithm | I have been practicing median search algorithm, and this is what I wrote-
#include <iostream>
#include <stdlib.h>
using namespace std;
int S1[10] = { 0 };
int S2[1] = { 0 };
int S3[10] = { 0 };
int mediansearch(int A[], int k, int size)
{
int ran = rand() % size;
int i = 0;
int a = 0;
int b = 0;
... | There are a few issues with this code, the first one being the naming of variables.
I suggest you choose more significative names in the future, because good naming is fundamental when someone else has to understand your code and your ideas.
Another thing is that the arguments of are in a counterintuitive order because... |
66,194,027 | 66,194,149 | How to remove redundancy from and add flexibility to template parameters? | I want to use constexpr, compile time generated std::arrays for fast value-lookup instead of lengthy runtime calculations. For that I drafted a templated constexprfunction that will be executed at compile time.
Please see the following example code, which allows for ultrafast access to Triangle and Fibonacci numbers an... | DataType can be deduced from passed generator, use std::declval.
std::integer_sequence can be replaced by std::index_sequence.
Size for calculation must be provided explicitly.
template <typename GEN, size_t ... Indices>
constexpr auto generateArray2Helper(GEN gen, std::index_sequence<Indices...>) {
return std::arr... |
66,194,031 | 66,194,097 | Pointer refer different values | I got a problem while solving a beginner c++ challenge in hackerrank.
https://www.hackerrank.com/challenges/variable-sized-arrays/problem
The challenge require me to create an array of int array which simply is a 2d array, but the order of input constraints is so bad that I cannot make it. Suddenly, it pops up to me an... | The scope for int arr_i[k]; is the first loop, and while it's fine to take it's address with arr[l] = &arr_i[0]; those addresses are out of scope when you dereference them in the 2nd loop.
|
66,194,322 | 66,195,572 | Issues with changing array defined in C++ from JNI | I've wrote a native method in Java that uses JNI to call C++ code.
I've got JNI working fine, but when I modify an array made in C++ with JNI it only shows the modification inside the method and not outside.
Java class:
package test;
public class JavaTest {
static {
System.loadLibrary("native");
}
... | Consider what happens in this loop:
while (true) {
updateArray(0, true);
Thread.sleep(1000);
updateArray(0, false);
}
If we mentally "unroll" it, the issue becomes obvious:
updateArray(0, true);
Thread.sleep(1000);
updateArray(0, false);
updateArray(0, tr... |
66,194,671 | 66,194,749 | error: lib.a: relocation R_X86_64_PC32 against symbol `...' can not be used when making a shared object; recompile with -fPIC | When building, linker throws this error:
Error:
error: /home/m3/repos/editor/editorlib/src/clipper/build//libclipper.a(clipper.cpp.o): relocation R_X86_64_PC32 against symbol `_ZNKSt6vectorIN10ClipperLib8PolyNodeESaIS1_EE4sizeEv' can not be used when making a shared object; recompile with -fPIC
I have built the libcl... | The error cause might be this. It got resolved by:
cmake -DCMAKE_POSITION_INDEPENDENT_CODE=ON ..
As suggested here.
|
66,196,042 | 66,221,529 | Visual Studio C++ Can't include additional directory within same solution or outside folder | So I'm learning C++ this semester and right on the first laboratory I got a problem which nor me, nor my prof could solve. Our task was really basic. Create a solution, create a project in which create a function and a header file. In the header file is the declaration of the function. Then create a new project (in sam... | I reinstalled VisualStudio and now it works prefctly. FML
|
66,196,063 | 66,202,450 | nested for loop optimisation | I have this expression
for (size_t i = 0; i < expression.size(); i++){
for (size_t j = i + 1; j < expression.size(); j++){
result += (expression.at(j) - expression.at(i));
}
result += (g - expression.at(i));
}
return result;
in the vector expression we have for example [1,2,3]. I am trying to get ... | Addition is commutative and associative so the operations can be reordered and grouped without changing the final result. (Note: not taking into account possible overflows in the intermediate calculations, which may be affected by the order and grouping of operations.)
In pseudo-code with n = expression.size() and x[k]... |
66,196,196 | 66,196,273 | why postgres written by c not c++? is c has better performance or just a history reason? | I am learning postgresql source code
But I am curious about why situations is not written in c++.
Is it a history reason(just choose a c language)
Or maybe in some situations c has better performance than c++.
The world’s most popular databases, including PostgreSQL, MySQL, Oracle Database are coded in C
| PostgreSQL has a long history. It was conceived as a successor to Ingres, which goes back to the 1970s. Although the first version of PostgreSQL was released to the public in 1996, papers about it were published as early as 1986, only a year after Stroustrup published The C++ Programming Language and the first C++ comp... |
66,196,821 | 66,483,672 | Unable to reference poco[sqlite3] using vcpkg manifest | I'm using vcpkg's manifest feature to reference the dependencies my project has. I'd like to use Poco's SQLite3 wrapper but I can't figure out how to reference it in the vcpkg.json file. When I use poco[sqlite3], vcpkg gives me an error stating that I have a mal-formatted reference in my manifest file. When I use po... | After reading the vcpkg documentation, I discovered there's a specific syntax to specify that a project requires certain features of a package.
In my case, I had to use the following syntax to specify that my project needed the SQLite3 feature of Poco:
{
"name": "poco",
"features": ["sqlite3"]
}
|
66,198,321 | 66,248,047 | After upgrading to 1.2.162.1: vkQueueWaitIdle == VK_ERROR_DEVICE_LOST | I recently upgraded my ray tracing renderer from Vulkan SDK version 1.2.148.0 to 1.2.162.1.
This was necessary because the ray tracing extension went out of beta and thus now works with non-beta
graphics drivers (am on version 461.40 for my RTX 2070 SUPER). It required me to make quite a few changes to the ray tracing ... | Turns out, the actual error can occur before the command buffer whose vkQueueWaitIdle returns the DEVICE_LOST error. I've had and continue to have a variety of errors in my acceleration structure building code. I can't easily debug it, because apparently the validation layers don't show if there's subtle mistakes in th... |
66,198,686 | 66,199,349 | C++ Vector of structs, read access violation | Edit: For loop didn't have a ending condition. Newbie mistakes.
I'm doing a school assignment for school, using MS VS, which has very specific
requirements. We're reading shape names and dimensions from a txt file, creating a struct for each shape with only the dimensions as members, and using a supporting function to ... | for (unsigned int i = 0; myBag.size(); i++)
No terminating condition
for (unsigned int i = 0; i < myBag.size(); i++)
Fixed
|
66,198,854 | 66,198,908 | Allowing User input to change function parameters C++ | I just began learning C++ this week, and I'm at a very basic learning stage.
I'm using a switch and attempting to let the user input the parameters of the function getDayOfWeek, and then call it to have it carry out the function based on the entered parameters. Any help? Below I have tried cin >> getDayofWeek() but tru... | First, you need to read the input into a variable:
int day;
cin >> day;
And now, you have a very convenient variable that you can pass to your function:
cout << getDayOfWeek(day);
|
66,198,899 | 66,199,135 | C++ std::vector with values from multiple classes | I'm using std::vector for storing my values into MyValues from my classes A and B. Inserted elements/values depends on the type of class. If it's A, inserts {x, y}, if B, inserts {x, y, z}. And I loop it, so i can try to add multiple values of it, to just test it. But when I loop A.ases 5 times and then B.bses 7 times,... | You could make your MyValues a vector of vectors, like this:
std::vector<std::vector<int>> MyValues;
Then, without changing the definitions of your A and B classes, you can insert 2- or 3-element vectors, using much the same code as you already have in your main function. You would only need to change the way you disp... |
66,199,109 | 66,199,133 | Is there any guarantee to be sure the left side of && operator is always evaluated first? | As the title says: Is there any guarantee from C++ Standard to be sure the left side of && (or and) operator always evaluated first? To be honest, I couldn't search in C++17 Standard, I don't know which section I most look for.
Sample of Problem:
I want to do something like this:
std::unordered_map<std::size_t, std::we... |
[expr.log.and]/1 ... Unlike &, && guarantees left-to-right
evaluation: the second operand is not evaluated if the first operand is false.
|
66,199,202 | 66,199,421 | Passing method of object as an argument | I have to do a TP for my school, using part of a code that I haven't written.
The prototype of the function is the following :
using Callback =
std::function< bool(std::string const& request, std::string& response) >;
TCPServer::TCPServer(Callback const& callback) :
callback_(callback) {
// signal(SIGPIPE, SIG_IG... | I'm presuming that Whole::processRequest is declared as :
bool Whole::proessRequest(string const&, string&);
So instead of this, where there's no instance of Whole being passed, just a pointer to a function with no instance of Whole associated with it:
shared_ptr<TCPServer> server = new TCPServer(&whole::processReques... |
66,200,343 | 66,200,446 | Is std::atomic<std::optional<std::chrono::time_point<std::chrono::system_clock>>> valid/safe? | According to Does std::atomic<std::string> work appropriately?, std::atomic<std::string> is not valid and may lead to undefined behaviour.
What about std::atomic<std::optional<std::chrono::time_point<std::chrono::system_clock>>>?
std::optional has the operator= but std::chrono::time_point does not, so I'm confued. How ... | It's simple to check:
static_assert(std::is_trivially_copyable_v<
std::optional<std::chrono::time_point<std::chrono::system_clock>>>);
Before gcc 8.1 (and the associated libstdc++) the assert fails so it's not safe to use. After gcc 8.1 the assert passes so it's safe.
Before clang 7 (and the asosciated libc++) the... |
66,200,444 | 66,200,482 | C++ : Error could not convert from std::vector<int>* to std::vector<std::vector<int> > | I want to use vector<int> adj[] as my parameter and vector<vector<int>> as my return function type but doing that will cause an error : This happens when returning the vector adj.
could not convert adj from std::vector<int>* to std::vector<std::vector<int> >
return adj;
How can I solve this issue ?
This is m... | As I got your are trying to convert the array of vectors to a vector of vectors.
Try to return an interval of elements of the original array.
return { adj, adj + V };
|
66,201,003 | 66,201,081 | Setting up GoogleTest to run all tests in one executable | In setting up my most recent project I am attempting to use GoogleTest. Currently I have this:
macro(add_test_l TEST_NAME)
# Create the executable and use the last arguments as source files.
add_executable(${TEST_NAME} ${ARGN})
# Link in the AMR and gtest libraries.
target_link_libraries(${TEST_NAME}
... | It is unnecessary to have an executable per each file. Build one executable for all tests and learn the gtest option --gtest_filter. You can run each test individually:
all_tests --gtest_filter=Element.Test
Or you can run all Element tests like the macro add_test_l does it:
all_tests --gtest_filter=Element.*
More inf... |
66,201,270 | 66,201,468 | Why GNU MP (gmplib) from MSYS2 unexpectadely converts ull to 32 bit integer? | I am porting my c++ code from Linux to Windows using MSYS2 (64 bit). The key library is GNU MP (gmplib). The following code gives wrong results in MSYS2/MinGW64 environment while in Ubuntu works fine. Apparantly there is an unwanted conversion from 64 bit integer to 32 bit unteger when using mpz_set_ui function.
#inclu... | The mpz_get_ui() function returns an unsigned long, NOT an unsigned long long.
On Linux/GCC, unsigned long is a 64-bit value, however the C++ standard only requires that unsigned long support values up to 4'294'967'295, which can be satisfied by a 32-bit integer. Linux allows larger values, but MSVC and MinGW on Window... |
66,201,273 | 66,201,766 | I want to use the QComboBox with an Event (Return) in QT | I have the following problem:
I'm using the QComboBox of QT to select a path by a Drop & Down.
It is working fine after I choose one of the list, the path is automatically update. But now if I want to edit the Path manually by type in a path, I get immediately a warning. So I know that this is happening cause of the ar... | You could subclass QComboBox and define a new signal in your class that's emitted only when the user types enter or when the index is changed.
To do that you must connect your new signal to QComboBox::lineEdit()'s returnPressed() or editingFinished() signals and to QComboBox::currentIndexChanged().
I chose editingFinis... |
66,201,504 | 66,217,785 | Why is WriteFile not advancing the file offset for subsequent writes in this code? | I created an overlapped WriteFile scheme, where one thread fills a ring-buffer and advances the head-pointer and calls WriteFile, and another thread watches events from OVERLAPPED writes to advance the tail pointer. The logic is behaving as expected, but the file size is not increasing, it remains the same and just ove... | Answer from @RbMm, byte-access files require the caller to set Offset/OffsetHigh in the overlapped structure, according to this: https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped
Fix looks like this:
void
FileWriter::queue_page(unsigned page, unsigned len)
{
ZeroMemory(&m_ov[pa... |
66,201,626 | 66,201,736 | How do I print a `chrono` duration with units with Howard Hinnant's date.h? | I have the following toy code:
#include "date/date.h"
#include <iostream>
using namespace std;
using namespace chrono;
int main() {
cout << microseconds(100);
};
But, it doesn't work because:
C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::chrono::milliseconds' (or there is n... | That operator<< is inside the date namespace. Since neither of the operand types are from this namespace, argument-dependent lookup won't find it.
To use it you need either using namespace date or using date::operator<<.
Another issue in your code is that microseconds can only be constructed from an integer type, not f... |
66,201,641 | 66,201,642 | Type redefinition of identical definition | If I wanted to use a type, let's say ulong (part of POSIX), but did not know whether it was defined already, is it guaranteed that redefinition with the same definition is benign? This works in GCC, but I am unsure if it is defined in the C Standard.
Example
#include <stdio.h>
#include <sys/types.h> // POSIX
/* 'ulon... | Short Answer
Yes, this is guaranteed by C11 and later, and C++98 and later.
Long answer
For C, Section 6.7.3 of the C11 Standard states:
- a typedef name may be redefined to denote the same type as it currently does,provided that type is not a variably modified type;
This means that a type may be redefin... |
66,201,729 | 66,201,749 | Correct way to implement singleton with shared pointer? | I'm attempting my first bigger C++ object and I'm running into a bit of a problem when it comes to implementing a singleton using a shared pointer.
When I try to compile the following, I Visual Studio gives me this error:
"Error C2248 'PaletteManager::PaletteManager': cannot access private
member declared in clas... | PaletteManager::instance = std::make_shared<PaletteManager>();
This results in std::make_shared attempting to new a PalletteManager object, and then construct a std::shared_ptr from it. This is what std::make_shared does, that's how it works.
This is not going to work here: that's because PalletteManager has a private... |
66,201,737 | 66,201,753 | Lambda function is giving unexpected output | I was going through lambda functions on https://shaharmike.com/cpp/lambdas-and-functions/ and found below code.
int i = 0;
auto x = [i]() mutable { cout << ++i << endl; };
x();
cout << i << endl;
auto y = x;
x();
y();
Output:
1
0
2
2
Unable to understand why last 2 statements are getting printed as 2 and 2. Even thou... | x has a copy of i. I will call it x.i.
x(); -- prints ++x.i, aka 1
cout << i; -- prints i, aka 0
auto y = x; -- copies x into y. x.i is 1, y.i is also 1.
x(); -- prints ++x.i, aka 2
y(); -- prints ++y.i, aka 2
|
66,201,805 | 66,201,855 | Recursive std::function is throwing errors | I was trying to use lambda function recursively as below.
#include <iostream>
#include <functional>
using namespace std;
int main()
{
std::function<int(int)> x = [](int y) -> int {
if(y == 0) {
return 0;
} else {
return y + x(--y);
}
};
cout << x(3) << ... | Updated
This line looks suspcious:
return y + x(--y);
You're decrementing y and evaluating it within the same expression. The rules vary between "defined" and "undefined" on statements like this. But I suspect you really want this:
return y + x(y-1);
Split your declaration of x separate from the assignment. And cap... |
66,201,988 | 66,202,174 | C++ Is there a way to initialize a class using different types for the same argument? | I have a class Obj with zero or two arguments.
No arguments
First arg is always a std::string name.
Second arg it shoud be of three different class types.
I would something like this:
class Sphere{
public:
int radius=1;
int a;
};
class Plane{
public:
int a=11;
int b=12;
int c=13;
};
class... | The C++17 solution for this is std::variant, although based on defined you probably want to wrap it in an std::optional.
class Obj{
public:
std::string name;
using Value = std::variant<Sphere, Light, Plane>;
std::optional<Value> v;
//with no arguments
Obj() = default;
//Type Sphere as ... |
66,202,144 | 66,202,226 | Lambda Expression pointer | Just started working with lambdas. I wanted to create pointer to array. I think that I searched the whole internet and every sigle tutorial and I didn't find the answer.
auto c = []() -> int* { int* b = new int[10]; b[0] = 2; b[1] = 2; return b; };
std::cout << sizeof(c()) << std::endl;
delete c();
The sizeof(c) is a... |
The sizeof(c) is always returning 4 even if arrar size is 1000.
If on your platform, the size of a pointer is 4, then the result is expected and correct.
[]() -> int* { int* b = new int[10]; b[0] = 2; b[1] = 2; return b; }
This lambda returns a int*.
So, the sizeof is actually returning the size of the int* type, no... |
66,202,417 | 66,202,917 | Creating an application such as notepad in Windows with the same memory usage | I've been playing around with GLFW, OpenGL, SDL2 and whatnot for making GUI's and games, but no matter what I do, the actual application itself uses roughly 20mb ram with nothing in the display, just a blank program. Contrary to this, and same with cmd, notepad in task manager uses litterally 0.1-0.2mb ram with the act... | Notepad's kind of heavy. I've gotten it down to about 200k.
Link against nothing but kernel32, user32, gdi32, advapi32 (if you must). Everything else can be done by hand; if you only do what you need it weighs less than loading the dlls. Implement RawEntryPoint() instead of WinMain() (don't forget to call ExitProcess()... |
66,202,704 | 66,202,743 | std::bind() throwing error when this is not passed | I am trying to understand std::bind(). I am trying to understand the code in the post https://riptutorial.com/cplusplus/example/7541/std--function-used-with-std--bind.
Code is as below.
#include <iostream>
#include <functional>
using namespace std;
class A
{
public:
std::function<void(int, const std::string&)> m_... | The this is needed because eventHandler() is not a static method. std::bind() is used specifically when you want to use non-static methods of your class.
Note that personally, I find it ugly and don't like using it. I use lambdas instead.
anObjA.m_CbFunc = [=](int i, const std::string&s) { eventHandler(i,s); };
Even t... |
66,203,012 | 66,203,072 | C++ dll injection failed | I am on a window10 environment, coding in vistual studio x64
Here is the dll injection target code
#include<stdio.h>
#include<iostream>
#include<Windows.h>
#include<string>
using namespace std;
int main()
{
string choose;
int hello = 200;
while (true) {
cout << &hello << endl;
cout << "[+] ... | You are compiling with UNICODE defined, making LPCTSR be const wchar_t*, but your injection code is not taking into account that sizeof(wchar_t)=2 bytes, it Is assuming that LPCTSR is const char* instead, where sizeof(char)=1 byte. As such, it ends up writing only 1/2 of the DLL's Unicode file path into the target proc... |
66,203,137 | 66,205,097 | OOP classes design: two numbers calculator | The problem is that write a two numbers calculator(+,-,*,/) using OOP. Based on intuition(I haven't learned design pattern yet), I wrote the code like this:
class Calculator {
public:
double calculate(double a, char op, double b) {
switch (op) {
case '+':
...
}
}
Howev... | There is no single perfect design for this. It's a tradeoff that you need to make based on what you expect to change more often and what guarantees the language provides for you. This is actually an old debate and you can find very comprehensive articles if you look up "pattern matching vs subtype polymorphism".
You ma... |
66,203,371 | 69,678,402 | fatal error: syncstream: No such file or directory | How do I install syncstream header?
gcc --version
gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
| The answer was given by Ted Lyngmo in a comment. To have a regular answer I copied it here:
You need to upgrade to at least g++ 11. Probably 11.1. Then including syncstream and compiling with g++ -std=c++20 ... works.`
|
66,203,378 | 66,203,504 | Run time error while changing the data type from int to long long int | In a codechef problem Maximise Function
My code for the problem is:
#include<iostream>
#include<math.h>
using namespace std;
void swap(long long int *x, long long int *y)
{
long long int temp = *x;
*x = *y;
*y = temp;
}
void BubbleSort(long long int n, long long int a[])
{
// long long int i, j;
for(long lo... | long long int n;
long long int a[n];
cin>>n;
You are attempting to create a variable length array of size n, where n is uninitialized. So the size of a will be some garbage value that may be too small for the input you end up putting in it, or so large that it immediately overflows the stack. Both are bad. It... |
66,203,906 | 66,204,123 | Min Heap Custom Comparator in C++ | I have a Point Class and am creating a min-heap of Point objects.
class Point
{
int x;
int y;
public:
Point(int _x, int _y)
{
x = _x;
y = _y;
}
int getX() const { return x; }
int getY() const { return y; }
};
// To compare two points
class myComparator
{
public:
int operator() (co... | See std::priority_queue:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
class priority_queue;
...
A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic inser... |
66,204,364 | 66,205,628 | Cython cdef class with C++ vector of C++ stack objects | In Cython it's really easy to create a Python extensions class of C++ vector of int
# vector_int.pyx
# distutils: language = c++
from libcpp.stack cimport stack
from libcpp.vector cimport vector
cdef class VectorInt:
cdef vector[int] v
def __cinit__(self, count):
self.v = [0] * count # <-- Works!... | Oops... just remove new.
Like, malloc, C++'s new allocates memory and returns a pointer to it. Here want actually want to reference the object directly.
cdef class VectorStackInt:
cdef vector[stack[long]] v
def __cinit__(self, count):
for i in range(count):
self.v.push_back(stack[long... |
66,204,433 | 66,204,628 | How to make template function work for char[32] and string type? | i want to design a template function, which build a shared memory with size = sizeof(T) * n
it returns template type pointer. and i pass a default value as default value.
function def looks like:
#ifndef SHMHELP_HPP_ ... | Change
if (rdflag == EmShmOpenMode::MODE_CREATE) std::fill((T*)ret, ((T*)ret) + n, v);
to
if (rdflag == EmShmOpenMode::MODE_CREATE) std::uninitialized_fill((T*)ret, ((T*)ret) + n, v);
That should help with the std::string case.
std::fill can only be used on memory that already contains objects. In your case you have ... |
66,204,571 | 66,204,821 | С++ abstract return type | I have the following structure of classes:
struct A {
virtual void function() = 0;
};
struct B : A {
void function() override {
// ...implementation...
}
};
struct C {
virtual A a() = 0;
};
struct D : public C {
A a() {
return B{};
}
}
the main idea is: I do not really care what... |
You can't create objects of abstract types, you can create pointers of them. As Ayxan said, you can use also smart pointers, but I suggest you use shared_ptr because it's more comfortable.
Use dynamic_cast to convert B to A.
You forgot to add ; to the end of the third struct.
Here is the correct code:
#include <iostr... |
66,204,735 | 66,204,941 | Recursive constexpr function | I was reading Effective Modern C++ and wanted to try out a very basic function using constexpressions. My C++ skills are really not great, but I can't figure out what is wrong with this basic code:
constexpr int test( int x ) {
// works if: return x == 43337, otherwise segmentation fault
return x > 1000000 ? x+1 : ... | In your code, you are not calling test in a context that requires compile time evaluation, and so the compiler is free to evaluate the call at run-time, leading to a segfault.
You could force a compile time context for the call to test by using the result to initialize a constexpr variable:
constexpr auto result = test... |
66,204,958 | 66,205,691 | error perfect forwarding a lamda - discards qualifiers | Given this code: link
I am passing a lambda and a parameter pack and forwarding it to std::thread's constructor.
Here is a code snippet:
template<typename Functor, class... Args>
std::thread create_fifo_thread(int sch_priority, const Functor&& func, Args&&... args)
{
std::thread th(std::forward<Functor>(func), std:... | To perfect forwarding use Functor&& func - not const Functor&& func
|
66,205,034 | 66,205,143 | return x; is not returning an integer value in C++ | #include <iostream>
using namespace std;
//binary search algo
int bin_search(int n, int a[], int k){ // k is the input value, n is the size of array.
int s = 0;
int e = n - 1;
int m;
while (s <= e){ // runs while s <= e cuz if s > e, the element doesn't exist
m = (s + e) / 2;
if (a[m]... | Change this
bin_search(n, arr, k);
to something like this
cout << "element found at index " << bin_search(n, arr, k) << endl;
As churill says, returning something is not the same as printing something. If you want to print something use cout <<. If you want to return something use return. If you want both then use bo... |
66,205,064 | 66,205,297 | inconsistent treatment of class template with defaulted argument as template template class argument of smaller arity | The following snippet is rejected by Clang on C++17, accepted by GCC on C++17 and rejected by GCC on C++14. This is consistent with all recent compiler versions. What's the correct behavior ?
template <class T, class = int>
struct test1 {};
template <class T, template <class> class>
struct test2 {};
using test_t = te... | GCC's is the correct behavior. It is consistent with p0522r0, which was accepted into C++17.
From the paper's introduction:
Template template-parameters only bind to arguments with matching
parameter lists. Matching is currently defined as an exact match; each
template parameter in the argument's parameter list must h... |
66,205,207 | 66,205,437 | How to query validity of enum class used as bit mask without casting to underlying type | I have an enum class I use for bit masking, like so (in Unreal Engine, therefore the uint8 type)
enum class Level : uint8
{
None = 0x0,
Debug = 0x1,
Info = 0x2,
Warning = 0x4,
...
}
I have added inline operators for |, & and ^ such that I can use a member as the actual bitmask (e.g. mask = Level::W... | You need operator bool - but operator bool can only be defined for class type. So - define class - and put your enum within it, like this:
class Level
{
public:
enum Value : std::uint8_t
{
None = 0x0,
Debug = 0x1,
Info = 0x2,
Warning = 0x4,
Error = 0x8
};
constex... |
66,205,273 | 66,205,591 | How to statically check if two functions that might or might not have the same signature are the same function? | I want to statically check whether two functions are the same one.
Something like this:
struct Base { void f(){} };
struct Derived1: public Base { void f(){ puts("Hey!"); } };
struct Derived2: public Base { int f(){ return 0; } };
struct Derived3: public Base {};
static_assert( &Base::f != &Derived1::f );
static_asser... | You need something to reject the different signatures before trying to == them.
template <typename F1, typename F2>
constexpr bool same_function(F1, F2) { return false; }
template <typename F>
constexpr bool same_function(F f1, F f2) { return f1 == f2; }
See it live
|
66,205,441 | 66,205,954 | getline function not compiling with mingw-w64 gcc | I have a program2.c c code.
gcc program2.c gives the following error -
I tried with various options like
gcc -std=gnu90 program2.c
gcc -std=c90 program2.c
gcc -std=c99 program2.c
gcc -std=c11 program2.c
gcc -std=gnu11 program2.c
g++ program2.c
None of the above compiled the file. Error was always similar.
Is there a... | Indeed, getline was never part of the C standard library, but is a Unix/POSIX extension. To get access to it, you need to compile with gcc in POSIX ("gnu") mode under Unix, in which case the compiler drops the function inside stdio.h. And dropping non-standard functions inside standard headers is non-compliant behavior... |
66,205,524 | 66,212,837 | What kind of data structure should I provide to handle scopes in my compiler? | I am developing a "toy" compiler with flex and bisonc++ in ubuntu, which compile a C-like input language into optimized C++.
In the input language contains a main functions (must have) and can have optionals functions outside the main, for example:
int myFunc1()
{
// some functionality
}
int main()
{
}
void myFunf... | The simplest implementation of a scoped symbol table is a searchable stack capable of storing both symbols and scope markers. The operations are simple:
Enter scope: Push a scope marker.
Declare a variable: Push the declaration, after verifying that the declared variable is not already locally declared.
Exit scope: Po... |
66,205,710 | 66,205,920 | C++ use std::fill for class with deleted assign operator | Suppose I have a range of objects
class X {
public:
X()
: X(0) {
}
X(size_t num)
: x_(num) {
}
X(const X& other) = delete;
X& operator=(const X& other) = delete;
X(X&& other) {
x_ = exchange(other.x_, 0);
}
X& operator=(X&& other) {
x_ = exchange(other... | Source object of std::fill is const. const object cannot be used as source of move operation.
You can add helper class with conversion operator to X, every time when *first = value; (look at possible implementation of std::fill) is called, temporary of X is returned and move operation is performed:
template<size_t N>
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.