question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
68,636,787 | 68,636,873 | slicing in 2d vector cpp | I want to create a new row in my 2d vector with the elements from index 1 to the end of the previous row. I wrote the below code but it is wrong. Can you please help me.
vector<vector<int>> res;
k=res.size();
res.push_back(res[k-1].begin()+1,res[k-1].end());
| When you use vector::push_back you append an element from value_type of the vector, and you can't push_back a range
https://www.cplusplus.com/reference/vector/vector/push_back/
You should call std::vector constructor in order to construct the new row, and push it to your vector:
res.push_back(vector(res[k-1].begin()+1,... |
68,636,881 | 68,637,082 | What is the difference between 'using' a parent class constructor and creating a new one in c++? | So recently i have been working on a basic math library in c++ and decided to make template classes and inherited, specialised classes, for example Vector.
I have had some problems with linking default constructor of parent class without having the need to make a new one.
I can see that the using keyword also allows me... | TL;DR - in your snippet, you do not need either. Your constructors are default constructors, do not use arguments and you could easily remove using declaration, as well as a explicit default constructor.
In more general case, using declaration for base constructor makes it visible in the child class (otherwise it is hi... |
68,637,076 | 68,679,272 | OPCUA C++ Monitored item doest'n callback the function | I'm quite new in the opcua's world and I'm trying to monitor a server variable with a client in C++.
I'm on the 1.2.2 version of opcua
I have a boolean variable in the server at the node (1,6070) and when I run the following code I receive the LOG :
[2021-08-03 15:27:47.442 (UTC+0200)] info/session Connection 5 | Secu... | I finally found the error !
The problem comme from the fact no means of handling asynchronous
events automatically is provided. However, some synchronous function
calls will trigger handling, but to ensure this happens a client
should periodically call UA_Client_run_iterate explicitly.
So the solution is to add UA_Cl... |
68,637,088 | 68,637,110 | Effective C++ (3rd edition) Item 4 code layout | In Scott Meyers' Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd edition), he describes in Item 4 how initialization of non-local static objects defined in different translation units crashes and gives a bunch of example codes.
However, I am confused with the code layout, what should it be?
Wh... | You need to move extern FileSystem tfs; from fileSystem.cpp to the header file fileSystem.h to be able to compile it.
If it's supposed to be possible to link it, you also need to define it in fileSystem.cpp.
fileSystem.h
extern FileSystem tfs;
fileSystem.cpp
FileSystem tfs;
|
68,637,162 | 68,640,256 | The best practice for (unordered) map keys and values modification | The map of the form map<long long, vector<long long>> is given. One has to take all keys and values modulo some integer N. Some keys can merge and corresponding values must join accordingly. For example, the map {{1,{2,6,4}}, {5,{8,4,9}}, {10,{5,1,7}}} should be equal to {{1,{2,1,4}}, {0,{0,1,2,3,4}}} after reduction m... | Since apparently values in map are unique and after applying modulo operation values contains unique items, then you should use different data structure. for example:
using Map = std::unordered_map<int, std::set<int>>;
std::set will handle uniqueness and order of items for given key.
Now the whole trick is to inspect ... |
68,637,456 | 68,637,528 | Can a class internally monitor its member function usage and arguments | Is it possible for a class to monitor when its member function is called and the arguments provided to the function, without modifying the member functions? I have a class defined and I want to have the option to toggle such functionality without modifying the functions themselves. At the end of the objects lifetime I ... | If you cannot change the original class you can instead write an adapter which does the logging for you.
Example:
#include <iostream>
#include <map>
class ProfilingSummary
{
public:
static ProfilingSummary& Instance()
{
static ProfilingSummary myInstance;
return myInstance;
}
void Log(... |
68,637,523 | 68,638,061 | Why does my array contain letters that I have not entered? | I'm having trouble with a piece of code. I'm trying to calculate a histogram inside a boolean function. I have this piece of code that I've written for another program, that I know works. The difference now is that it's inside a if and else if statement. The program takes a string from the user and stores that in an ar... | An edit has shown that the loops are reading past the end of the input string.
The first loop after the !inText.empty() check should be
for (i = 0; i < inText.length(); i++)
Alternatively, you could just write the whole thing as:
for (const char x : inText) {
if (x >= 'A' && x <= 'Z') { absolutHisto[x-'A']++; }
... |
68,637,757 | 68,662,788 | Installing C++ libraries in codeblocks | I need to run some code which involves yaml-cpp and cvode libraries in code blocks. I have tried to install the libraries and link to the compiler (I think that,s what I did) but it doesn't seem to work. I have also tried including the library in the directory and opening using:
#include "yaml-cpp/yaml.h"
But I keep g... | Step 1: you need to compile the yaml-cpp library.
After compilation, using cmake, (in the yaml-cpp/build folder) you will find the files:
libyaml-cpp.dll and libyaml-cpp.dll.a.
Step 2: Create a new project in CodeBlocks.
Step 3: From Project menu go to Build options and set C++11 language version or higher.
Step 4... |
68,638,007 | 68,638,805 | Running c++ program using micropython on esp-32 | I want to run my C++ programs using micropython which run on esp-32 board perfectly. Now I want to run it using micropython. For that I am referring to
https://github.com/stinos/micropython-wrap this wrapper.
I created foo.cpp and test.py
#include <micropython-wrap-master/functionwrapper.h>
//function we want to call ... | The repo you linked to doesn't let you "run" a C++ program from within MicroPython. You cannot just import C or C++ code into MicroPython at runtime, as you were trying to. C and C++ must be compiled using a C/C++ compiler.
The repo you referenced lets you extend MicroPython by compiling your own C++ functions and incl... |
68,638,694 | 68,638,695 | "There are no more endpoints available from the endpoint mapper." when creating or activating an IMFMediaSource | Using the Microsoft tutorial on Audio/Video Capture in Media Foundation, I try to create a media source for a video camera. Code below is directly taken from the aforementioned tutorial:
HRESULT CreateVideoCaptureDevice(IMFMediaSource **ppSource)
{
*ppSource = NULL;
UINT32 count = 0;
IMFAttributes *pConfi... | In my case, the culprit was a disabled service: Windows Camera Frame Server.
I had to enable it (Automatic startup) through the Services application and start it:
After that the error did not occurred again.
On a related note, I also had to allow applications to access the camera:
Local Group Policy: Computer Config... |
68,638,730 | 68,641,082 | C++,Copy all csv files in a dir to a new file | I Have n csv files in a directory. I need to copy all these files in new file. But header should copy only once.
One way to solve this issue was to use batch file
copy /b *.csv Combine.csv
but it copies n headers of these n files.
The other solution
I put all these files in a vector and iterate through it.
std::vect... | Depends a little bit on your operating system.
But usually dst << src.rdbuf(); is not that bad.
Complete solution would then be:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <utility>
std::vector<std::string> sourceFileName{
"20210731_000000_datastore3.csv",
"20210801_00... |
68,638,794 | 68,643,950 | how to jump to the implementation of c++ functions built by myself? | this seems like a stupid question, but it has bothered me for a long time. First of all, I build the leveldb by myself, and make install. Then, I can use #include <leveldb/db.h> etc. But, I fail to jump to the implementation of some functions. ps: I'm using vscode and the vscode-cmake extension.
For example, I can not... | My guess, when installing leveldb you'll basically end up with the leveldb's headers and the library binary.
You should instead try to integrate leveldb source directly in your project using FetchContent module.
ref: https://cmake.org/cmake/help/latest/module/FetchContent.html
|
68,639,761 | 68,639,802 | Why does this C++ program have problems linking with undefined reference error? | For some reason, I'm having a lot of trouble lately with creating classes with multiple files because an undefined reference error keeps showing up.
Here's the code:
Card.h
class Card {
char name;
public:
char getName();
void setName(char);
Card();
Card(char);
};
Card.cpp
#include "Card.h"... | Instead of g++ -o Card.o main.o you want g++ -o Card Card.o main.o
The doc says:
-o <file>
So, the -o option takes an output file. This is preventing you from linking Card.o in.
|
68,639,773 | 68,640,096 | Is it safe to assume that the compiler will remove these method calls? | I'm fleshing out how I want to setup a debugging logger for an application. I'd like to be able to include calls to the logger from within the codebase, but have these calls only be made when build contains environment variable DO_LOG (so for development purposes only, then disabled for production build). The below cod... | In your simplified example, and in specific compilers at the highest optimization levels?
Yes, it is fully eliminated. Not for the reasons you are expecting though.
std::string("these are words") simply happens to hit a common optimization in STL implementations: "short strings". If the string is shorter than ~24 bytes... |
68,639,888 | 68,640,777 | Determine the print-size of a string containing escape characters | I'm trying to make a progress bar which would resize according to the space left on screen. The progress bar consist of a title string followed by the bar and few trailing numbers:
15:23:11 [SampleElement] SampleElement.cpp:25: Finding bin index... [###########] 100% (14K it/s)
In principle this is a pretty straight f... | You can use a regular expression to search for ANSI terminal escape sequences since they have a unique pattern. Incidentally, there is a C function called isprint(x) to check for printable characters.
Combining these two, you should be able to create a function that can count printable characters in a string. (Assuming... |
68,640,041 | 68,641,372 | how to further optimize this code using Openmp multithreading | i have this code snippet I came across and I'm trying to use OpenMP to make it run faster than the original version. However, in comparison this seems to be taking about the same amount of time as the older version. Not sure why this multithreading approach is not working to optimize it. Like the timings are still the ... | The best optimization you can apply is to vectorize the code. Compilers can often auto-vectorize the code when it is sufficiently simple but this one is too complex for most compilers (including GCC and Clang) to vectorize it.
Manual code vectorization is cumbersome error-prone and often make the code (more) dependent ... |
68,640,329 | 68,646,429 | CommandLineParser does not accept arguments with minus characters inside | This is my main.cpp source code:
#include <iostream>
#include <string>
using namespace std;
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
const char* keys = {
"{@command ||}"
"{@input ||}"
"{@argument ||}"
};
int main(int argc, const char** argv) {
CommandLinePars... | You may have a look at the CommandLineParser documentation before starting.
If you just change those 3 lines with the following one, you will get the desired output:
cv::String param0 = cv::String(argv[1]);
cv::String param1 = cv::String(argv[2]);
cv::String param2 = cv::String(argv[3]);
Actually argv is an array and ... |
68,640,411 | 68,640,506 | Why does -O3 downcast/change the value of a const reference to a variable? | #include <iostream>
#include <stdint.h>
class Test {
public:
Test(const int64_t & val) : val_(val) {
std::cout << "initialized: " << val_ << std::endl;
}
void print() {std::cout << "reference val: " << val_ << std::endl;}
private:
const int64_t & val_;
};
int main() {
long long int input_val= 1628... | Problem is conversion.
int64_t is not the same thing as long long int.
So when this constructor is called: Test(const int64_t & val)
temporary value of type int64_t is created from long long int.
So result is const int64_t & val_; holds reference to temporary object which lifetime ends before Test::print is called.
Add... |
68,640,558 | 68,640,736 | Can't Input into a dynamic array with "double" data type | I'm having an issue with populating a double array, as I keep getting an error. Here is a snippet of the code I'm trying to run:
#include<iostream>
using namespace std;
int main()
{
int n;
double d;
double array_d[1000];
cout << "You have chosen to use Double as your datatype\n";
cout << "Enter the... | Try changing your for loop to use integers:
for (unsigned int index = 0u; index < n; ++index)
{
cin >> array_d[index];
}
The issue is that when d == 0.3333, array_d[0.3333] is kind of hard to address. Array cells are singular and there is no definition of a partial cell in an array.
Also, get into the habit of us... |
68,640,576 | 68,644,171 | how to debug a _mm_mul_ps function? | I've this code:
inline __m128 process(const __m128 *buffer) {
__m128 crashTest;
for (int i = 0; i < mFactor; i++) {
crashTest = _mm_mul_ps(buffer[i], _mm_set1_ps((float)(((int32_t)1) << 16)));
}
return crashTest;
}
when I call it with some "buffer", it crash the application (i.e. Segmentation ... | _mm_mul_ps is not a function. It looks like one, but it compiles into a single instruction, depending on compiler settings either mulps or vmulps. The output is well defined over complete range of inputs, does the right thing even with weird values like INF, NAN or denormals.
If that function crashes, the probable reas... |
68,640,740 | 68,640,894 | Get Clang AST from C/C++ Code with Undeclared Identifiers | I would like to generate an AST from a set of C/C++ code in which I know that there will be missing includes. Here is a sample.
int main() {
printf("Hello, World!");
}
I've tried doing this with clang -Xclang -ast-dump -fsyntax-only test.cpp. But it stops exporting the AST when it encounters printf.
With Import
#... | I could reproduce your issue with clang-10, but as of clang-11.0, the output is much more informative and spits out an UnresolvedLookupExpr node as I'd expect:
FunctionDecl 0x5641ea7ce5d8 <<source>:9:1, line:11:1> line:9:5 main 'int ()'
`-CompoundStmt 0x5641ea7ce860 <col:12, line:11:1>
`-RecoveryExpr 0x5641ea7ce8... |
68,641,262 | 68,641,399 | Is it possible to store (0,1)-matrix with single bits rather than bool? | I need to store fairly large size (1M x 1M) square matrices on a limited memory device. The matrices consist of elements only "1" and "0".
I have read that bool could save 1/0 ( or true/false) but that is also 8 bits storage.So I could have stored 8 times larger size if I could store the values in a single bit.
Instead... | This is exactly what std::vector<bool> is for.
#include <vector>
#include <string>
int main()
{
std::string each_row;
int row_val;
int N = 8;
std::vector<bool> matrix(N*N);
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
unsigned char val = matrix[row * N + col];
... |
68,641,883 | 68,642,334 | Transforming Hermite Polynomial Recursion to a solution using std::stack | Hermite polynomials are defined by the following formulas, where n>0 and x is a real number:
I have already defined a solution using recursion:
int hermitPolynomial(int n, int x){
if(n == 0){
return 1;
}
if (n == 1){
return x*2;
}
return 2*x*hermitPolynomial(n-1,x) + 2*(n-1)*hermitP... | First of all, let me notice that the recurrence formula is
H_n(x) = 2xH_{n-1}(x) - 2(n-1)H_{n-2}(x)
(notice the minus sign).
Here is a solution, together with a small test computing the first polynomials at x=1, and x=2.
#include <stack>
#include <iostream>
int hermitePolynomial(int n, int x)
{
std::stack<int> s;
... |
68,642,676 | 68,642,915 | Best approach for arithmetic and comparison of quantities with different signedness in C++ | I have code roughly equivalent, for all intents and purposes to the following:
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
auto number = 2;
auto vec = std::vector<int>{1, 2, 3, 4};
auto number_location = std::find(vec.begin(), vec.end(), number);
auto number_index = std::distance(v... | If you know for sure that the value of the (formally) signed variable will not be negative, then the safest way to avoid the warning would be to cast that to a size_t type, because unsigned types have a higher maximum value than signed types of the same size. Also, on most platforms, ptrdiff_t (the deduced type of your... |
68,642,743 | 68,643,591 | How do I "surpass" the int function of C++ | Alright so, I'm a noob first of all. I started studying code (in C++), and I want to make a random number generator. It's great and all, but as far as I've observed, the generated numbers never exceed the "int" limit of 32768, even tho my variables are all "unsigned long long" (I'm pretty sure that's how you get the la... | Even though all the numbers you use are unsigned long long, rand() will only ever return a number less than or equal to RAND_MAX which is guaranteed to be 32767 or more.
To guarantee a return value more than 32767 you're going to need some more advanced random number generation techniques. The standard library has a mo... |
68,642,784 | 68,642,804 | Why vector.size() - something can give segmentation fault? | In following code as expected for loop won't run(due to condition i<0-1) and nothing will be printed:
#include <iostream>
#include <vector>
using namespace std;
int main() {
for(int i=0; i < 0-1; i++){
cout<<"Yes"<<endl;
}
return 0;
}
But when I do the following, vector size is printed 0 as expect... | a.size() returns an unsigned integer. When you subtract 1 from unsigned 0 it underflows (look up "unsigned integer underflow" to 0xFFFFFFFF (a really big number). So your loop runs for a really long time.
In fact since all possible ints are less than 0xFFFFFFFF the compiler is smart enough to know that i<a.size()-1 wil... |
68,642,803 | 68,649,234 | Segmentation Fault/Out of Range on accessing a 2D vector array | #include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
int m, n;
cin>>m>>n;
vector <vector<char>> mine(n);
for( int i = 0; i < m; i++)
{
vector<char> row;
for( int i = 0; i < n ; i++)
{
char x;... | There are several problems with your code:
When you create your mine vector, it just contains n empty vector<char>.
You then create a row vector within each iteration of the outer for loop. But that vector is not connected at all with the mine vector. Furthermore, that row vector gets destroyed at the end of every loo... |
68,643,140 | 68,643,239 | 'auto *const' has incompatible initializer of type std::_Array_iterator<char, 48> | I am trying to compile this code with clang 11.0.1, c++14, for the PS4 platform. The some_array is std::array which is initialized as std::array<char, 48> some_array{{}};
auto* const characters = std::remove(some_array.begin(),
some_array.begin() + length, filtered_character);
and I get the fol... | The std::remove returns the forward iterator, not a pointer.
template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );
^^^^^^^^^^
In your case, it is of type
std::array<char, 48>::iterator
Therefore, you do not need to add the auto*, rather let the compiler deduce the t... |
68,643,168 | 68,643,676 | How to cout elapsed time without repeat in SFML? | Here is my code:
...
sf::Clock clock;
float time = 0.f;
while(window.isOpen())
{
time = clock.getElapsed().asSeconds();
cout << (int)time << endl;
}
...
This is the output I am getting:
0
0
0
0
1
1
1
1
As you can see from the above output, each second is getting logged multiple times, and I just want it to be di... | You are inside a while, you have a cout inside it! so it will print all the time, and convert each time(milliseconds) to seconds!
for this purpose you need to use a timer or an easier method, save the last time and +it with 1000 milliseconds and check it inside your while condition.
as a pseudo code:
int time = 0;
int ... |
68,644,202 | 68,645,922 | Unable to use std:: counting_semaphore in Visual Studio 2019 and 2022 | So I am trying to use counting_semaphore in visual studio 2019 and 2022 but all I get is " std has no member counting_semaphore".
I tried it in visual studio 2019 after adding the clang 11 in individual components but I still get the same error. Then I was like ok it doesn't support C++20. So I thought maybe that's why... | Whether you have set the c++ language standard?
Property -> General -> C++ Language Standard -> /std: c++ latest
I could build successfully in visual studio 2022 preview 17.0.0 preview 2.0.
And I could also build successfully in visual studio 2019.
|
68,644,683 | 68,644,771 | When does a variable copy be released in lambda function? | As the example below, I define 2 variables x and y. When I call the lambda function twice, it seems like it will not destroy the copy. From 11.14 — Lambda captures | Learn C++ - Learn C++, it says:
Because captured variables are members of the lambda object, their values are persisted across multiple calls to the lamb... | It stores it inside the object itself. Another way to think of your lambda is below. This is "kind of" equivalent to what the compiler is generating, and yes, I'm changing scopes around a bit and I know that, but this may be clearer to a beginner at C++.
static int y = 1; // Moved this out from main
class my_lambda{
... |
68,644,883 | 68,645,076 | is there a c++ version of int..args | In Java we have variable arguments This syntax tells the compiler that fun() can be called with zero or more arguments. As a result, here a is implicitly declared as an array of type int[].
class Test1
{
// A method that takes variable number of integer
// arguments.
static void fun(int ...a)
{
... | From C++11 and above, you can use parameter packs and store them in a std::initializer_list:
#include <iostream>
#include <initializer_list>
template <typename ...Args>
void fun(Args const&... args) {
std::initializer_list<int> arg_list { args... };
std::cout << "Number of arguments: " << arg_list.size() << st... |
68,645,067 | 68,645,112 | how to create a templated class that has a member of that same class?, initialized it's value at some point?, and avoid pointers if possible | let us say I have a templated class and inside that class
I want to have an uninitialized member of that same class,
and possibly at some point I want to initialize that member of that class,
how am I gonna do this in C++?, and as much a possible I also wanted to avoid pointer based solutions because of possible memory... | If a class contains itself as a member, then that member contains the same class as a member which contains the same class as a member which contains the same class as a member which contains the same class as a member which contains the same class as a member ... can you spot the problem?
It is simply impossible for a... |
68,645,264 | 68,645,399 | How to input number of testcases in C++? | While working with questions on hackerrank, I found questions which required to input number of test cases. Please guide me on how do I take the input.
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int m;
int n;
cin>>n>>m;
int arr[n];
for(int i=0;i<n;i++)
{
... | using a while loop
int testcase;
cin >> testcase;
while(testcase--)
or using a for loop
int testcase;
cin >> testcase;
for(int i = 0; i < testcase; i++)
The entire code would look like this :
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--){
in... |
68,646,027 | 68,646,473 | Arduino, code hangs in weird way when a function is invoked | I have the following code behaving in a weird way, when I make a method call
#include <TimerOne.h>
#include <cppQueue.h>
#include <Arduino.h>
typedef struct Diagnostic {
String entityName;
uint16_t pin;
} Diag;
// Global setup
cppQueue q(sizeof(Diag *), 10, FIFO, false);
int ctr = 0;
void setup() {
// initialize dig... | It looks like cppQueue copies objects using memcpy so it only works with trivially copyable objects, String is not trivially copyable so your code has undefined behaviour
|
68,646,333 | 68,646,757 | Is it worth storing the result of a function call in a temp variable for further reuse in this case? | std::rotate(vec.begin(), vec.begin() + index, vec.begin() + index + 1);
auto first = vec.begin();
auto toMove = first + index;
std::rotate(first, toMove, toMove + 1);
Will the second version be more efficient than the first? Can the compiler implicitly optimize the first version to avoid multiple calls to vec.begin()... | The only possible answer is "it depends". On what? On the implementation of involved iterators.
For instance, with std::vector, I got the very same generated machine code for both options. This is because vector iterators are basically just pointers to vector value types, possibly wrapped into some implementation class... |
68,646,338 | 68,648,246 | Validating std::function with variadic args against a 'kind' hierarchy | I have a system (C++14, using Visual Studio 2015 & GCC 4.9.2) where we have a number of different kinds of 'events' that can cause a callback to occur, and a hierarchy of classes which identify the kind of event and other custom properties specific to that kind of event.
There is an event manager which can take in a sp... | Require the concrete event type at registration time, and have the event provide the listener type.
class FirstEvent : public EventBase {
public:
EventKind kind() const final { return EventKind::first_kind; }
bool matches(const EventBase&) const final; // compare kind and other properties
using listener_ty... |
68,646,637 | 68,647,102 | Can we declare a vector as template in main function in c++ , if yes how? | I was practicing templates for first time, so i thought of creating a template for a vector in main function.
And it gave error (error: cannot declare '::main' to be a template). If there is any solution to it, then please tell.
Below is the code I tried:
#include <iostream>
#include<vector>
using namespace std;
templ... | What you wrote is a templated main function.
I think you wanted to do something more like this
#include <iostream>
#include<vector>
using namespace std;
template <class T>
void func();
int main() {
func<int>();
}
template <class T>
void func()
{
T val;
vector <T> vec;
for(int i=0;i<3;i++){
c... |
68,646,731 | 69,781,152 | ETW - Realtime consuming of event trace | I'm not a C++ developer so apologies for any imprecise language.
I have a ETW Kernel Logger configured (basically a tweaked version of the Microsoft examples). It writes events to a log and I can view the data from the etl file. I would like to switch LogFileMode to EVENT_TRACE_REAL_TIME_MODE and interact with the data... | Here is the minimalistic example based on MSDN:
void create_realtime_consumer(const wchar_t * session_name, EVENT_RECORD_CALLBACK * event_callback, EVENT_TRACE_BUFFER_CALLBACKW * buffer_callback)
{
EVENT_TRACE_LOGFILE trace{};
TRACE_LOGFILE_HEADER * pHeader = &trace.LogfileHeader;
TDHSTATUS status = ERROR_S... |
68,646,805 | 68,646,972 | Where is std::cin when std::cout is going to the "Output" pane of VSCode | When I do a "Run Code" command in Visual Studio Code in Windows (it's the first option when I right-click in the editor), the std::cout output goes to the "Output" pane of VSCode. But when this happens, where is std::cin? You can't type in the "Output" pane, and the code hangs at any cin lines.
Is there some other plac... | what you say is provided with two extension of VSCode.
The "Run Code" command in right click menu is likely provided by extension Code Runner
The 'settings.json' and the issue talks about the Microsoft's official C/C++ support extension C/C++
For you case, you may need to set this setting for Code Runner if you want ... |
68,646,980 | 68,647,340 | "iterator cannot be defined in the current scope" error | I am a novice C++ programmer working through a simple problem to print out name-and-score pairs together. Here I have used a std::unordered_set for the names and a vector for the scores (to accept duplicate scores, but not names) and that works fine.
But one thing puzzles me about the result, and that's that if I try t... | In C++ for-loop
for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) )
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
init-statement
either an expression statement (which may be a null statement ";")
a simple declaration, typically a declaration of a loop counter variable... |
68,647,258 | 68,681,348 | how override std::unorderedmap<T,T>::hash_function to my own hash function | I want to override std::unordered_map::hash_function to my own hash function,which ways are possible to do it
| As I understand you want to use the hash function to override the default hash function of the std::unordered_map. Or if there is no standard hash function available for the type of keys you want to use, then you have to implement your own hash function.
So first you need to write your own hash function and append it i... |
68,647,487 | 68,647,638 | How to avoid code duplication with function overloading | I have a pair of overloaded functions:
void func(const std::string& str, int a, char ch, double d) {
// piece of code A
sendMsg(str, a, ch, d);
// piece of code B
}
void func(int a, char ch, double d) {
// piece of code A
sendMsg(a, ch, d);
// piece of code B
}
piece of code A and piece of cod... | template may be a possibility:
template <typename ... Ts>
auto func(const Ts&... args)
-> decltype(sendMsg(args...), void()) // SFINAE to only allow correct arguments
{
// piece of code A
sendMsg(args...);
// piece of code B
}
but moving // piece of code A in its own function would probably be my choice.
|
68,648,171 | 68,648,386 | How to generate random binary numbers 0 or 1 with length of N and with option to control the probability of having 0 or 1? | I want to generate random binary numbers (0 or 1) having N length size. The tricky part is that, It should be able to control the probability of having either more 1 or 0. For example, I want total 100 random numbers with 0 having probability of 40% and 1 having probability of 60%. Please help.
| A general solution for controlling this distribution is as follows:
First generate a uniform random number between 0-100 (or 0-1000 for more control, i.e if you need 60.1% chance for a number)
Then if the number is below or equal to 60, assign 1, now you have a 60% chance to assign 1.
I hope this helps, I think you wil... |
68,648,392 | 68,648,574 | register keyword in inline function included from C | I am currently working on a mixed C and C++ project. Lately it happened that external library I have no control over added an inline function containing register keyword to header. For simplicity let's assume header looks like this:
// external_header.h
inline int do_stuff() {
register int res = 1;
return res;
}
/... | Using compiler options, you can disable the -Werror flag for this warning only:
-Werror -Wno-error=register
Or you can disable this warning altogether:
-Wno-register
Or within the code you could use preprocessor macro to remove this keyword. Note that replacing keywords (even unused ones like register) is Undefined B... |
68,648,858 | 68,649,149 | Forward declaring class, but Visual Studio ignoring it | //Code for a simple game I am making
#include <iostream>
#include <stdlib.h>
#include <Windows.h>
#include <conio.h>
#include <algorithm>
#include <string>
using namespace std;
class Enemy;
class Player{
public:
int health=10;
int damage=(rand() % 5);
void attack(Enemy enemy, string log){
... | Forward declaration is used to break dependency cycle.
But declaration is not enough when you need definition, so you might need to move some stuff after both classes are defined.
In your case, it would be something like:
class Enemy;
class Player
{
public:
int health = 10;
int damage = (rand() % 5);
void a... |
68,649,072 | 68,667,685 | How to link ImageMagic static libraries successfully? | I compiled source code so I can use build files to my program as a third party resources.
When I link IM with its dynamic libraries it makes sense, however, when it comes to static libraries, linking error happens:
here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(image_magic_compare)
set(CMAKE_... | I makes it work by using following CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(image_magic_compare)
set(CMAKE_AUTOGEN_VERBOSE on)
set(CMAKE_CXX_STANDARD 14)
set(ImageMagickLib
Magick++-7.Q16HDRI
MagickWand-7.Q16HDRI
MagickCore-7.Q16HDRI
jbig
lcms2
tiff
... |
68,649,266 | 68,657,164 | atomic inside a single construct | In an openMP framework, suppose I have a series of tasks that should be done by a single task. Each task is different, so I cannot fit into a #pragma omp for construct. Inside the single construct, each task updates a variable shared by all tasks. How can I protect the update of such a variable?
A simplified example:
#... | There is no data race in your original code, because x,y, and z are different vectors in struct A (as already emphasized by @463035818_is_not_a_number), so in this respect you do not have to change anything in your code.
However, a #pragma omp parallel directive is missing in your code, so at the moment it is a serial ... |
68,649,274 | 68,653,403 | C++ QT Call C++ function in QJSEngine | I'm trying to call a function which is implemented in C++ to call in a JS function, which gets evaluated with the QT QJSEngine.
So far I have tried this
class Person : public QObject {
Q_OBJECT
public:
Q_INVOKABLE cppFunction(int a);
};
My function evuation looks like this
QJSValue formulaFunction = jsEngin... | So, after some research I got it running.
class MyObject : public QObject{
Q_OBJECT
public:
Q_INVOKABLE MyObject() {}
Q_INVOKABLE bool hasChannel(int id);
};
QJSEngine engine;
QJSValue injectedObject;
injectedObject= engine.newQMetaObject(&MyObject::staticMetaObject);
engine.globalObject().set... |
68,649,415 | 68,649,825 | Changing the address of a pointer to edit its value | recently we were trying to use pointer to void, by passing a copy of its address to an instance of a class, in order for the instance to allocate it to the same memory space as an OpenCV Mat it contains, and that is contained in a stack of memory shared by the GPU and CPU to compute it with OpenCV+CUDA.
However while d... | @463035818_is_not_a_number offered a good answer that works well.
But there might be value in fully understanding what your original code is doing.
Beggining from the start:
int a = 1, b = 2, c = 3;
int *ptr = &a;
This initializes three pieces of memory in stack memory containing the int values you gave (a,b,c) and on... |
68,649,828 | 68,650,847 | SDL2 cannot render entities from vector | Rendering individual textures was no problem at all, though after i wrapped these textures in an entity class, and put these in a vector, things just didn't work anymore (renders black screen). Anyone got a clue why?
main.cpp
#include "RenderWindow.hpp"
#include "vec.h"
#include "entity.h"
#include <SDL2/SDL.h>
#inclu... | The creation of entities requires a temporary Entity, which is destroyed afterwards. Since you did not implement a copy constructor, this leaves the new Entity with a dangling pointer to a freed object.
The quickest fix is to change the type of Entity::texture to std::shared_ptr<SDL_Texture>.
Alternatively, you can cre... |
68,649,869 | 68,650,082 | Bidirectional iterator from char * buffer with size | I can't seem to be able to find an easy simple solution, how to get bidirectional iterator from char *buffer with defined bufferSize. I don't want to copy the buffer to std::string (too expensive), I just want something like std_whatever::buffer_wrapper myWrappedBuffer(myBuffer, mySize); and then use myWrappedBuffer.be... | char *b=buffer;
This is your beginning iterator.
char *e=buffer+buffersize;
This is your ending iterator.
Plain, garden variety pointers meet all requirements of not just bi-directional, but random access iterators, and can generally be used anywhere any kind of an iterator is required, and they'll work just like one... |
68,650,948 | 68,650,997 | Why name lookup can't find std::swap when a base class has a swap function in C++? | I have a replica of what's inside my code
#include <utility>
using namespace std;
class Parent
{
public:
void swap(Parent*);
};
class A : public Parent
{
public:
void handle();
};
void A::handle()
{
long x = 1;
long y = 2;
swap(x,y);
}
int main()
{
A v;
v.handle();
... | For unqualified name lookup:
name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
So the name swap is examined in class A firstly, it's not found, then examined in class Parent, it's found, then name... |
68,651,498 | 68,652,759 | How to push_back a "unique_ptr<Base>&" to "vector<unique_ptr<Derived>>" | I need to move elements between 2 vector<unique_ptr> with some condition checkings. After moving, I will ignore the from-vector (transfer the ownership to the to-vector).
Case 1: Move from vector<unique_ptr<Derived>> fromDeriveds to vector<unique_ptr<Base>> toBases:
vector<unique_ptr<Derived>> fromDeriveds;
vector<uniq... | You can iterate on fromBase list and make your checks, if that requirement is met then you can simply release the pointer - which gives away the base pointer without calling destructor on it. Just make sure to remove such empty pointers that were released, in case you need to use fromBase vector again.
WANDBOX LINK
#in... |
68,651,793 | 68,651,826 | How to declare a c++ function that returns std::list or takes std::list as a parameter type? | I've been trying to make a function in c++ that takes a list, performs some operation on it, and returns it. but the function won't accept std::list as a valid return type or as a parameter type.
#include <iostream>
#include <list>
std::list list_function(int n, std::list progress) {
}
int main() {
/* std::list<... | std::list is a template library, so you need a template argument to use that as a type.
For example:
#include <list>
std::list<int> list_function(int n, std::list<int> progress) {
return std::list<int>();
}
int main(void) {
std::list<int> a = list_function(10, std::list<int>());
return 0;
}
If you want t... |
68,651,800 | 68,654,479 | Second overload of std::foward (example on cppreference.com) | I know that the second overload of std::forward:
template< class T >
constexpr T&& forward( std::remove_reference_t<T>&& t ) noexcept;
is used for rvalues (as stated by Howard Hinnant in his answer: How does std::forward receive the correct argument?)
There is an example of when this overload is used at cppreference.c... |
Why is the outer forward forward<decltype(forward<T>(arg).get())> even needed?
It's not. The expression already is of its own correct value category. In C++17 (when returning by value bigger types) it's even a pessimization. All it does is turn a potential prvalue into an xvalue, and inhibiting copy elision. I'm temp... |
68,651,953 | 68,652,075 | Window is not responding to XMoveResizeWindow request | I have one window manager code, which can do window Move, window resize. But when I try to do both at the same time with XMoveResizeWindow, it does not working, and no error log also coming.
My code is given below
void WindowMgrLib::MoveResizeWindow(Window window, int x, int y, int width, int height)
{
Display *dis... | XCloseDisplay
The XCloseDisplay function closes the connection to the X server for the display specified in the Display structure and destroys all windows, resource IDs (Window, Font, Pixmap, Colormap, Cursor, and GContext), or other resources that the client has created on this display, unless the close-down mode of ... |
68,651,964 | 68,757,125 | Attach virtual machime disk on gluster volume via libguestfs (Error "No operating system found") | There are 3 compute node with Debian 10. Each node is used as hypervisor based on QEMU/KVM.
Libvirt0:amd64 5.0.0-4+deb10u1
Libguestfs0:amd 1:1.40.2-2
I create Virtual Machines with disks on GlusterFS volume.
<disk type='network' device='disk'>
<driver name='qemu' type='qcow2' cache='none' io='threads' discard='un... | In this case VM disk format is qcow2.
Be default parameter GUESTFS_ADD_DRIVE_OPTS_FORMAT is "qcow", so using guestfish there arn't any errors.
In C++ code you should set GUESTFS_ADD_DRIVE_OPTS_FORMAT in appropriate value.
|
68,652,041 | 68,682,849 | Why boost::multiprecision::exp gets stuck when evaluating complex-valued integral? | I am new to Boost C++ Libraries, and naturally I have encountered many problems when using them (due to lack of knowledge and examples available :)
One of these problems comes from the following piece of code
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/math/quadrature/... | Thanks to John Maddock from Boost, it was possible to resolve the problem. Namely, John pointed out that, despite constraints imposed on the value of the exponent, the result was getting extremely small. When mpc_exp is approaching such an extremely small value, it gets slower and slower.
The reason for this to be happ... |
68,652,171 | 68,661,448 | Graphviz in cmake project build fails - header not found | I want to create an example Cmake project in C++ to see if Graphviz can be used in a big project for documentation purposes.
My project structure is whereas I cloned graphviz from github into the external directory and performed git submodule update --init --recursive
Project
|external
| graphviz
|main.cpp
|CMakeList... | I asked the same question directly in graphviz support forum and got as answer, that it's a known issue with Cmake and linked me to this thread
https://gitlab.com/graphviz/graphviz/-/issues/1477
Tl:dr
Graphviz is currently not buildable as as subdirectory in a Cmake project.
|
68,652,174 | 68,656,297 | How can I know which printer is selected | I have a program with the typical printer dialog (made with QPrintDialog from Qt5.1) where you can select the printer you want from a list. Let's say you have printerA (selected by default), printerB, printerC and printerD. I have a problem with printerD so when the user selects it I want to do something (maybe show a ... | You are probably looking for the printer name: QPrinter::printerName.
QPrinter printer;
QPrintDialog printDialog(printer);
if (printDialog.exec() == QDialog::Accepted) {
// executed after the print dialog is closed and accepted.
if (printer.printerName() == "printerD") {
// show a message or do somethin... |
68,652,237 | 68,652,658 | Use pointer to member function to determine which function to call | I have the following class:
class Karen
{
public:
Karen(void);
~Karen(void);
void complain(std::string level);
private:
void debug(void) const;
void info(void) const;
void warning(void) const;
void error(void) const;
};
The co... | Syntax to call a member function via member function pointer is
(this->*memf)();
You cannot magically turn the string into a member function pointer. Sloppy speaking, names of functions do not exist at runtime. If you want such mapping you need to provide it yourself. No way around that. What you can avoid is the "for... |
68,654,080 | 68,654,597 | Scope of shared pointer in this clippet | void RecHouse::createRec( const std::string& SourceId,
const std::string& Name,
const std::string& Location,
const std::string& Description,
const... | Yes, the shared pointer goes out of scope and the weak pointer, as expected, does not extend the lifetime. Here's one way to test this:
#include <iostream>
#include <memory>
int main() {
std::weak_ptr<int> weak_rec;
{
std::shared_ptr<int> rec = std::make_shared<int>(200);
weak_rec = rec;
}
std::cout <<... |
68,654,097 | 68,654,325 | Clang: no warning with -Wdangling-gsl and curly braces initialization, bug in clang? | Consider the following snippet:
#include <string>
#include <string_view>
int main() {
auto str = std::string{};
auto sv1 = std::string_view(str + "!"); // <- warning :)
std::string_view sv2(str + "!"); // <- warning :)
std::string_view sv3 = str + "!"; // <- warning :)
auto sv4 = std::string_v... | This is a bug in clang's diagnosis. The use of curly braces in your last two cases does not 'fix' the dangling pointer issue.
By way of 'confirmation', the Code Analysis tool (static analyser) in Visual Studio/MSVC gives the following warnings for all five svX variables:
warning C26449: gsl::span or std::string_view cr... |
68,655,114 | 68,655,201 | This is C++ code for linked list. after putting value of ch=1 it will add a node with some value but after putting one value program shuts unexpectdly | #include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
int main()
{
Node *head=NULL;
Node *temp;
Node *nodeToAdd;
int ch,val,flag=1;
while(flag){
cout<<"\n1.Add 2.Traverse 3.EXIT\n";
cin>>ch;
switch(ch){
case... | Before doing:
temp=head;
while(temp->next!=NULL){
you need to check whether head is NULL. Like
if (head == NULL)
{
// ... Do stuff to insert first element
}
else
{
// Add to end of list
temp=head;
while(temp... |
68,655,174 | 68,655,175 | C++ : rebind variable of generic type | Re-use heap memory for generic types by rebinding variables.
What I want to do:
template <typename T> //unconstrained type
//...
{
//in some complex procedural logic
T rebindable = .../*r-value*/;
//...
//some procedure dependent case:
T rebindable = .../*different r-value*/; //rebind (I am aware this does n... | Rebind using placement new
The last example using placement new does not require the associated type constraint!
The expression T t = r-value; does not call the constructor, and in the same way, the expression new (&t) T {r-value}; does not call the constructor either.
placement new bypasses the constructor with r-valu... |
68,655,247 | 68,655,898 | Where is the equivalent of std::filesystem::last_write_time() for the file's creation time? | I'm using c++17 and std::filesystem::last_write_time already, but now I also need the file creation time, and there doesn't seem to be an API for that in std::filesystem. Did I miss it? If not, how come there isn't one?
Do I have to resort to non-portable code to extract that creation timestamp? Does Boost. File system... | I don't think it exists in C++17.
Boost contains boost::filesystem::creation_time since version 1.75.0 (December 2020). If you don't want to depend on Boost and only care about some platforms, you could use their implementation for inspiration.
Note that creation time is inherently non-portable; although some filesyste... |
68,655,433 | 68,655,866 | How does epoll return the correct file descriptor | I have two UDP connections and I'm trying to add them to use epoll(). I am looking at this example:
https://programmer.ink/think/epoll-for-linux-programming.html
I've pasted the code below.
At the beginning they create an epoll event along with an array of epoll events:
struct epoll_event ev,events[20];
I'm not sure wh... |
So how does events[i].data.fd contain the socket file descriptor?
It's put in there by epoll_wait(). It fills in the events array with information about all the events that occurred.
Why do we set ev.data.fd=listenfd; if we have an array of epoll_event, which has a file descriptor data member?
ev is used to reg... |
68,656,058 | 68,658,138 | How to make a base converter from base 10 to base 9 and then to base 7 | I'm trying to make a base converter, from any base between 2 and 10. That code should make two conversion, for example: I want to convert 100 in base 9 and the result shall be conversed in base 7 the output should look like this 121 - for first conversion and 202 for second conversion.
However my code doesn't solve cor... | Few suggestions:
Don't std::reverse your array - you can simply iterate through it backwards.
Integer values are binary; don't stuff your base 9 or base 7 values into it - it makes no sense. You need to print it out? Print the elements of your array.
Don't repeat the same code twice, use another function. If you nee... |
68,656,295 | 68,656,748 | Why global arrays does not consume memory in readonly mode? | The following code declare a global array (256 MiB) and calculate sum of it's items.
This program consumes 188 KiB when runing:
#include <cstdlib>
#include <iostream>
using namespace std;
const unsigned int buffer_len = 256 * 1024 * 1024; // 256 MB
unsigned char buffer[buffer_len];
int main()
{
while(true)
{... | There's much speculation in the comments that this behavior is explained by compiler optimizations, but OP's use of g++ (i.e. without optimization) doesn't support this, and neither does the assembly output on the same architecture, which clearly shows buffer being used:
buffer:
.zero 268435456
.secti... |
68,656,627 | 68,668,476 | Vulkan proper frame synchronization | I'm trying to synchronize frames in Vulkan API, but I have some weird problems. I implemented synchronization like this:
void RenderSystem::OnUpdate(const float deltaTime)
{
uint32_t frameIndex{};
auto result = SwapChain->AcquireNextImageIndex(PresentationCompleteSemaphore.get(),
... | You have only one set of semaphores. That means access to those semaphores might be missynchronized.
Let's see the code without the distractors:
AcquireNextImageIndex( PresentationCompleteSemaphore, frameIndex );
InFlightFences[frameIndex].WaitAndReset();
QSubmit( PresentationCompleteSemaphore, RenderCompleteSemaphore,... |
68,656,983 | 68,660,091 | Autosar standard-compilant way to use regex | I need to parse URI-like string. This URI is specific to the project and corresponds to "scheme://path/to/file", where path should be a syntactically correct path to file from filesystem point of view. For this purpose std::regex was used with pattern R"(^(r[o|w])\:\/\/(((?!\$|\~|\.{2,}|\/$).)+)$)".
It works fine but c... | I feel like making the code worse for the sake of satisfying an analyser is counterproductive and most likely violates the spirit of the guidelines, so I'm intentionally ignoring ways to address the problem that would involve building the regex string in a convoluted manner, since what you did is the best way to build ... |
68,657,028 | 68,657,821 | No match to call for template member function for operator<< overload | I am trying to write an output function for a matrix class by overloading the operator<< overload. The matrix class also has an indexing function, which is created by overloading the `op.
The code is as follows:
template<typename T, unsigned int N>
T& LU_Matrix<T, N>::operator() (unsigned int i, unsigned int j)
{
r... |
What's going wrong here?
As others have pointed out in comment section, Your LU_Matrix::operator() isn't const-qualified, therefore it cannot be used with const qualified LU_Matrix objects.
In your operator<< overload, you have the above-mentioned case:
std::ostream& operator<< (std::ostream& os, const LU_Matrix<T, ... |
68,657,148 | 68,664,672 | static_cast from enum to long yields different output depending on enum members | NOTE1: I have figured the problem before asking it here but I just want a discussion about this non-intuitive behavior in my opinion
NOTE2: This happens on gcc 7.5
#include <stdio.h>
enum lulu
{
XXX=-2,//if I comment this it considers the enum as unsigned
//and the cast to long is telling a tota... | The solution, as stated in the code is to temporary convert to a signed integer variable and then make a static_cast to long.
int val2 = l2;
long lval2 = static_cast<long>(val2);
|
68,657,307 | 68,693,189 | Read Access Violation on Virtual Function | This is a simplified version of my program.
#include <iostream>
#include <vector>
class Base
{
public:
Base()
{
}
void virtual update()
{
std::cout << "no update function\n";
}
void virtual draw()
{
std::cout << "no draw function\n";
}
};
class Derived : public Bas... | Solution from Remy Lebeau:
Derived derived_class{}; reg_obj(&derived_class); is causing undefined behavior in the rest of your code. You are storing a pointer to a local object that is destroyed afterwards, leaving a dangling pointer in the all_objects vector. All of your method calls on all_objects elements are acting... |
68,657,541 | 68,657,581 | Why is public destructor necessary for mandatory RVO in C++? | Please consider the simple example as follows, where the function bar returns an object of class A with private destructor, and mandatory return value optimization (RVO) must take place:
class A { ~A() = default; };
A bar() { return {}; }
The code is accepted by Clang, but rejected by GCC with the error:
error: 'const... | This is CWG 2426. The destructor is potentially invoked within this context, because even after the initialization of the return A object, it's still possible that the function fails to complete successfully: any temporaries created during the return statement, and automatic local variables that are in scope, must be d... |
68,657,808 | 68,657,827 | "no operator >> matches these operands" | I'm a complete noob at C++, and the first problem I am encountering is the following:
no operator >> matches these operands
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "hello world!";
cin >> "hello world!";
}
| std::cin needs to write to a variable, but you are passing it a const char[13] string literal instead.
You need to pass it something like a std::string instead:
std::string str;
std::cin >> str;
P.S. This is a good time to a) read compiler messages, b) avoid using namespace std; globally, c) get a good C++ book.
|
68,657,826 | 68,668,859 | Quaternion rotation ignoring yaw | I'am working with Quaternion and one LSM6DSO32 captor gyro + accel. So I fused datas coming from my captor and after that I have a Quaternion, everything works well.
Now I'd like to detect if my Quaternion has rotated more than 90° about a initial quaternion, here is what I do, first I have q1 is my initial quaternion,... | The "yaw" of a quaternion generally means q_yaw in a quaternion formed by q_roll * q_pitch * q_yaw. So that quaternion without its yaw would be q_roll * q_pitch. If you have the pitch and roll values at hand, the easiest thing to do is just to reconstruct the quaternion while ignoring q_yaw.
However, if we are really d... |
68,658,141 | 68,658,190 | Where can I find a list to all C++ functions? | Once again I am studying C++ and hit the same wall: the reference list of functions. I could not find a complete list of functions implemented by the standard C++ headers, only websites with these functions shown one by one, separated by classes, templates etc.
I am looking for something similar to this:
https://www.ib... | The C++ Standard does contain a list of all names in the Standard Library.
I don't think you will find it particularly helpful, there are far too many to find anything by reading through the index, the organized hierarchy is much better.
But here it is anyway:
Index of library names
|
68,658,302 | 68,658,488 | How do I make catch2 not print its annoying header? | I'm running some unit tests built with catch2. Its output begins with:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test_suite is a Catch v2.13.6 host application.
Run with -? for options
well, I don't want to see that. Neither I nor other users/maintainers need to be reminded of th... | Catch2 is open-source
If you go to src/catch2/reporters/catch_reporter_console.cpp, you'll find:
void ConsoleReporter::lazyPrintRunInfo() {
stream << '\n' << lineOfChars('~') << '\n';
Colour colour(Colour::SecondaryText);
stream << currentTestRunInfo->name
<< " is a Catch v" << libraryVersion() << "... |
68,658,580 | 68,696,030 | Include dependencies in dynamic library | I am building a library in C++ that requires a few libraries to be included, some of which being GLEW, SDL2, and GLM. I am using CMake to build this library, and have successfully set up (at least to my knowledge) a CMakeLists.txt that adequately does this, but currently without dependencies. I would like to know the p... | To dynamically link GLEW, SDL2, and GLM, you can use the find_package command.
find_package(GLEW REQUIRED)
find_package(SDL2 REQUIRED)
find_package(glm REQUIRED)
Then, after you've called add_library, you will need to link the libraries to your library:
target_link_libraries(mylib PRIVATE GLEW::GLEW SDL2::SDL2 glm::gl... |
68,658,689 | 72,023,628 | How to match start and end of input with std::regex on Visual Studio | From what I understand, C++ regex symbol ^ should match only the beginning of input and $ should match only the end of input. This can be changed to match begin and end of every line with the std::regex::multiline flag.
Unfortunately Visual Studio 2017 fails to conform to this behavior:
#include <string>
#include <iost... | I got hung up on this issue as well. It turns out that this non-standard behavior is expected from Visual Studio 2017 for historical reasons, but they would like to change it in the future.
Here's a link with more info (pasted below for posterity): https://developercommunity.visualstudio.com/t/multiline-c/268592
We ma... |
68,659,040 | 68,659,287 | C++ templated function with templated class as return value | I have this Java code:
public interface Adapter<FROM,TO> {
/**
* Adapts something from one type to a type.
* @param f
* @return
*/
public TO adapt(FROM f);
/**
* Chains adapters.
*
* @param <NEXT>
* @param next
* @return a new adapter that takes the outp... | You are close.
In Java, interfaces have to be implemented by concrete classes, and interface methods are virtual and must be overriden in those classes. In the case of your example, the use of the default keyword on the chain() method allows Java to generate its own class to implement the Adapter interface that chain(... |
68,659,125 | 68,659,432 | Returning 'inf' when finite result is expected | The outputs are not what Python/Mathematica previously calculated when calling test_func(3000, 10). Instead, my code returns inf, and I am not sure why.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <chrono>
#include <cmath>
using namespace std;
//I0
double I0 (double y0, double... | double has a limited range. On most modern implementations, doubles are in the standard IEEE floating point binary64 format, with range up to about 1.8e308. Anything bigger (such as your exp(6000)) rounds up to infinity.
Switching to a larger type like long double may not be the best idea. Though the range of floating ... |
68,659,197 | 68,660,558 | Cannot convert rvalue std::array to std::span | Consider the following code.
#include <array>
#include <span>
std::array<int, 2> Foo()
{
return {1, 2};
}
int main()
{
std::array a = {3, 4};
std::span s1 = a;
// std::span s2 = Foo(); // Nope
// std::span s3 = std::move(a); // Nope
// std::span s4 = std::array<int, 2>{5, 6}; // Nope
... | TL;DR. This is just because libc++ has not yet implemented
P1394.
The problem is that in libstd++ and MSVC-STL, std::span has the following CTAD:
template<typename _Range>
span(_Range &&)
-> span<remove_reference_t<ranges::range_reference_t<_Range&>>>;
When we call std::span{std::array{0}}, the type of span... |
68,659,745 | 68,659,901 | c++ timer terminate without an active exception? | I want to design a timer in c++, to execute my function after a fixed time.
the code likes like:
#include <thread>
typedef void (*callback)();
class timer {
public:
void start(int sec, callback f) {
std::thread t([&sec, &f]() {sleep(sec); f();});
}
};
void test () {
printf("here called\n");
}
int main() ... | There are a few problems with your code that need to be addressed:
After spawning a std::thread you need to synchronize it using std::thread::join().
Remove the reference capture from the sec parameter in order to prevent dangling of references by the end of the scope of start().
sleep() is platform-dependent, so your... |
68,659,906 | 68,660,243 | How to bind all kind of function to a timer? | I have a simple timer, which i want to execute my function after a fixed time.
the code is:
#include <thread>
typedef void (*callback)();
class timer {
public:
virtual ~timer() {
t_.join();
}
void start(int sec, callback f) {
if (t_.joinable()) t_.join();
t_ = std::thread([sec, &f]() {sleep(sec... | We may use a start function with a template argument to replace the function pointer argument
#include <chrono>
#include <functional>
#include <iostream>
#include <thread>
class timer {
public:
virtual ~timer() { t_.join(); }
template <typename Fn>
void start(std::chrono::seconds sec, Fn&& f) {
t_ = std::thr... |
68,660,649 | 68,660,671 | Need I really use another template in this case | template<class Key, class Value>
class ThreadSafeMap
{
std::mutex m_;
std::map<Key, Value> c_;
public:
Value get(Key const& k) {
std::unique_lock<decltype(m_)> lock(m_);
return c_[k]; // Return a copy.
}
template<class Value2>
void set(Key const& k, Value2&& v) {
std::u... | v is supposed to be declared as forwarding reference, which only works with templates. Then we need make set itself template.
(emphasis mine)
Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward. Forwar... |
68,660,764 | 68,661,119 | 112.path sum leetcode wong answer for two test cases | problem My code fails for the following test case. I don't understand why. Can you tell me where I went wrong? My code passes (114/116) test cases. I'm doing DFS and checking whether currSum==targetSum and if it satisfies this condition and it's also a leaf node I'm setting global variable ```flag=true``.
[1,-2,-3,1,3,... | The code works fine and the logic is perfect, you forgot to put brackets to the if statement
if(root->left == NULL && root->right == NULL) {
flag=true;
return;
}
Here's the full code
class Solution {
public:
bool flag = false;
void dfs(TreeNode *root, int currSum, int ... |
68,661,484 | 68,687,596 | Why does the lesser than equal to operator show unexpected behavior for two ```double``` values in C++? | This is the link for the problem that I was trying to solve: https://www.codechef.com/problems/HS08TEST
It's a pretty straightforward problem with just three scenarios so I was sure that the code would run. However, I got the wrong answer message (the website doesn't show what has gone wrong). My code is as follows :
#... | In the problem, there is a condition like, " For each successful withdrawal the bank charges 0.50 $US". If you have 5$ in your account you cannot withdraw 5$. You can withdraw 5$ - 0.50$ = 4.50$ as you have to keep 0.05$ for transaction fee. It needs to be assured before withdraw that you have a transaction fee left in... |
68,661,542 | 68,661,623 | How to get un-overwritten functions from Base to update to overwritten function in derived? | Sorry if this is a duplicate, but I wasn't able to find it elsewhere.
class Base {
public:
template <typename T>
T A(T param, T param2) {
return param + param2;
}
int B() {
return A(1, 1);
}
};
class Derived : public Base {
public:
template <typename T>
T A(T param, T param... | You need to make the function A in the base a virtual function so that runtime polymorphism take place.
class Base
{
public:
virtual int A(int param, int param2) // virtual A
{
return param + param2;
}
// ....
// ~Base () = default;
};
class Derived : public Base
{
public:
in... |
68,661,546 | 68,661,691 | Why does this nested for-loop print this? | I need to figure out how this nested for-loop outputs:
1
2
3
2
4
2
3
5
2
3
4
#include <iostream>
using namespace std;
int main()
{
int x, y;
for (x = 1; x <= 5; x++)
{
cout << x << endl;
for (y = 2; y < x; y++)
cout << y << endl;
}
}
| The problem here is that you don't seem to understand which value is 'x' and which one is 'y':
You can easily understand this by replacing following lines of code:
cout << x << endl;
by
cout << "x: " << x << endl;
And
cout << y << endl;
by
cout << "y: " << x << endl;
|
68,662,005 | 68,664,637 | C++ How to cache a variable of template type T in a class? | Suppose that I have a Foo class like this, and I need many instances of it.
class Foo {
public:
Pool* bars; // a global list of bars, each may have a different type
template<typename T>
T& AddBar(int x) {
return bars->emplace<T>(x);
}
template<typename T>
T& GetBar() {
retur... | While writing a mockup, with the idea of n. 1.8e9-where's-my-share m., for your "complicated registry pool" I wrote the actual could be implementation of Foo. I left in there Foo only to also give some suggestions. If you want so have more than one variable of one type you would have to change the value type of the map... |
68,662,245 | 68,663,521 | Why does any OpenCv (C++) substract operation result in a full black image? | I want to start with that I am certainly no beginner using OpenCV. But I have been mostly using it in C#, and now I am completely lost on a simple issue on the C++ variant that I cannot seem to solve...
Issue: Whenever I use any operation that will subtract one image from another, the output image is 100% black. With 1... | It can easily happen that cv::Mat share their data memory within lists or arrays so that if on of the images is updated, all the images still point to the same memory. For example if capturing updates the same cv::Mat element in every iteration and this cv::Mat is pushed back to a list or vector without deep-copying th... |
68,662,622 | 68,665,032 | GPU array addition using OpenMP | I am trying out OpenMP offloading with an nvidia GPU and I am trying to do some array calculations with it in C++.
Right now my output is not desirable, as I am new with offloading calculations with OpenMP. Would appreciate if someone can point me to the correct direction.
Code Snippet:
#include <omp.h>
#include <iostr... | You have some typos on the OpenMP constructors, namely:
#pragma omp parallal -> #pragma omp parallel;
#pragma omp parallel for -> #pragma omp for
Regarding 2. you do not need the parallel because you are already inside a parallel region.
Try the following:
using namespace std;
int main(){
int totalSum = 0, ... |
68,662,678 | 69,667,525 | Why is the assignment operator private in some libraries? (e.g. RapidJson) | I have encountered some libraries like rapidjson (or wjwwood/serial) where the assignment operator of their more important object is private.
When I try to use the operator on rapidJson:
test.Parse(jsonScheme);
rapidjson::Document test2;
test2 = test;
... and it produces the following error ...
[build] ../... | rapidjson is compatible with pre C++11 compiler, where the =delete directive is not available.
So as @Jarod42 pointed , declaring Copy constructor or copy assignment operator is the old way of prohibiting usage of them. By the way this is stated in some comments,
For example in reader.h :
private:
// Prohibit copy con... |
68,663,058 | 68,663,136 | Why I cannot pass std::make_unique<S> as a function parameter? | Can anyone make it clear for me why I can call std::make_unique<S> with only one template parameter, i.e. S, like this:
auto p = std::make_unique<S>(12, 13);
But, I cannot pass std::make_unique<S> to a function to do that for me, like this:
template <typename FuncType, typename ...Args >
void call_method(FuncType f, A... | The signature for std::make_unique is
template<class T, class... Args>
unique_ptr<T> make_unique(Args&& ...args);
If you call make_unique directly the compiler is using template argument deduction to deduce what Args should be from what you are invoking it with. By passing std::make_unique<S> to your function, you are... |
68,663,199 | 68,663,306 | Why does operator== work for statically initialized char*? | When creating a char array like:
char c_array1[] = { "str1" };
char c_array2[] = { "str1" };
char* cp_array1 = c_array1;
char* cp_array2 = c_array2;
if(cp_array1 == cp_array2) { // char* cannot be compared with char*
The comparison does fail. But with statically initialized char*:
char* cp_array1 = "str1";
char* cp_ar... | "But with statically initialized char* It works" - It may work - if the compiler optimized your code to store only one str1 (which it is allowed to do).
You are comparing pointers - not the strings they point at.
If you want to compare the strings, use std::strcmp:
if(std::strcmp(cp_array1, cp_array2)) {
// not equ... |
68,663,394 | 68,663,619 | Any idea why MSVC returns -1 for mktime? | I have the following code:
int main() {
std::tm tm{};
tm.tm_min = 30;
tm.tm_hour = 15;
tm.tm_mday = 1;
auto tt = std::mktime(&tm);
std::cout << tt;
}
any idea why MSVC returns -1 for mktime()? clang and gcc return value(negative non -1 value, so it should be valid). I'm using VS2019, and compi... | std::mktime() returns the "time since epoch", which is Jan 1st, 1970. The exact type of time_t is unspecified, but the semantics is the famous Unix-derived "seconds since epoch", that is, Jan 1st, 1970, 0:00 h. The POSIX standard says:
The mktime() function shall convert the broken-down time, expressed as local time,... |
68,663,872 | 68,664,025 | How does vector's begin() and end() work, and how should I write it for my custom vector? | I am currently studying Bjarne's PPP, and I don't really understand how begin() and end() works, and how I am supposed to implement it.
Here is my code for the vector.
template<typename T> class vector {
int sz;
T *elem;
int space;
std::allocator<T> alloc;
public:
vector():sz{0},elem{nullptr},space{... | begin() and end() should return an iterator. Basically, iterator is a class that implements variables such as iterator_category and value_type, which let other functions to know how to use it.
It should also implement functions required by the iterator_category that you choose to use.
For your a vector, you need a rand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.