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 |
|---|---|---|---|---|
65,431,310 | 65,431,390 | Is there any way to "uninclude" a file in C++? | I have a class that is only used in one specific part of another class. It is not mentioned in any other parts of the main class. And I include the corresponding header at the top of a file.
Is there any way to "uninclude" the header after I've used it?
What I mean, is that after you "uninclude" the header with the cla... | The effect of unincluding a header half way through a code file, into which you have included the header at the file start, is supposed to be that the code in the second half acts as if the header has not been included.
This can be achieved by splitting the code file into two parts.
First part includes the header in qu... |
65,432,195 | 65,435,737 | Can I use lambda as a hashing function in boost::multi_index hash-like interface? | Is it possible to use lambda for hashing in hashed_<non>_unique interface for boost::multi_index?
See this example: https://godbolt.org/z/1voof3
I also saw this: How to use lambda function as hash function in unordered_map? where the answer says:
You need to pass lambda object to unordered_map constructor since lambda... | Starting with C++20, yes, you can: https://godbolt.org/z/fTbzPP (note f is declared as auto const hash_f, without a &).
As for @sehe's claim that multi_index_containers can't be passed instances of hash objects (or other intervening function objects) at construction time, the claim is incorrect: they can, although the ... |
65,432,713 | 65,432,735 | C++ "incomplete type is not allowed" when using stringstream | I have the following C++ code
#include <iostream>
int main()
{
std::string sText = "These are words in my string!";
std::string sWord;
std::stringstream ss(sText);
}
And it works fine on Fedora with g++. However, running it on Windows with Visual Studio (so I guess clang) gets incomplete type is not allow... | You've failed to #include <sstream>.
This is allowed to compile (any standard header can include an arbitrary number of other standard headers), but you should normally include the headers for the "stuff" you're using (and stringstream is declared in <sstream>). Once you include the header, VC++ compiles it just fine.
... |
65,433,008 | 65,433,149 | Error (std::bad_array_new_length) in a 2d array textbook example (Absolute C++, Savitch) | Here is a textbook example from Absolute C++ by Walter Savitch:
I tried a different version but got an error, so I tried typing out the code exactly:
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int main()
{
int d1, d2;
cout << "Enter dimensions (row*col): \n";
cin >> d1, d2;
Int... | Your error is likely on this line: cin >> d1, d2;
It should be cin >> d1 >> d2;
Compiling with a modicum of warning flags set, -Wall -Wextra in my case, would have revealed this to you immediately.
Here is the warning I received:
main.cpp:9:16: warning: expression result unused [-Wunused-value]
cin >> d1, d2;
... |
65,433,017 | 65,433,061 | Why is the constructor of the class called four times, and the destructor is only called twice when the program is about to end? | Why is the constructor of the class called four times, and the destructor is only called twice when the program is about to end?
I want to construct a one-way circular linked list and it's OK, but I got some problems on the destructor of the Bufferclass.
The code is as follows:
#include <iostream>
#include <string>
#in... | When you create a circular reference with shared_ptr, i.e. A contains a pointer to B and B contains a pointer to A, those object will never be destroyed. In this case two of your Buffers are pointing to each other. Try working out on paper what you are doing when you set up those pointers and you will see the circular ... |
65,433,206 | 65,433,331 | Redirection of a std::list<CString> content to a text file | I am using that code to enumerate files with specific extensions in a drive and write them out to a text file.
It outputs something like this in the text file. How can I write file address with their names instead of these garbage values.
00000281BBACF338
00000281BBACEA78
00000281BBACF108
00000281BBAD1E48
#include <Win... | You cast strfile to LPCTSTR, and write the file stream of ofstream, the character sets of the two do not match.
You can use wofstream to solve this problem:
std::wofstream file;
Or use CT2A function to convert it:
for (const auto& strFile : listFiles)
file << CT2A(strFile) << std::endl;
More reference : Convert C... |
65,433,270 | 65,433,297 | Assignment using std::make_unique<> | Can someone explain this C++ wizardy:
#include <memory>
class Base
{
public:
Base(){}
};
class SubClassA : public Base
{
public:
SubClassA(){}
};
class SubClassB : public Base
{
public:
SubClassB(){}
};
int main()
{
std::unique_ptr<Base> base;
bool condition = true;
if(condition) {... | C++ cannot infer that you want the expression to be a std::unique_ptr<Base>, so you can cast one of them and C++ can then infer the cast for the other:
base = condition ?
(std::unique_ptr<Base>) std::make_unique<SubClassA>():
std::make_unique<SubClassB>();
|
65,433,271 | 65,435,901 | When using overloading in C++, how can I put the overloading function in the lhs? | I am a new learner of C++. I want to define a class 'ap_uint'. The goal is to conveniently implement the bit-wise operation.
For example:
I define an unsigned int value inside the class 'ap_uint'.
I want to implement both read and write as below.
my_ap_uint(4, 2) = 7; // write operation, only set bits[... | You might return proxy class:
class ap_uint
{
struct Proxy
{
ap_uint* parent = nullptr;
int hi;
int lo;
Proxy& operator =(unsigned u) {
parent->set(hi, lo, u);
return *this;
}
operator unsigned int () const {
return parent->rang... |
65,433,311 | 65,434,089 | Why the numeric_limits Machine Epsilon does not satisfy the 1+e>1 condition? | If I'm not wrong the definition of the Machine Epsilon is the lowest number that satisfies the condition:
I was trying to test this making use of the std::numeric_limits<float>::epsilon() but the value does not satisty this, if you try to get the prior float number with std::nextafter:
#include <cmath>
#include <iostr... |
If I'm not wrong the definition of the Machine Epsilon is the lowest number that satisfies the condition: [1 + epsilon > 1]
Close, but you are wrong in the context of C++. (I believe your definition is correct in other, more academic contexts.) According to cppreference.com, the machine epsilon is "the difference bet... |
65,433,510 | 65,433,708 | getting an error of signed integer overflow(c++) | please help me in resolving the error in below code:
int smallestRangeII(vector<int>& A, int k) {
sort(A.begin(), A.end());
int mini = INT_MAX;
int maxi = INT_MIN;
int x, y;
int n = A.size();
for(int i=0;i<n;i++){
x = A[i]+k;
y = A[i]-k;
... | You are returning a signed integer where the value is the difference between the maximum and minimum integer values (that is possible for empty A). Even if A is not empty, there is no guarantee that A doesn't contain these extreme values. The value INT_MAX - INT_MIN is twice as large as the value the int type can repre... |
65,433,766 | 65,433,944 | Why program is terminated if neither calls std::thread::detach nor std::thread::join? | I know that if there is neither std::thread::detach nor std::thread::join is called. The thread object calls std::terminate within the destructor. I am wondering what the design choose of this? Why it calls std::terminaten within destructor. Furthermore, if it doesn't call std::terminate within the destructor, the beha... | This was the subject of much debate pre-C++11.
Your question makes a bold assumption: that detachment is obviously the correct behavior. But you never substantiate it. Indeed, there are many arguments against this idea, and the committee considered them.
I'll take this example from the paper outlining the argument agai... |
65,434,406 | 65,434,812 | std::condition_variable::wait in c++ | I am slightly confused in mutex, lock, and wait.
Here is my code:
void producer(std::mutex* m, std::condition_variable* cv,bool* signal) {
std::this_thread::sleep_for(std::chrono::seconds(1));
m->lock();
*signal = true;
m->unlock();
std::this_thread::sleep_for(std::chrono::seconds(3));
cv->n... | The problem is consumer 2 doesn't release the lock on the mutex before going to sleep:
std::unique_lock<std::mutex> lk(*m);
cv->wait(lk, [&] { return (*signal); });
printf("consumer %d passes this point!\n", index); // <-- mutex is still locked here
std::this_thread::sleep_for(std::chrono::seconds(10000));
So even... |
65,434,790 | 65,435,080 | how to achieve std:map in C++ v60? | I'm trying to implement Dictionary type operation in C++ -V60 build tools. I found map for the alternative for Dictionary generic type in C++. But while trying to implement it i'm facing issue while declaring the map variables.
#include <iterator>
#include <map>
using namespace std;
int main()
{
// insert single v... | You have to disable warning before including header files, e.g.
#pragma warning(disable: 4786)
Warning 4786 is linker warning, so you have add something like /IGNORE:4786 to list of switches in command line
|
65,435,457 | 65,435,654 | setting value doesn't work when iterating array by pointer increment | In example1, setting element is done by [] operator and getting element is done by pointer increment *(data++), and it seems to work well. In example2, on the other hand, both setting and getting element are done by pointer increment and seem not work. From this comparison, I can guess that pointer increment seems not ... | You are changing data and then using it again as if you hadn't changed it. Just declare a new variable
std::cout << "=== example 2 ===" << std::endl;
int* data = new int [6];
int* ptr = data;
for(int i=0; i<6; i++){
*(ptr++) = i;
}
ptr = data; // move ptr back to the beginning... |
65,435,720 | 65,437,087 | Does Eigen's Matrix delete dynamically-allocated data when it's lifetime is over? | Please consider the procedure in the following snippet. First dynamically create data, and then create Eigen matrix using the data. In this case, the matrix will release the memory of data when it's lifetime is over?
I guess in the Eigen::Map operation, pointer is copied and actual elements of data is not coppied. Thus... | The matrix will not release the memory of data when it's lifetime is over.
There is no any way for Eigen to guess where your pointer is located (Stack/Heap or wherever), and how it is allocated.
|
65,436,128 | 65,436,470 | How to understand address for array of pointers? | I have a simple program:
int main(){
int *p[2];
p[0] = new int;
p[1] = new int;
*p[0] = 10;
*p[1] = 12;
delete p[0];
delete p[1];
}
Compile:
g++ test.cpp -g -fno-stack-protector -o test
Using GDB to debug (break before variable destruction):
(gdb) x p
0x7fffffffdfc0: 0x5556aed0
(gdb) x &... | When an identifier of an array type appears in an expression other than sizeof, address-of (&), or initialization of a reference, it's converted to a pointer to the first array element. Therefore, p means &p[0].
For int *p[2] the type of expression &p is int* (*)[2] pointer to array of 2 pointers to int.
p+1 move to ne... |
65,436,134 | 65,436,392 | Eigen's matrix seems to preserve the memory in the different scope | The following snippets, I thought that standard output must be the same in the both scope1 and scope2. However, as the results shows there are not. And the result implies that m in the scope2 inherits some values from the ones in scope1. I think this is strange because m in scoper1 is supposed to has nothing to do with... | The documentation says:
Constructs an uninitialized matrix with rows rows and cols columns.
A program that reads uninitialized data has undefined behaviour.
|
65,436,187 | 68,632,781 | How do I read text chunks quicker with libpng? | With libpng, I’m trying to extract text chunks in a 44-megabyte PNG image (and preferably validate that the PNG data is not malformed (e. g. lacking IEND, etc.)). I could do that with png_read_png and png_get_text, but it took way too long for me, 0.47 seconds, which I’m pretty sure is because of the massive amount of ... | I had to do something similar, but where I wanted libpng to do all of the metadata chunk parsing (e.g. eXIf, gAMA, pHYs, zEXt, cHRM, etc. chunks). Some of these chunks can appear after the IDAT, which means the metadata can't be read with just png_read_info. (The only way to get to them would be to do a full decode o... |
65,436,527 | 65,441,020 | Clang MatchResult has no AST nodes bound? | I'm writing my first AST Matcher to detect pointer-to-integral conversions but the size of the BoundedNodes in the MatchResult is 0. How is this possible? Why would the AST Matcher call my callback even with an empty MatchResult? Is it possible for a piece of code to match a certain Matcher without appearing as a node ... | Found it. Apparently you have to bind your matcher to some string, otherwise the nodes it matches will not be present in the bound nodes. It makes sense if you say it like that, but I had to search way too long for it.
For anyone reading this, if you call the bind method at the end of your matcher, you can basically sp... |
65,436,780 | 65,437,809 | Using STL algorithms on unary functions | So I often want to perform some STL algorithm on a range of elements and instead of a comparison function, I would like to pass a unary function f.
For example I would like to write something like this
std::max_element(begin(range), end(range), f);
to find the maximum element in the range after applying f.
My current ... | Using c++ 20's ranges you can do:
std::ranges::max_element(range | std::views::transform(f));
|
65,437,248 | 65,437,694 | c++ when reference variable's value change? | using namespace std;
int foo1(int &n);
int foo2(int n);
int main() {
int n1, n2;
cout << foo1(n1) << n1 << foo2(n2) << endl;
}
int foo1(int &n) {
n = 3;
return 1;
}
int foo2(int n) {
return 2;
}
and I get output 1 (trash val) 2.
Why n1's value is not modified? foo1() is worked faster than cout ... | This
cout << foo1(n1)<<n1<<foo2(n2)<<2ndl;
actually resolves to
operator<<(operator<<(operator<<(operator<<(cout, foo(n1)), n1), foo2(n2)), endl);
The order of arguments evaluation is not defined by the standard. It's an implementation dependent. So here
operator<<(operator<<(cout, foo(n1)), n1)
either can be evalua... |
65,437,471 | 65,437,670 | How to resolve this issue ? showing keith error | I was writing a simple c++ program
#include <bits/stdc++.h>
#define ll long long
#define ul unsigned long long
#define ld long double
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define repi(i, a, b) for (int i = (a); i > (b); i--)
#define all(x) x.begin(), x.end()
#define ks(x) (cout << #x << ":" << (x) << '\... | This is wrong
while (s[i] == ')' && i > -1)
it should be
while (i > -1 && s[i] == ')')
If i equals -1 then in the first version s[i] gives you the error you can see. But in the second version i > -1 is evaluated first and because it's false s[i] is not evaluated and so does not cause an error.
There's an important le... |
65,437,607 | 65,438,028 | How to flip image from QCamera? | In QT Creator how we can filp the images from camera. I googled a lot but I didn't get a proper solution.
Following is my code.
mCamera = new QCamera;
mViewfinder = new QCameraViewfinder;
mLayout = new QVBoxLayout(ui->graphicsView);
mLayout->addWidget(mViewfinder);
mCamera->setViewfinder(mViewfinder);
... | QCamera::FrontFace and QCamera::BackFace are just positions of the camera. To achieve what you want, you should flip every image.
Create QCameraImageCapture and connect to its imageCaptured() signal.
auto imageCapture = new QCameraImageCapture( mCamera );
connect(imageCapture, &QCameraImageCapture::imageCaptured, [&](i... |
65,438,052 | 65,438,289 | Why does using unordered map over a vector give me a TLE? | I am solving this question on leetcode link
This is my working solution using an unordered map which gives me a TLE while using a vector of vectors passes all test cases.
They both work on the same logic then why does using an unordered map give me a TLE ?
class Solution {
public:
int longestArithSeqLength(vector<... | Top answer from Why is vector faster than unordered_map?
First thing to note is, although the average time to query an unordered_map is constant, the worst case is not O(1). As you can see here it actually rises to the order of O(N), N denoting the size of the container.
Secondly, as vector allocates sequential portion... |
65,438,132 | 65,438,346 | How to build opus.lib in windows? | I am trying to make a custom microsip project. But, it gives me the error of
LNK1104, cannot open file opus.lib
I don't have the lib, nor I can find it online. I have downloaded from https://www.opus-codec.org/downloads/, but can't make the build out of it. How am I suppose to? there are just some .exe files and html... | It doesn't look like there's a binary distribution of the Opus .lib for Windows, only pre-built encoder and decoder tools, so you'll have to build it yourself.
Get the source code, either
download a source .tar.gz or .zip from the download page and extract it somewhere
or clone the project from GitLab
In your check... |
65,438,247 | 65,438,301 | How Do I Deal With This C++ Multimap Destructor? | I am a beginner in C++ working on simple program and I ran into an issue which left me stumped... I do not understand where the memory is leaking. I understand more precisely, but I cannot write the destructor correctly. I ask for help.
Here is the class DBMAP
class DBMAP
{
private:
multimap < int, Volkov_1... | ~DBMAP()
{
for (multimap< int, Volkov_1* >::iterator it = setMAP.begin(); it != setMAP.end(); ++it)
delete it->second;
}
A multimap iterator points to a pair of values. The first of the pair is the key, the second is the value. That's the pointer you want to delete.
|
65,438,952 | 65,439,197 | problem with compiling C project in a C++ unit test | I have a struct forward declaration like below in C
I added googletest and want to test my code using
I added extern "C" in my test.cpp file but I get the error
baseCommand.h file
typedef struct Command_t Command_t;
struct Command_t{
uint8_t id;
uint8_t procId;
uint8_t priority;
char initCommand[50];
... | Here:
int32_t (*fpInit)(struct Command_t* this);
You're getting an error because this is a keyword in C++ and therefore can't be used as an identifier. You need to change the name to something else.
|
65,439,069 | 65,439,216 | How can I solve this error in c language in kali system? | I put the code in a source file and give it permission to execute then
when I run this file, the output appears in the picture what does that mean? How can I solve it?
#include <stdio.h>
//unsigned long balance;
//float deposit;
//int choice, pin, k,withdraw;
//char name[20];
int main() {
char name[20];
pr... | You can't run a .c file like it's a script. You need to compile it first:
gcc -o main main.c
./main
|
65,439,237 | 65,477,434 | Will bazel fetching as long as i configured my project? | While using TensorFlow, i first run
bazel build --config=opt //tensorflow:libtensorflow.so
And then i copy the folder of this project to another computer, and run the same command again, I saw it will fetching again, and it will waste my time.
Is there a solution to only fetching one time, even I copied to another co... | I believe that the bazel remote cache also shares fetched objects.
|
65,439,407 | 65,443,774 | How to create sink writer from buffer? | my implementation of encoder gets as input .wav file bytes and gives as output .mp3 bytes written in out file.
Like this
void co_AudioEncoderMF::start_encoding()
{
...
IMFSinkWriter * sink_writer = nullptr;
//Create sink writer
HRESULT hr = MFCreateSinkWriterFromURL(
L"D:\\buffer\\del\\out\\tes... |
Have byte stream implemented to accept the data (you are already familiar with IMFByteStream concept from your development on the source end)
Have MFCreateMP3MediaSink (this is the key API for the mentioned task) create an implementation of IMFMediaSink for MP3 stream
MFCreateSinkWriterFromMediaSink will create an IMF... |
65,439,572 | 65,440,445 | Inconsistent behavior between gcc and clang when c++20 concepts are involved | Does anybody know about inconsistency below? where gcc and clang behaving differently when c++20 concepts are involved.
Basically declared concept in gcc is able to find my custom operator== even through it is declared after the concept, but it isn't the case for plain functions( with user defined names ). Whereas the ... | Clang is correct. gcc just has issues with lookup for operators.
In both of your concepts, we are doing lookup for a name: operator== in one case and compare in the other. We first do regular unqualified lookup and then do argument-dependent lookup.
In both cases, both lookups should find nothing: there are no viable c... |
65,439,775 | 65,440,275 | Overloaded increment operator ++ inherited in derived class | I am trying to use the increment operator in a derived class. But I am not able to achieve this.
#include<iostream>
using namespace std;
class Base {
private:
int a;
public:
int x, y, z;
int Converter(int data) {
cout << "Printing z: " << z << endl;
return data *... | The meaning of the code is impossible to work out. I have no idea what you are trying to do.
But the reason for the Printing z: 0 output is clear enough. It comes from this constructor
explicit Base(int a_) : a(a_) {}
(which actually leaves z uninitialised but I guess you get 0 on your system)
That constructor is bein... |
65,439,922 | 65,442,382 | FLTK: how to put graphical object in foreground? | I have two draggable objects inside a window: the one containing the black square is in background while the one containing the red square is in the foreground.
This layout is due to the order in which they are drawn. I would like to have in the foreground the one that I am currently dragging: for example, if I drag ... | The widgets get drawn in the order in which they appear in the child() list of the parent. The trick is to ensure the widget that is dragged is the last one drawn. Change the push case as follows
case FL_PUSH:
{
offset[0] = x() - Fl::event_x(); // save where user cli... |
65,439,924 | 65,440,190 | Changed existing unordered_set element, what's the mechanism here? | I created an unordered_set on my own class A
struct A {
int v;
};
struct A_eq
{
bool operator()(A* lhs, A* rhs) const {
return lhs->v == rhs->v;
}
};
struct A_hash
{
std::size_t operator()(A* obj) const {
return std::hash<int>{}(obj->v);
}
};
int main(int , char* []) {
A* a7 =... |
[unord.req]/5 ... For any two keys k1 and k2 in the same container, calling pred(k1, k2) shall always return the same value. For any key k in a container, calling hash(k) shall always return the same value.
Your program exhibits undefined behavior by way of violating this requirement. It modifies a key in a way that ... |
65,439,976 | 65,440,247 | What does "bytes to encode the instructions" mean? | I am reading "Computer Systems: A Programmer's Perspective".
Topic: stages of compilation in C
Preprocessing phase, Compilation phase, Assembly phase and Linker phase.
In Assembly phase this line "This file (the object file) is a binary file containing 17 bytes to encode the instructions for function main."
I can't und... | Without entering in much detail, the result of the compilation is stored in object files. Then, after compiling that function main, the result are 17 bytes that are stored in the object file. It says 'encode' because the compiler is "translating" from C++ language to another, which normally is machine code. Depending o... |
65,440,602 | 65,440,656 | How to extract length/width from c++ face bounding box | I am using OpenCV c++ to compute the bounding box of a face. I am using this code:
haarClassifier.detectMultiScale(frameGray, boxes, 1.1, 6, CASCADE_SCALE_IMAGE, minFaceSize);
When I cout boxes to the terminal, I get this kind of result:
[485 x 485 from (358, 138)]
This is all the information I need, but I'm not sur... | do not convert it to string and attempt to parse it.
please look up that method on docs.opencv.org
you are given a vector of cv::Rect
use docs.opencv.org to find out how to access parts of a cv::Rect. the Rect type has numeric fields.
|
65,440,791 | 65,441,008 | C++ OpenSSL 1.0 migration to 3.0 | I'm trying to make a bot to access and do stuff with BitStamp API (https://www.bitstamp.net/api/), but I'm hitting a snag.
In the page linked, they show an example of how to authenticate with c++ (the V2 version). I'm having problems with this part for the authentication using openSSL:
HMAC_CTX ctx;
HMAC_CTX_init(&ctx)... | OK, there are several issues:
Error C4996 'HMAC_Update': Since OpenSSL 3.0
Look here: https://stackoverflow.com/a/20448142/421195
It sounds like you're using Microsoft Visual Studio C++ to compile. You might be able to eliminate the C4996 "error" with #pragma warning(disable : 4996)
"Seems like i download the 3.0 al... |
65,441,145 | 65,444,615 | How to get audio session GUID with Windows API | I'm trying to make a simple mixer app using Windows audio API. I've already figured out how to get IAudioSessionEnumerator and IAudioSessionControl which allows me to retrieve the DisplayName of each session. And now I want to get/set volumes of these sessions. From winApi docs I think I first need to use GetSimpleAudi... |
Each audio session is uniquely identified with a GUID—session instance
identifier.
You can IAudioSessionControl2::GetSessionInstanceIdentifier and retrieve a string that contains the session identifier.
Or you can query ISimpleAudioVolume interface on IAudioSessionControl interface like this:
ISimpleAudioVolume *simp... |
65,441,177 | 65,455,317 | std::wstring::find() broken in g++? | What's wrong with this program:
#include <string>
int main()
{
std::wstring s = L"12345";
s.find(L"x");
return 0;
}
If nothing is wrong, why does Valgrind complain:
$ g++ -g main.cpp
$ valgrind ./a.out
==9301== Memcheck, a memory error detector
==9301== Copyright (C) 2002-2017, and GNU GPL'd, by Julian S... | Probably a bug on valgrind side. I tested with g++ 10.2 and with valgrind 3.16, it worked without an error.
|
65,441,276 | 65,441,520 | Can a pch show warnings referencing the textual source? | I've been compiling a C++ project with a chained pre-compiled header file (.pch).
I am using the Clang compiler on a Linux platform, with a few warning flags, ex: -pedantic, -Wall.
Now, upon compiling the .pch, no warnings are shown at all, but, when compiling my main source code (.cpp), a few warnings are logged to th... | PCH doesn't mean it's compiled, it's only "precompiled" which is only a fancy name for saying "it's a dump of the current parser state".
Meaning preprocessing has been performed (includes, ifdefs and macros are gone), and the code has been cut into tokens, but no actual translation work has been performed yet.
All that... |
65,441,303 | 65,441,409 | "AddCustomer" was not declared in this scope. Where is the mistake? | My aim is to develop a database for Customer, so that I started creating a Datbase.h, Database.cpp and the classical main.cpp.
When I run i received the following error:
"AddCustomer" was not declared for this scope
In Database.cpp you find only an example.
I am convinced there is something in the class that doesn't wo... | The error is due to the reason that you have used AddCustomer() inside the case of switch statement, which the compiler is expecting to be avaialble in the global scope, hence can't find it.
Since it's a member function of the Database class, you will need to access it through an object. For eg.
int main()
{
int choice... |
65,441,305 | 65,443,867 | Correct types for matrix size and looping variables | Have I chosen the correct types for the size and looping index in the below example. There seem to be so many options and int seems to appear in most scratch examples. What is canonical/best practice/correct types to use for my simple example. I have chosen size_t as it this represents the row/column matrix size and pt... | Disclaimer: These are opinions, but they are primarily motivated by the intentions of the types mentioned.
size_t seems to be the right type to represent the number of elements in an array. After all, size_t is defined to be large enough to hold the size of any object, including any array. In fact, the return type for ... |
65,441,449 | 65,441,731 | Simplifying external functions calls | I have dozens of such functions, those are calls to some 3rd party external library. Is there any way to simplify it using some modern c++ feature? I want to avoid macros.
class Renderer;
Renderer* pointer;
void DrawSetRedColor(int r) {
using DrawSetRedColor_prototype = void(__thiscall**)(Renderer*, int);
return (... | Something like this would probably work:
template <typename R, typename... Args>
R CallThroughVtable(void* pointer, size_t offset, Args... args) {
using prototype = R (__thiscall**)(void*, Args...);
return (*(prototype)(*(DWORD*)pointer + offset))(pointer, args...);
}
void DrawSetRedColor(int r) {
CallThroughVta... |
65,441,515 | 65,441,695 | Why don't containers in C++20 have .ssize member function? | I am confused as to why STL containers in C++20 do not have a member function .ssize(), but instead only way to get a signed size(except obviously casting .size() result) is a free function.
I can not think of any "ergonomic" reason since every STL continer(exceptforward_list) contains .size() method.
note: I do not wa... | Some background is described here P1227:
... an ssize() member function should be added to all STL containers; this implied by extension that all containers should have ssize() member functions, and the amount of work to do that was strongly resisted by some in attendance.
At 2018 San Diego, the ssize() member funct... |
65,441,703 | 65,441,936 | How to not duplicate code for printing tree | I have a function that prints tree nodes from left to right.
void PrintTree()
{
...
Print(curentNode);
...
}
But now I want to add a function that prints nodes that meet some condition.
For example, print only such nodes, strings of which start with a given string. So it would look like
void PrintTreeByCondition(strin... | The C++ ways is to create an iterator for the traversal and use that for printing as well as filtering or other uses. Traversing a tree can probably be done in a bidirectional fashion which would allow plenty of algorithms to become accessible for the tree, too. In fact, the ordered associative containers (e.g., std::m... |
65,441,886 | 65,441,992 | How does std::optional delay initialization? / How is std::optional implemented? | Lately I've taken interest in initialization. One of the things I'm particularly interested in, is std::optional for its ability to initialize an instance of a type after it's been declared. I have tried reading the code inside the optional header, but the code is just too 'bombastic' for me to comprehend.
How is std::... | The "obvious" way to represent an std::optional<T> is to use an indication whether the value is set together with a union containing a T, i.e., something like this:
template <typename T>
class optional {
bool isSet = false;
union { T value; };
public:
// ...
};
By default the members in the union are not i... |
65,441,952 | 65,442,238 | How can I fix the input and index operator overloading problem? | I am trying to implement index and input operator overloading ([] and >>) in C++ language. The program should ask user to input an integer then it should print digits of this integer, but my program does not works correctly. I cannot understand where the problem is. How can I fix the problem? Thanks in advance for your... | There are a couple of errors in your code.
In your input function:
istream& operator >> (istream& inp, Integer &obj) {
inp >> obj.ptr[size-1];
return inp;
}
What actually happens, when you enter 1234, is that you're storing it entirely in obj.ptr[size - 1]. You should slice up each digit and store it in a se... |
65,442,001 | 65,442,594 | How can I determine if a string contains a character and then a number? | I'm making a command line battleship game in C++ and need to be able to determine if a string entered by the player contains a character (A - J) and then a number (1 - 14), which will represent the coordinates of the ship currently being entered. Is there a way to do this without using regular expressions (simply beca... | Try this
bool validShipCoords(char input_char, int num) {
/* Check character from A-J or a-j, and number
less or equal to 14*/
return ((input_char >= 65 && input_char <= 75)
|| (input_char >= 97 && input_char <= 107))
&& num <= 14;
}
int main()
{
string shipCoords;
cout<<"Enter ... |
65,442,009 | 67,434,963 | flickering white areas when resizing Qt window | I am observing a strange behavior when resizing QWindow. When I resize the window so that both width and height are increasing or decreasing, then the window does not flicker with white background. But when I increase width while decreasing height (or vice versa) the window flickers and temporarily fill the new are wit... | This bug has been fixed in Qt 6.1. As far as I tested it in my projects flickering of the white areas is gone.
UPDATE: This holds only for QtWidget applications. For QtQuick/QML there is still a lots of flicker as of Qt 6.3. See e.g. https://bugreports.qt.io/browse/QTBUG-103201
|
65,442,030 | 65,442,083 | How to check if a Number is decimal or not and apply here? | My code works perfectly fine if the total sum of given elements in vector a divided by 2 is an integer, but fails if its a double. So i need to check if the sum is double and if it is return false. I tried to do it but its not working.
TestCase a= [1,2,3,5] fails here
bool isPresent(vector<int>& a, vector<int>& v, co... | int sum = (double)(s/2);
This takes s and divides it (as an integer) by 2 (which truncates), then casts the definitely integer result to a double, then stores the result back into an int, which truncates again. Consider
double sum = ((double)s) / 2.0;
But you can avoid going through double at all by checking the modu... |
65,442,054 | 65,859,869 | Can't install ImGui in a GLFW project in Visual Studio (C++) | I have a GLFW project in Visual Studio and I want to add ImGui to it. I followed a tutorial to install it and I simply picked up some file and added to the project but it gives me a lot of error (+200). The main error is:
#error
"Cannot detect OpenGL loader!"
The tutorial that I followed is this:
https://www.youtube.... | Do you have any OpenGL loader library such as GLEW or GLAD? Without an OpenGL loader ImGui is not gonna work.
If you don't have any, download GLEW or GLAD.
Here is a video about how to setup
GLEW: https://www.youtube.com/watch?v=H2E3yO0J7TM
GLAD: https://www.youtube.com/watch?v=HFyHIc89z1g
|
65,442,517 | 65,442,534 | Error: expected expression & expected unqualifed-id | I'm building an application that does a thing... Ya boi's trying to implement a password feature that allows the user to create a password if they're a new user, or enter their password if they're a returning user (all data being written/read to and from a txt file named UserData.txt), and the compiler keeps returning ... | The macro definition
#define Password
means that any token Password in your code after that should be replaced with empty string.
Therefore, it is preventing you from using the identifier Password as an variable.
You should give another name to the include guard.
|
65,442,691 | 65,514,090 | NS3-How to modify pointopoint channel datarate during simulation run | I'm new to NS3 and looking at the first.cc tutorial.
https://www.nsnam.org/doxygen/first_8cc_source.html
In the tutorial two nodes are setup using a point to point link.
I'm interested in changing the datarate of the device/channel during simulation run() and analyzing the delay. E.g, i would like to modify the datarat... | I think thenewjames' comment is correct. I haven't run this script, but here is an example to get you started.
static void
DecreaseDataRate(PointToPointNetDevice *dev) {
dev->SetDeviceAttribute ("DataRate", StringValue ("3Mbps"));
}
int
main(int argv, char* arg[]) {
// setup simulation ...
PointToPointHelper point... |
65,443,018 | 65,443,201 | Add upon constructor from base class in subclass | I was messing around with c++ classes when I ran into an issue. I am trying to make a player class inherit from the Entity class and mix their constructors. The entity class has a constructor that requires you to provide the x position float and the y position float. I want the Player class to require x and y position ... | Try this
Player(float x, float y, const char* name)
: Entity(x,y)
{
Name = name;
}
|
65,443,595 | 65,443,617 | Why unique_ptr doesn't destroy object immediately when goes out-of-scope? | I have the following piece of code:
struct C
{
C() {std::cout << ">>> constructor\n"; }
~C() {std::cout << ">>> destructor\n"; }
};
void bar(std::unique_ptr<C>&& p)
{
std::cout << "bar\n";
}
int main()
{
auto instance = std::make_unique<C>();
std::cout << "after construction... | std::move doesn't actually move. It just casts it into a an rvalue reference.
Change
void bar(std::unique_ptr<C>&& p)
to
void bar(std::unique_ptr<C> p)
To actually do the move in the move constructor.
|
65,443,715 | 65,444,053 | Templated elipsis constructor C++ | I want to create a templated math vector class. But it says code editor says ambiguous constructor.
I use only header file!!
.h
template<class T>
class MathVec {
private:
std::vector<T> mathVec;
size_t dimension;
public:
MathVec(size_t dim);
MathVec(size_t dim, ...);
Math... | Modern C++ has better way to accomplish that. Create the following constructor:
MathVec( std::initializer_list<T> values )
Usage:
MathVec<int> vect( { 1, 2, 3 } );
|
65,443,730 | 65,446,816 | GetModuleFileNameExA won't work like it should when I try to link the function on runtime from psapi.dll (windows) | I'm experimenting with loading functions from dlls during run-time on windows. I tried doing a program that would print it's own modules, based on this one: https://learn.microsoft.com/en-us/windows/win32/psapi/enumerating-all-modules-for-a-process.
I need two functions to do what i want: EnumProcessModules and GetModu... | You should change this line of code
typedef DWORD (__cdecl *EnumModules)(HANDLE hprocess, HMODULE *moduleHandles, DWORD cb, LPDWORD lpcNeeded);
to this.
typedef DWORD(__stdcall* EnumModules)(HANDLE hprocess, HMODULE* moduleHandles, DWORD cb, LPDWORD lpcNeeded);
for more info you can reference this
|
65,443,904 | 65,444,034 | How do I forward the values of tuple to a member initializer? | I need to forward the values of a tuple to a member initializer:
struct Struct {
Member1 member1;
Member2 member2;
template<typename Tuple1, typename Tuple2>
Struct( Tuple1&& tuple1, Tuple2&& tuple2 )
: member1(tuple1...), member2(tuple2...)
{}
};
The code above obviously isn't valid. How can I ex... | std::make_from_tuple is indeed the right choice:
#include <tuple>
struct Member1 {
Member1(int x,float y, char z){}
Member1(const Member1& other)=delete;
Member1(Member1&& other)=delete;
};
struct Member2 {
Member2(int x,float y, char z){}
Member2(const Member2& other)=delete;
Member2(Member2... |
65,444,256 | 65,444,327 | Error C2102: '&' requires l-value, VS2019. How to fix? | I am using DirectX 11 and trying to load variables locally in scope using XMLoadFloat4. I am doing a lot of it and names are pretty long so I don't want to create bunch of local variables, however with code like this:
XMStoreFloat4(&vertices[0].normal, XMVector3Cross(
XMLoadFloat4(&(vertices[2].position - verti... |
Do you know elegant way to create reference in place like this?
The function expects pointers and you're trying to pass the address of temporaries which isn't allowed. Just store the temporary results in variables and pass the addresses to those:
auto a = vertices[2].position - vertices[0].position;
auto b = vertices... |
65,444,608 | 65,444,660 | "'MinGW/bin/gcc.exe' is not able to compile a simple test program." | I am currently learning CMake. Right now I am trying to configure CMake to build an example program to learn the basics, but I can't get past what seems like something that should be really easy. It seems that CMake does not agree with my gcc and g++ compilers. I have installed them through CodeBlocks, and they work fi... | C:\CodeBlocks\MinGW probably doesn't contain the DLL's to gcc or g++. You should add C:\CodeBlocks\MinGW\bin and/or C:\CodeBlocks\MinGW\lib to your path instead, depending on how MinGW was installed. I use MSys2 and use the provided environment for 32bit and 64bit tools. I try to get rid of the pre-packaged versions of... |
65,444,777 | 65,444,890 | File I/O vs TCP socket, which is faster for data trasnfer within same machine? | I have about 10MBs of data to send from the server program to the client program, both of which run within the same hard drive.
The server is written in C++ while the client is written in python.
I have already created an architecture where the server writes the data to temporary binary files and then sends the names o... | Assuming your software is written to use TCP efficiently, TCP will be faster, since during a TCP transfer the data will never need to go out to a hard drive and then back in again. Rather, it will stay in RAM the entire time, and RAM is much faster than either a spinning disk or a solid-state disk.
Sending the data vi... |
65,444,810 | 65,448,577 | Passing 2D array of strings to a function | I can initialize a 2D array of strings using the following:
const char * const aListOfStrings[] {"test","test1"};
However, if I want to do the same thing when calling a function, such as:
void function( char const * const aListOfStrings[] ) {}
void CallWithArrayOfStrings()
{
function( {"test", "test1"} );
}
The c... | const char * const aListOfStrings[] {"test","test1"}; is a shorthand for
const char * const aListOfStrings[2] {"test","test1"};
Size is deduced.
But arguments of signature are fixed (unless template is used), moreover you cannot pass C-array by value, so:
void function(char const * const aListOfStrings[]) is equivalent... |
65,444,812 | 65,448,581 | Is there any date-time module in c++ | Is there any date time module in c++?
I researched a bit in google and came to know about <ctime> header file but it just went above my head.
Any other thing that can do my work?
| In the C++ standard: <chrono>
C++11
Starting with C++11, the standard library contains date & time utilities, available in the <chrono> header, with constructs within the std::chrono namespace.
Among these you will find:
Clocks
Time points
Durations
A flexible mechanism for parsing date & time values from strings
the... |
65,444,814 | 65,444,849 | Why does std::set_difference not remove duplicates? | cppreference states that std::set_difference:
Copies the elements from the sorted range [first1, last1) which are not found in the sorted
range [first2, last2) to the range beginning at d_first.
With that said, I would expect the following MWE to output 2 4, because only 2 and 4 are not in the second set.
#include <a... | I'm not really sure there's a good reason it has to be defined to work that way, but it definitely is how it's defined. The standard specifically requires this behavior. Here's the wording as of N4835 (§[set.difference]/6):
Remarks: If [first1, last1) contains m elements that are equivalent to each other and [first2, ... |
65,444,888 | 65,444,921 | Is there a way to get or define typeid of a template? | I have a template class which is dependent on multiple template class, like following:
#include <vector>
#include <string>
#include <typeinfo>
#include <iostream>
template <typename _T>
struct Foo {
_T mem;
};
template <typename _T>
struct Bar {
_T mem;
};
template <template <typename> typename ... _Depend... | Templates are not types. Only types have typeids.
template<template<class...>class>struct template_tag{};
this is a template.
template_tag<_Dependencies>
this is a type.
Take the typeid of template_tag<your template>.
Aside:
Note that a program where you name a type _Dependencies is ill formed no diagnostic required... |
65,445,232 | 65,445,281 | Segfault when puting cin value into array | Here is all of my code:
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <iostream>
using namespace std;
int main(){
ifstream fin("cereal.in");
ofstream fout("cereal.out");
int n, m, f, s;
cin >> n >> m;
int c1[n];
int c2[n];
for(int i = 0; i < n; i++){
... | for(int i = n-1; i >= 0; i++){ // <------
if(fs.find(c1[i]) == fs.end()){
fs.insert(c1[i]);
}else{
if(fs.find(fm[c1[i]]) == fs.end()){
fs.insert(fm[c1[i]]);
}
}
fm[c1[i]] = c2[i];
ans.push_back(fs.size());
}
Change to i--. ... |
65,445,319 | 65,445,447 | Is there a way to access a the nth element of a struct? | I have struct of pointers where the pointers are of arbitrary type but are known at compile time.
struct ptrs
{
int* a;
const char** b;
int* c;
float* d;
};
Given they are all pointers they will all be the same length. Is there a way that I can access the nth element with type information.
I could cast... | Yes, it can be done. Some of the code is a little tricky to write, but Boost PFR has already done the heavy lifting, so you could do something like:
ptrs p;
float * f = boost::pfr::get<3>(p); // get the `float *` member
*f = 123.4f; // and write via the pointer
[Note that I've only broken this i... |
65,445,479 | 65,445,660 | Is there a way to modify the private variables of a child class using an inherited method in C++? | I have a class Child that inherits from a class Parent. They both have a private instance variable named a. The parent class has a method to change the a variable.
Parent.h
#pragma once
#include <iostream>
class Parent {
public:
Parent() {}
~Parent() {}
virtual void changeA() {
a++;
std::co... | The parent class knows nothing of any child. It can define a virtual method, and the child can override this method like that:
class Child : public Parent {
void changeA() override {
// Here the Child::a will be changed:
++a;
std::cout << "Child a: " << a << std::endl;
}
private:
in... |
65,445,481 | 65,445,516 | using size_t inside for loop throwing error "std::length_error" | I had encountered an error inside for loop, if str.size() = 1 then it's throwing error as
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create
but if str.size() is anything more than 1 then everything goes well.
Also when I changed size_t to int everything goes fine. Why... | size_t is an unsigned type, so the condition i >= 0; will always evaluate to true, and the loop never ends.
Either replace i >= 0 with i != 0 (and make sure to never enter the loop with an empty vector), or change the loop variable from size_t to a signed type like int.
|
65,445,554 | 65,445,667 | Operator overloading with function template | My job is to overload operator<< so it can print any object (e.g std::vector, std::set, std::map, std::deque, etc.)
With my basic knowledge of templates and searching the web I came out with something like this:
template <typename T>
std::ostream& operator<<(std::ostream& stream, const std::vector<T>& v){
stream <<... |
I've tried replacing const std::vector<T>& v with const T& v but it won't compile.
You can put constraints on the type to avoid conflict with overloaded operator<< provided by the library. E.g.
// works on types supporting std::begin and std::end
template <typename T>
auto operator<<(std::ostream& stream, const T& v)... |
65,445,657 | 65,445,729 | Why is the size of structure pointer **s when derefenced to '*s' and further to 's' is 8 in the below code in C? . Can anybody please explain it |
Structure
struct student
{
int rollno;
char name[10];
float marks;
};
main Function
void main()
{
struct student **s;
int n;
Total size of memory to be dynamically allocated
printf("Enter total num... | Pointer types are as big as they need to be to represent an address on the host system. On x86-64 platforms, all pointer types tend to be 64 bits, or 8 8-bit bytes, wide. The expressions s and *s both have pointer type (struct student ** and struct student *, respectively), so on your platform they’re both 8 bytes wi... |
65,445,837 | 65,445,863 | c++ is unordered_map<int, Enum> thread safe with one thread write and a second thread read, no new element insert? | I have the following senario,
class enum class Status {
Unknown, Pause, Normal, Resume
}
std::unordered_map<int, Status> status_map;
If at beginning I know all the key in status_map and initialze,
for(auto key:key_list) {
status_map[key]=Status::Unknown;
}
Then later, thread1 will change known key's status, a... | In a nutshell: no.
Imagine that your threads are executed on different cores, and each core has the map cached in it's own cache. Even worse: each core would cache part of the map. There is no guarantee that your reading thread would see consistent values that the writing thread is updating. You still need the values t... |
65,445,846 | 65,446,049 | Knight's Algorithm using Backtracking | I have written this Knight's problem algorithm using Backtracking and got the following output, however wherever I have looked up people code it differently and I don't know if this way is correct or wrong and what optimizations are needed? Could anyone guide me here as I am fairly new with backtracking algorithms.
#in... | Your code is incorrect. You never return to try another branch, as you always increment the counter. You are just traversing all the cells in a DFS order, and there is no guarantee that it would produce a valid solution (where a valid solition means a path, not a DFS order).
The ideas how you can correct the algorithm:... |
65,445,854 | 65,445,868 | what can be the cause of segsigv error in my program? | I am quite new to coding and I was trying to solve a problem in which we would be given a number of test cases (say n) and an integer (say k). So for each test case, a new integer(say a) will be given for which we have to find how many numbers (say sum) is divisible by k.
#include <iostream>
#include <cmath>
using name... | First, you provide the address of the variable when scanning with scanf:
scanf("%d", &n);
scanf("%d", &k);
scanf("%d", &a);
Also, initialise sum:
sum = 0;
Second, this is C++, so use cin and cout instead:
std::cin >> n >> k;
std::cin >> a;
std::cout << sum;
|
65,446,368 | 65,446,529 | What is ** in the following: int className(baseClassName** obj,int a) in C++ Polymorphism? | int className(baseClassName** obj,int a)
What should I send to baseClassName** to make operations?
| It means you have 2 indirections. Obj is pointer to pointer of baseClassName. As int is also passed I can assume that it may be the size of 2d array of pointers to baseClassName objects Allocated on heap.
you have to pass to this function will look like this.
int size = 5;
baseClassName** obj = new baseClassNam... |
65,446,498 | 65,446,571 | Where is the pointer pointing? | This is the defination for my class.
class RingBuffer {
private:
static const size_t buffer_size;
public:
std::shared_ptr<RingBufferLock> ring1_;
std::shared_ptr<RingBufferLock> ring2_;
RingBuffer();
};
I take a pointer out of the class object:
std::shared_ptr<RingBuffer> rings = std::make_shared... | rings.get():
This is getting raw pointer from rings which gives you RingBuffer *
rings_->ring1_.get():
I suppose you mean rings->ring1_.get(), which first dereferences rings and then get raw pointer from member ring1_. It is the same with rings.get()->ring1_.get(). The final result is a RingBufferLock *
|
65,446,992 | 65,447,032 | What is the reason for this stack smashing error in my array program? | I have an array that inserts a value and shifts elements. Although it compiles, I have some warnings. Here is my code:
#include <iostream>
void display_array(int arr[], int max_length = 10);
void insert_array(int arr[], int insert_num, int index_num, int max_length = 10);
int main() {
int arr_length = 10;
... | Your code does this
for(int i = max_length; i > index_num; i--) {
arr[i] = arr[i - 1];
}
where max_length equals 10. But your array has size 10 so the maximum valid index is 9. Change to
for(int i = max_length - 1; i > index_num; i--) {
arr[i] = arr[i - 1];
}
|
65,447,229 | 65,447,280 | Why Recursion + Memorization Gives TLE? | Okay we know that the time complexities of Iterative and memoriztaion is same. but still on leetcode it gives TLE for this. Problem : https://leetcode.com/problems/partition-equal-subset-sum/
Also Im using Call by Reference but still.
Am i doing it wrong or missing something?
Code :
public:
bool isPresent(vector<in... | You are using your memo only when dp[i][sum] == true.
In other words, you are not using the memorized information that there won't be any solution for that parameter.
You will need (at least) 3-state memo table: "true", "false", and "not yet calculated".
Here is one example using another table dpValid:
public:
bool... |
65,447,241 | 65,447,265 | How to manage certificates using OpenSSL in c++? | I need to manage certificates and containers using openssl in c++, and create stunnel.
How can I do this? I've been trying to find any examples or instructions on the internet but found nothing.
| Im not sure what you really want to do, but they show a good example on the openssl library here: Stackoverflow: openssl-in-c-socket-connection-https-client
|
65,447,262 | 65,447,300 | Question regarding the output and use of a function combined with a structure in C++ | We are given the task to create horner's rule by making three separate functions combined with a structure.
The structure looks like this:
struct Polynomial
{
long n;
double* a;
};
Next I created a function that is supposed to take in the polynomial degree and coefficient:
Polynomial createPoly()
{
Polynom... | Your function createPoly returns a Polynomial object so you could write something like:
Polynomial p = createPoly();
double result = calcPoly(1.56, &p);
Basically, the createPoly function returns an object that you can then set into a variable and use in your other functions like calcPoly or any others.
|
65,447,631 | 65,448,103 | Implementing an abstract class as a interface for other classes without vtable overhead | I want to make interface classes ForwardIterator, BiderctionalIterator and RandomAccessIterator, each one of them has some operators (all of them are pure virtual and not implemented). Now if I want to implement an iterator for a container, I just inherit from the right iterator and get the help of the compiler if I ac... | If I understand correctly, you want to be sure that some methods are implemented in the final derived classes but without using the classic way (abstract inheritance) because it's too heavy.
My first idea was simply declare and not define the methods
template <typename T>
struct ForwardIterator {
T operator++ ();
... |
65,447,813 | 65,449,623 | I'd like to understand this assert macro | In Visual Studio the assert macro is defined like this:
#define assert(expression) (void)( \
(!!(expression)) || \
(_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(... | Let's break down the code:
#define assert(expression) (void)( \
(!!(expression)) || \
(_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) \
)
T... |
65,447,886 | 65,448,890 | calling ApplicationView::GetForCurrentView() returns error in uwp app | This is how I call this. to resize window of the app
auto view = ApplicationView::GetForCurrentView();
view.SetPreferredMinSize({ 300, 200 });
Window::Current().Activate();
and the error:
Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "public: static s... |
This is how I call this. to resize window of the app
If you want to resize your app, please call TryResizeView method after setting preferred min Size.
auto view = ApplicationView::GetForCurrentView();
view->SetPreferredMinSize({ 300,200 });
view->TryResizeView({ 300,200 });
And please make sure above code run in th... |
65,447,933 | 65,448,031 | error: invalid use of void expression for an int type function | I am trying to solve a question in which we have to find all those sub sets of an array/vector which sums up to be equal to a user defined number.
I decided to solve it recursively using vectors. Here is the code -
#include <bits/stdc++.h>
using namespace std;
vector<int> v1{1,2,3};
int n = v1.size();
int sum = 4;
in... | Error in line return (subset(cur, i+1) + subset(cur.push_back(v1[i]), i+1));
cur.push_back has declaration - void push_back (const value_type& val);
It returns void.
|
65,448,071 | 65,448,140 | How can I optimize this prime test to take less time? | I'm trying to test for big prime numbers, but even with numbers that only reach to 9.999 it takes about 20 to 70 seconds to get the 2 primes I want and thats kinda really slow, so how can I optimize this test loop?(thats only the header and the loop; I can post the whole function if needed):
#include <iostream>
for (u... | Well I solved the problem inspired by MikeCATs comment(I removed iostream), so I just answer to myself to close the question now :)
Well...I can in 2 days @-@
|
65,448,279 | 65,448,312 | Problem on Array Rotation(C++)- Taking Array and number of transitions as input from user | I'm solving a problem on array rotation. We take an array and the number of transitions to take place as input from the user.
For example, Assume that the array A[]={1,2,3,4,5} and the number of transitions(d)=2.
Then, the output will be : {3,4,5,1,2} , etc.
This is the code that I've written, but I'm getting a Segment... | Firstly, in this part
//To move the elements by d positions
for(int i=0;i<(n-d);i++)
{
a[i]=a[i+2];
}
is is weird to use the fixed number 2 while the shift width d is configurable. It seems i+2 should be i+d.
Then, in C++ variable-length array (VLA) like int a[n]; and int temp[d]; are non-stand... |
65,448,452 | 65,448,533 | MPFR: undefined reference | incorrect installation? | I am trying to use mpfr library on Ubuntu 20.04.
I have installed it with:
sudo apt-get install -y libmpfr-dev libmpfr6
And I have a simple test code (copied from a tutorial somewhere):
#include <iostream>
#include <mpfr.h>
int main() {
mpfr_t s, t;
mpfr_init2(s, 2000);
mpfr_set_d(s, 22, MPFR_RNDD);
m... | The problem is in the compilation command line. The order of the arguments matters: the things that depend on others must be before the things they depend on. So if you use this command
g++ -O0 -Wall --std=c++14 -L/usr/lib -o asd asd.cpp -lmpfr -lgmp
the compilation will succeed since the libraries are after the sourc... |
65,448,873 | 65,449,170 | How to remove prime node in linked list? | can anyone help me to make function in this code to delete prime numbers in linked list
here ?
and another function in this code to return middle element in this linked list?..................................................................................................................................................... | Try this
bool isPrime(int num){
for(int i = 2; i <= num; i++){
if(i == num){
return true;
}else if(num % i == 0){
return false;
}
}return false;
}
void deletefirst()
{
if (head==NULL)
cout<<"Empty";
else
{
node *b=head;
if(isPrime(b->data)){... |
65,448,942 | 65,449,024 | Lambda inheritance using pack expansion | I am studying about lambda inheritance and I try to change the following example
under this stackoverflow link. I modified the code using template deduction guide and fold expression.
The piece of code
#include <iostream>
using namespace std;
template<class... Ts>
class FunctionSequence :Ts...
{
using Ts::operat... | using Ts::operator()...;
This "hoists" all the operator() from base classes into the class namespace.
That's apparently not what you want here. It looks like you want to perform the constituent base-class operations in sequence.
Here's how you could write that in a nifty way using the comma operator:
template<class...... |
65,449,204 | 65,450,970 | How to compile RtMidi API properly on Windows | I’m using C++ on visual studio 2019 and having issues trying to link my project to PortAudio. When I use the RtAudio header file in a project, I get the error message "MidiInDummy: This class provides no functionality." Most solutions I can find online say to add __WINDOWS_MM__ to the pre-processor definitions and link... |
I get the error message "MidiInDummy: This class provides no functionality."
This warns that no valid MIDI API was defined. The warning is issued from the constructor of the MidiInDummy class in rtMidi.cpp, which is just a placeholder without functional implementation.
add __WIN_MM__ to the pre-processor definitions... |
65,449,378 | 65,450,037 | C++ structs/classes members | I have a couple of questions regarding the nitty-gritty of c++ struct/classes.
i) In C++, can struct members with different access modifier be reordered by the compiler? As per here, compiler can reorder members with different access. If that is the case then How do we guarantee members are correctly initialized? For e... | With respect to your first question: the order of members in memory is only guaranteed without intervening access specifier. However, the order in memory does not affect the construction or destruction order.
Assuming you actually serialize the data, the memory organization clearly doesn’t matter. Of course, simply ta... |
65,449,403 | 65,449,429 | C++ Double Linked List, should I delete the nodes after dynamically allocating them? | void addEnd(T data) {
if (head == NULL) {
Node<T> *temp = new Node<T>(data);
head = temp;
tail = temp;
temp = NULL;
delete temp;
++size;
} else {
Node<T> *temp = new Node<T>(data);
tail->LinkToNext(temp);
temp->LinkToPrev(tail);
tail = temp;
tem... | You must not delete the newly created node in the addEnd function because it will be used later. The nodes should be deleted when the list is thrown away. (maybe in the destructor and/or something like clear() function).
Also note that the delete temp; in your code is meaningless (no gain, no harm) because temp is set ... |
65,449,454 | 65,450,023 | How can I handle returning an error from a getter method? | I am wondering how can I return an error from a getter method in this situation?
class A
{
private:
int a;
int b;
public:
const int& get(int i)
{
if (i == 1) return a;
else if (i == 2) return b;
// else... what to do here? I get a warning if I don't put anything.
}
};
| NOTE: You don't need to return a const int& to your member class, int is enough.
The C++ way for this is Exceptions, but i don't like them and i want suggest some other way based on some situations:
The Getter function must do some operations and then return the result; In this case we could return a std::pair<boo, Ty... |
65,450,116 | 65,450,203 | Interaction between templates and overloads | The output of the following code is TA, but I don't understand why.
#include <iostream>
#include <type_traits>
struct A {};
template<typename T>
void fun(T) {
std::cout << "T";
}
template<typename T>
void caller(T t) {
fun(A{});
fun(t);
}
void fun(A) {
std::cout << "A";
}
int main() {
caller(A{... | fun(A{}); doesn't involve any template parameter-dependent expressions, and so the lookup and overload resolution occurs at the point of definition. At that point, only fun(T) is visible; fun(A) does not participate in overload resolution.
fun(t) call depends on T, and so the resolution is delayed to the point of insta... |
65,450,386 | 65,450,785 | How to include third party tools with cmake? | I have been working on a CPP project but was using configuration on visual studio IDE. Now, I wanted to use a build system generator CMake. It is a little difficult to getting started with this.
I am trying to add cppunit third-party tool for my testing. For that, I have added include and lib file in a folder third_par... | add_subdirectory(${CPP_UNIT_DIR}) will look in the directory specificied for a CMakeLists.txt and since CppUnit has a CMakeLists.txt file (https://github.com/Ultimaker/CppUnit/blob/master/CMakeLists.txt) it will build the library specified add_library(cppunit STATIC ${Sources}) which is cppunit.
And then when you speci... |
65,450,597 | 65,450,908 | How to create a context menu for right click in QGraphicsView | I created a graphics view using the designer in Qt creator.
The hierarchy is the following:
When I do a right click in the area of my graphics view nothing happens (which is the default behavior afaik). Since I'm trying to show a drop down menu on right click but I can't get it to work I added a connect and custom slo... | Explanation:
It gets 2 impressions because the on_graphView_customContextMenuRequested slot is invoked 2 times since there are 2 connections. The first connection is the one made by using QtDesigner that uses the uic tool to generate C++ code using the .ui, this connection is automatic if the name of the slot complies... |
65,450,691 | 65,450,964 | How to use the range version of `transform()` with two ranges? | The header <algorithm> contains a version of std::transform() taking a two input sequences, an output sequence, and a binary function as parameters, e.g.:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v0{1, 2, 3};
std::vector<int> v1{4, 5, 6};
... | The way you would like to use transform, where you take an arbitrary number of input ranges is not possible directly with what's available in <algorithm> as of C++20. You can of course write such an algorithm yourself without too much effort.
The example with 2 input ranges can be implemented in C++20 like this:
std::r... |
65,450,761 | 65,450,821 | Determinism in C++ standard library | std::sort is not guaranteed to be stable.
Is it guaranteed to be deterministic though?
For example, will this code always print 1?
struct S
{
int a, b;
};
bool cmp(const S& lhs, const S& rhs)
{
return lhs.a < rhs.a;
}
int main()
{
std::vector<S> seq1 = {{1, 2}, {1, 3}};
std::vector<S> seq2 = seq1;
... | The only requirement on a range once it has been sorted with std::sort is that the the elements are ordered according to the provided predicate. So if there are multiple valid orderings that are possible, then an implementation is conforming so long as it generates any one of them.
An implementation is allowed to gener... |
65,451,147 | 65,659,448 | How to fix llvmlibc-restrict-system-libc-headers check in Clang Tidy? | I do not understand the llvmlibc-restrict-system-libc-headers check in Clang Tidy (link).
I include C libraries in C++ code like this:
#include <cstddef>
What should I change to fix this Clang Tidy check? Should it be fixed at all?
| The check enforces that the programmer uses compiler provided (libc) headers.
It's used mainly by the team that develops llvm's libc in order to avoid using system provided headers.
From the Phabricator web interface of the clang-tidy project:
This adds a new module to enforce standards specific to the llvm-libc proje... |
65,451,500 | 65,451,693 | Equivalent to `<T extends MyClass>` in C++ | In Java you can define a generic type, that should interhit from anoter, by <T extends MyClass> void myMethod(T item)
Is there an equivalent in cpp? I tried template<class T : Draw_Shape> class MyClass, but dont work.
| When reading below, please be aware that I am not a Java programmer. My knowledge of Java is almost entirely abstract, and possibly out of date. So if Java implemented reification of generics in the last version or two I don't know about it.
So Java Generics and C++ templates share some common syntax and uses, but t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.