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 |
|---|---|---|---|---|
62,405,407 | 62,405,496 | std::size() from iterator library won't work on C-style array passed to function | #include <iostream>
#include <iterator>
void count(int foo[])
{
int dSize;
dSize=std::size(foo); //No matching function for call to 'size'
std::cout<<dSize<<std::endl;
}
int main()
{
int arr[5]={0,0,0,0,0};
count(arr);
return 0;
}
Hi, I'm trying to run this code, but it give me this error. T... |
is it because of when you pass this to a function the array decay to a pointer?
Almost. More accurately, it is because you declared that the function argument is a pointer. std::size only works with containers (or anything that has member function size) and arrays. A pointer is neither of those.
|
62,405,599 | 62,405,657 | Undefined references to global variable in QT C++ | I'm try to pass string value from mainwindow.cpp to userdetails.cpp. I had been used global variable. And When the program run it's show error message "Undefined references to globelusername". globelusername mean the global variable name. What is the error in code?
mainwindow.h
#ifndef MAINWINDOW_H
#define MAIN... | This line
extern QString globelusername;
just declares a global variable but does not define it.
You have to define it in one of your .cpp file (e.g. in mainwindow.cpp):
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString globelusername;
// ...
|
62,405,998 | 62,412,209 | Painting rows and columns of a 2D matrix | Problem: We have given a nxm matrix, initially initialized with 0. We have to perform k queries:
Each query supports one of the two operations.
paint all elements in ri row with the colour ai .
paint all elements in ci column with the colour ai.
The same element can be painted more than once. But the color of that ... | It is only needed to memorize the last color that was affected to a given row or a given column, and the last time at which it was performed.
Then, for a given element mat[i][j], we simply have to check if the last modification on row i occured before of after the last modification on column j.
We don't even need to s... |
62,406,373 | 62,406,613 | C++: no matching function for call: why is an empty constructor needed? | When I try to compile the following code:
class a {
int i;
public :
a(int);
};
class b {
a mya;
int j;
public:
b(int);
};
a::a(int i2) {
i=i2;
}
b::b(int i2) {
mya=a(i2);
j=2*i2;
}
int main() {
}
I get the following errors:
prog.cpp:21:12: error: no matching function for call to ‘a::a()... | (All ISO Standard references below refer to N4659: March 2017 post-Kona working draft/C++17 DIS)
As per [class.base.init]/9, the mya member of b, which is of type a, is default-initialized, but a defines no default constructor:
In a non-delegating constructor, if a given potentially constructed
subobject is not des... |
62,406,433 | 62,406,956 | MSVC fails to compile SFINAE checks | Is there some compiler flag I should be aware of? The following code works just fine and as intended according to GCC and Clang but not MSVC. What makes std::allocator's allocate so different here?
#include <type_traits>
#include <memory>
template <typename T, typename = std::void_t<>>
constexpr bool declares_allocate... | Depending on the C++ standard implementation, std::allocator<T>::allocate can be defined as:
T* allocate(size_t n, const void* hint = 0);
T* allocate(size_t n);
T* allocate(size_t n, const void* hint); // deprecating usage of hint
T* allocate(size_t n);
That is, the second implementation turns allocate into an o... |
62,406,576 | 62,406,834 | Using Main() return value as an argument for a python script | I want my C++ processes to pass their return value to open a python script.
cpp example file
int main()
{
//do something
//process is going to finish and is gonna return, for simplicity, 0
//retval = 0, or whatever the return value is going to be
popen("mypython_script.py retval")
return 0;
}
mypython... | You can capture the return value of the C++ program from the parent python script, if you run the C++ program using cpp_retval = subprocess.call(...), or cpp_retval = subprocesss.run(...).returncode (https://docs.python.org/3/library/subprocess.html).
Then you can pass that to the other python script. So, something lik... |
62,406,793 | 62,406,878 | Why is my Char* empty after filling with integers? | I would like to save several integers in a char pointer and then send this pointer with sendto (winsock2). Unfortunately my char pointer always only contains "\n". Right at the creation and also after filling. What have I done wrong?
uint32_t id = getID();
uint8_t inputType = getInputType(), inputValue = getInputValue(... | You char pointer does not contain '\n', at least not in the first position anyway. Rather it contains NUL as the first element, so it will appear blank when displayed as a C-style string.
That's because the least significant 8 bits, obtained with & 0xff, of 10 right-shifted 24 times is zero.
There are data in the char... |
62,406,819 | 62,472,736 | How to call ntoskrnl.exe srand function? | With dumpbin.exe, we can see that ntoskrnl.exe exports the srand function.
With the Windows Driver Kit, how to call this function ?
I have already tested with stdlib.h, but I would like to call ntoskrnl.exe directly.
Thank you
| #include <stdlib.h>
EXTERN_C NTSTATUS DriverEntry(DRIVER_OBJECT *pDriverObject, UNICODE_STRING *pRegistryPath)
{
srand(100);
return STATUS_UNSUCCESSFUL;
}
|
62,407,279 | 62,409,018 | Fixing "-Wunused-parameter" warning which depends on pre-processor conditions | How to fix the "-Wunused-parameter" warning when the use of variable depends on the preprocessor-directive(#if, #else ...) conditions.
void foo(std::string& color)
{
#ifdef PRINT
printf("Printing color: ", color);
#endif
}
I have seen the usage of (void) like:
void foo(std::string& color)
{
#ifdef PRINT
printf... | I really prefer to use std::ignore:
// Example program
#include <iostream>
#include <string>
#include <tuple> // for std::ignore
void foo(std::string& color)
{
#ifdef PRINT
printf("Printing color: ", color.c_str());
#else
std::ignore = color;
printf("Not printing any color");
#endif... |
62,407,661 | 62,407,721 | Unexpected behaviour while using ostringstream | Getting different output in following cases
std::string temp, temp1 = "foo", temp2 = "bar";
std::vector<char> test;
std::ostringstream s;
s << temp1;
temp = s.str();
std::copy(s.str().begin(), s.str().end(), std::back_inserter(test));
std::copy(temp2.begin(), temp2.end(), std::back_inserter(test... | The streams str function returns the string by value.
That means the two s.str() calls will return two different strings, and their respective begin and end iterators will be for different strings, making the std::copy call invalid and lead to undefined behavior.
|
62,407,709 | 62,421,101 | Change "header files" (folder name) from Chinese to English in Visual Studio 2017 | Hi completely vs and c++ beginner here.
The project was made in a "chinese working environment", thus you can see the "header files, source files, and resource files" are all in chinese after I loaded it in my "english working environment". Is there any way I can make them English? Or I can just manually change them?
T... | Either within the IDE: right-click each folder name, select Rename from the context menu, and enter any name you prefer, including the default English name.
Or outside the IDE: close the project in Visual Studio, edit the .vcxproj.filters file in the project root (using a UTF-8 aware text editor), and replace the ... o... |
62,407,769 | 62,407,956 | Filling of vector with unique_pointers | I have to classes A and B.
B derives from A.
I have also vector std::vector<std::unique_ptr<A>> samples
This piece of code works:
std::vector<std::unique_ptr<A>> samples;
samples.push_back(std::make_unique<B>(param_1, param_2));
But this one doesn't:
std::vector<std::unique_ptr<A>> samples = {std::make_unique<B>(param... |
Is this error connected with lack of proper constructor in vector (interator?) or in A/B class?
Neither, this is due to the fact that the copy constructor of std::unique_ptr is implicitly deleted (due to the user-declared move constructor); you cannot copy a std::unique_ptr, you move it.
When I make push_back, sh... |
62,407,997 | 62,416,526 | Cannot allocate memory using boost test | I have a test case like this:
BOOST_AUTO_TEST_CASE(Test) {
std::thread([](){
BOOST_CHECK(system("script.sh") >= 0);
}).detach();
//other checks here
}
When I run only this test suite everything is ok. When I run my 80 tests then assert fails with "cannot allocate memory" as value returned by system... | If you run the test in isolation and it works, while running this test in non-isolation (with other tests) and it fails, then "something" is happening to the state of your test program and that need to be fixed.
For instance,
a memory leak in other tests that affects this one,
the fact that you started too many thr... |
62,408,177 | 62,408,300 | QtMetaObject unresolved external Error in Visual Studio 2017 | I'm trying to implement a simple server client application in QT. I'm using Visual Studio 2017.
Here's the Header File to my client class.
#pragma once
#ifndef Client_H
#define Client_H
#include <QTcpSocket>
class Client : public QObject
{ Q_OBJECT
public:
explicit Client (QObject *parent = 0);
void... | These files are automatically generated by the moc tool. Did you set it up to run whenever your header file changed? Did you run it manually? If not, consider installing the Qt Visual Studio tools that solve this for you.
|
62,408,203 | 62,408,264 | size of type vs its unsigned equivalent? | The standard specifies minimum ranges that can be hold by arithmetic integer type. However, is there a guaranty that for each signed integer, its unsigned equivalent has the same size?
In other words, is it Always true that:
sizeof(short) == sizeof(unsigned short)
sizeof(int) == sizeof(unsigned int)
sizeof(long) == siz... | (All ISO Standard references below refer to N4659: March 2017 post-Kona working draft/C++17 DIS)
However, is there a guaranty that for each signed integer, its unsigned equivalent has the same size?
Yes.
From [basic.fundamental]/3 [extract, emphasis mine]:
[basic.fundamental]/3
For each of the standard signed integ... |
62,408,315 | 62,408,531 | How to inherit from array built in class in c++ | I want to make a class that inherits from base array class, and just add some new functionality for the sake of learning.
Now when I try using this code
class checkInherit : public array
Error is
C++ argument list for class template is missing
Which I think is that I have to add some arguments. When I Peeked into ... | If your array is the standard std::array template, I won't recommend inheriting from it.
I want to make a class that inherits from base array class, and just add some new functionality for the sake of learning.
That smells like a very bad idea. Read a good C++ programming book then a C++ reference.
If you really want... |
62,408,326 | 62,408,942 | Endless loop after exceeding the value range of the int | I have programmed a decimal to binary converter and used the datatype unsigned long long int. Additionally I have a while loop so that I can convert a number again after the conversion. Why do I come into an endless loop if I exceed the value range of the unsigned long long int?
My guess is that the loop has no conditi... | You just need to add a litte check if the user wants to continue converting the numbers. The problem was your while loop in main() checking a variable which is never changed. Use something like this:
int main() {
char ch = 'Y';
while (ch == 'Y' or ch == 'y') {
calculateBinary();
std::cout << "\... |
62,408,341 | 62,409,193 | Unsigned character prints it's ascii value | I have C++ program that reads from a binary file byte by byte then outputs it as a character to the console.
After using unsigned char as a type, the console will print it's ascii value, which I didn't expect.
How do I get it to print the character instead of it's ascii value?
The reproducible code:
#include <iostream>... | The latest problem is caused by the mix of types in the conditional expression.
unsigned char a;
...
cout << (a > 31 ? a : '.');
This expression has type int because neither char type is big enough to include all the values of the other. (Apologies if the previous statement isn't totally accurate, I can't be bothered... |
62,408,580 | 62,408,674 | Unhandled exception in 0x7A47E727 | #include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
//system("cls");
const int x = 30;
const int y = 15;
string tabella[y][x];
char bordo = '#';
for (int i = 0; i < x; i++)
tabella[0][i] = bordo;
for (int i = 0; i < y; i++)
tabella[i][0... | You declare the array
const int x = 30;
const int y = 15;
string tabella[y][x];
but here you use the indices wrong:
std::cout << tabella[i][j];
because i counts from 0 to 29 and j counts from 0 to 14.
So you have to use:
std::cout << tabella[j][i];
This will solve your problem
|
62,408,857 | 62,424,756 | Can `new` and `delete` be used in a DriverKit driver? | DriverKit provides IONewZero and IOSafeDeleteNULL. Those does not call any constructor or destructor.
Let's say that I would like to have some class in the ivars structure. The class does not need to inherit from OSObject nor IOService. How should I construct this object? If I have it as a member in the ivars struct t... | The default operator new is indeed implemented in the DriverKit runtime. I've used it successfully to allocate and initialise my …_IVars objects themselves. (the PIMPL type that's automatically forward-declared by the header generated by iig for any classes defined in .iig files)
So, I actually do this in MyDriver::in... |
62,408,913 | 62,409,268 | Unable to allocate memory with new[] from within templated function | I am trying to create a function that allocates memory. It allocates it, but the problem is that it only appears to do so inside the function, but after it returns the memory allocated is no longer there. Almost as if I am allocating memory with another pointer, but there should be no other there.
template<class T> str... | When you pass an integer to a function, you cannot change the integer.
When you pass a pointer to a function, you cannot change the pointer.
When you pass a pointer to a function, you can change the pointed-to value.
Pass-by-non-const-reference is the exception; it allows you to change the passed value. Passing a point... |
62,408,941 | 62,429,278 | Cannot obtain same output tensor values in C++ side | I try to make predictions for a 4-class classification project in C++ side using libtorch 1.4. However, I cannot obtain same predictions compared to Python side. Firstly, I obtain same input tensor values just before prediction. When I compare the output tensor values, I noticed that they are different. You can find th... | I noticed that I used opencv functions to apply normalization using this code:
subtract(image, Scalar(0.485, 0.456, 0.406), temp);
divide(temp, Scalar(0.229, 0.224, 0.225), image);
This operation changes only the first channel and does not change other channels. For this reason, in fact, input tensor values are differ... |
62,408,946 | 62,409,658 | In Linux, How to get the backtrace of a program running under valgrind | OS : Linux RedHat 7.7
Program is running under valgrind
I want to get the current backtrace in order to find out what the program is doing (similar to use of gstack when NOT running under valgrind).
Use of 'gstack' does not show useful information when the program is under valgrind.
Is there anyway this can be achieved... | found the answer, 'vgdb v.info scheduler"
|
62,409,234 | 62,415,177 | Function template overload resolution, dependent and non-dependent parameters | Given the following program
#include <iostream>
template<class T> struct id { using type = T; };
template<class T1, class T2>
int func(T1, T2) { return 0; }
template<class T1, class T2>
int func(typename id<T1>::type, typename id<T2>::type) { return 1; }
int main()
{
std::cout << func<int, int>(0, 0) << std::en... | This is bog-standard partial ordering. We substitute unique types into one of the function templates and try to deduce the other against it. Do it both ways and if deduction only succeeds in one direction, we have an order. If you want to read the arcane rules, see [temp.func.order] and [temp.deduct.partial].
So here,
... |
62,409,554 | 62,411,980 | How do I optimise the code to return the number closest to a given integer, not present in the given list? | I solved this problem statement (Yeah Yeah, I know, I am putting the problem statement below).
Given are an integer X and an integer sequence of length N: p1, …, pN.
Among the integers not contained in the sequence p1, …, pN (not necessarily positive),
find the integer nearest to X, i.e. the integer whose absolu... | You can see this "cheating" algorithm. It's cheating because the _Find_next method is only in the GCC compiler. Also, with the help of printf and scanf, I accelerated input and output, due to which the program runs faster. I sent it for execution several times and received 4, 6 and 8 ms (6 ms most often):
#include <bit... |
62,409,584 | 62,420,818 | How to ignore execution of some line of binary file? | I want to make my program more strong in front of hackers, so i have a program::validator class which validate my environment by some parameters. I :
Compile program::validator shared library.
Compile program using -O2 and --ffast-math and link to libprogramvalidator.so.
Run the program with the GDB.
Find the line whi... |
i just want avoid call to is_valid_system function in my ELF executable binary file.
There are several easy ways. You can use GDB jump $address, or return commands to achieve this. Example:
#include <stdio.h>
int is_valid_system()
{
return 0;
}
int main()
{
if (is_valid_system()) {
printf("Life is good\n");... |
62,409,721 | 62,409,893 | In the C++ standard does well-formed means that the code compiles? | The C++ standards defines well-formed programs as
C ++ program constructed according to the syntax rules, diagnosable
semantic rules, and the one-definition rule
I am wondering if all well-formed program compile or not (if it is not the case, what types of error make the difference between a well-formed program an... | A well-formed program can have undefined behaviour.
It's in a note, and thus not technically authoritative, but it seems that it is intention that termination of compilation (or "translation" as the standard calls it) is within the scope of possible UB:
[intro.defs]
undefined behavior
behavior for which this document ... |
62,410,062 | 62,410,157 | running windows C++ code on a linux cluster | My program recently got an bad_alloc error when increasing it's precision. My guess is, that it needs more RAM than my Computer can assign it (effectively more than 3GB RAM needed).
So I decided to try it on our linux cluster since it can give me way more RAM. It contains some gcc modules. But I'm not sure how to use m... | There are ways to make Windows executables run on Linux, e.g. Wine but usually you want a native Linux executable. Executables have a different file format on Windows (EXE) and on Linux (ELF).
Your options are
to recompile the code and run the program without other tools or
to use a tool, e.g. Wine, that can run Windo... |
62,410,305 | 62,410,352 | Problem with pow giving me an infinite answer | I'm trying to compute a discount factor given a rate and the number of payments to be made per year.
#include <iostream>
using namespace std;
int main()
{
uint32_t due_dates_per_year = 2;
double t = 1;
double rate = 0.05;
double df = pow(1 + rate / due_dates_per_year, -due_dates_per_year * t);
cout ... | The problem is in the exponent (i.e. the second parameter) of std::pow. The expression
-due_dates_per_year * t
is grouped as (-due_dates_per_year) * t (that's how the C++ grammar parses the expression). The unary negation of the unsigned type produces a large (and also unsigned) number which explains the result.
Other... |
62,410,380 | 62,410,436 | std::bad_cast vs NULL, what's the difference? | Why we need std::bad_cast when It returns Null when it fails?
I learnt that when dynamic_cast fails it returns Null So I could check if Null was returned it means an error happened.
But why std::bad_cast exception was added to C++?
| Because you can't have a null reference. A dynamic_cast<T*> can return nullptr as a failure but dynamic_cast<T&> can't, since you're returning a reference to the object. For that case you need an exception to know that the cast failed.
|
62,410,396 | 62,410,464 | Global variable pass the null value | I'm try to pass string value from mainwindow.cpp to userdetails.cpp. I had been used global variable. When the program run it does not pass the variable value to the userdetails.cpp. When I use qDebug( globelusername.toLatin1() ) it does not show any value. What is the error in this code? globelusername mean, the glob... | You are not setting globelusername. instead, you are creating a local variable with the following line:
QString globelusername = username; //globlevariable
remove the variable type before setting the value:
globelusername = username; //globlevariable
|
62,410,834 | 62,419,073 | How to draw SDL 2D rectangles over a 3D OpenGL scene? | I'm trying to overlay small interactive info rectangles drawn with SDL 2D over a 3D scene drawn with OpenGL. Each of itself works, but not together. The 3D model is then hidden.
SDL_Init(SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute(SDL_GL_CONTEXT... | You don't, at least for now.
Here's the (open) bug about adding backend API state getters/setters to SDL_Renderer..
Alternatively, create a SDL_Renderer instance that uses the software renderer & upload the bitmaps coming out of that into a OpenGL texture & composite that into your scene.
|
62,410,916 | 62,411,097 | Don't use static cast for arithmetic conversions (cpp-core-guidelines) | msvc's code analyzer for the cpp core guidelines tells me
Warning C26472 Don't use a static_cast for arithmetic conversions. Use
brace initialization, gsl::narrow_cast or gsl::narrow
(type.1).
for this snippet
static_cast<IntType>(static_cast<unsigned long long>(hexValue(digit)) << (digitIdx * 4));
Why shouldn't ... |
so is this purely a readability issue here?
Nope. Brace initialization prohibits narrowing conversions, and will cause a diagnostic. The guideline's purpose is to help protect code from unintended narrowing. A static_cast will allow a narrowing conversion through silently.
You seem to be dealing in integers, so short... |
62,410,928 | 62,411,134 | C++ Struct with default argument, optionally changeable in constructor | Let's say I have the following struct.
struct vehicle
{
int price;
char* year;
char* type;
}
I would like to make a regular constructor for it, that would allow me to specify each member.
Nevertheless, I would like to set the member "type", as "car" b... | First of all, you didn't say it, but I sense a small misunderstanding: The difference between a struct and a class is just convention. Structs are classes in C++. The keywords struct and class can be used to declare a class and the only difference is the default access (in accordance with the common convention that str... |
62,410,929 | 62,412,039 | Mac c++ filesystem library not recognized | NOTE: this does not fail to #include <filesystem>. It fails afterward.
I’m on a macOS 10.15, using clang 11. Output of clang --version:
Apple clang version 11.0.0 (clang-1100.0.33.17)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
When I try to compile s... | Yes, there are specific compiler options you need. Notice that the entire contents of this header, apart from boilerplate, are wrapped in an #if __cplusplus >= 201703L ... #endif block. That means the header is effectively empty unless the compiler declares conformance with the 2017 revision of the C++ standard (or l... |
62,411,111 | 62,411,365 | How to delete a overload function from overload resolution? | Say I have a class STest and I want it to be able to implicitly cast to char const* but not bool.
struct STest {
operator char const*() const& { return "abc"; }
operator bool() const& = delete;
};
void bar(bool) {}
void foo(bool) {}
void foo(char const*) {}
This implementation works as expected (error) when... | You can use a conversion operator template, and constrain it with SFINAE.
struct STest {
template<typename T, std::enable_if_t<std::is_same<char const*, T>::value, int> = 0>
operator T() const& { return "abc"; }
};
Instead of having two overloads participating and causing an error when the wrong one is chosen,... |
62,411,152 | 62,411,731 | Constructor taking std::string_view vs std::string and move | Suppose I have a class which has a std::string member, and I want to take the value for this member in one of its constructors.
One approach is to take a parameter of type std::string and then use std::move:
Foo(std::string str) : _str(std::move(str)) {}
As far as I understand it, moving a string just copies its inte... |
No need for moves or constructing temporary std::string's, but I think it actually just does effectively the same thing as before.
That entirely depends on what the user has when they call your constructor. So lets consider your case 1 (std::string) and case 2 (std::string_view). In both cases, the eventual result is... |
62,411,200 | 63,865,598 | Trait to detect if a function type is maked noexcept | I am wondering whether there would be a trick to simplify the writing of a trait to return whether a type is a noexcept function. Currently my implementation is the following, and it just lists all the possibilities, one by one. Could it be written in a simpler way using standard C++20?
// Default
template <class>
stru... | There are two parts to your problem: detect whether the type is a function, then detect whether that function is noexcept. Unfortunately, there is no better way to detect whether a type is a function. Not even in C++20. You really do need to specialize for all combinations of const, volatile, and ref qualification.
Thi... |
62,411,394 | 62,433,229 | Given an array S of size N , check if it's possible to split sequence into two sequence | Given an array S of size N, check if it is possible to split sequence into two sequences - s1 to si and si + 1 to sN such that first sequence is strictly decreasing and second is strictly increasing.
Input Format
First line contains a single integer N denoting the size of the input.
Next N lines contain a single intege... | I tested your code on some test cases and it seems that your code fails on,
n = 2
1 1
It's answer should be True as it can be broken into {1}, {1} and since single element is increasing as well as decreasing both, the answer is true.
Here is my code
Explanation: My whole concept is based on we need to check if given s... |
62,411,825 | 62,412,189 | How can I better check whether two char variables are in some set of values? | Recently, our professor has requested that we use two char variables (day) to receive the input from the user.
The code below works fine as a check to ensure that either Mo, Tu, We, Th, Fr, Sa, Su are the only two characters which are entered together as a pair. If anything else is received as input, it'll loop and ask... | You could write a fold-expression that compares 2 characters to a string:
template<typename ...Days>
bool any_of(char a, char b, Days ...days)
{
return (... || (a == days[0] && b == days[1]));
}
and then use it like this:
while (! any_of(std::tolower(dayOne), std::tolower(dayTwo), "mo", "tu", "we", "th", "fr", "sa... |
62,411,973 | 72,707,790 | ifstream: /dev/stdin is not working the same as std::cin | For my formation, an exercise ask us to create a program similar to the linux 'cat' command.
So to read the file, i use an ifstream, and everything work fine for regular file.
But not when i try to open /dev/ files like /dev/stdin: the 'enter' is not detected and so, getline really exit only when the fd is being closed... | The following code worked for me to deal with /dev/fd files or when using shell substitute syntax:
std::ifstream stream(file_name);
std::cout << "Opening file '" << file_name << "'" << std::endl;
if (stream.fail() || !stream.good())
{
std::cout << "Error: Failed to open file '" << file_name << "'" << std::endl;
... |
62,412,126 | 62,412,372 | Warning: ignoring attributes on template argument... in declaration of std::unique_ptr (-Wignored-attributes) | Using the pattern explained here as follows:
auto action =
std::unique_ptr< posix_spawn_file_actions_t, decltype(&posix_spawn_file_actions_destroy) >
{ new posix_spawn_file_actions_t(), posix_spawn_file_actions_destroy };
triggers a [-Wignored-attributes] in gcc v10.1.0 -std=c++20:
warning: ignoring attributes o... | It is saying you are ignoring the fact the function pointer doesn't throw.
Your code has other errors, like newing a pointer that isn't cleaned up by delete.
In c++14 or later I use
template<auto x> using kval_t=std::intergral_constant<std::decay_t<decltype(x)>,x>;
template<auto x> constexpr kval_t<x> kval={};
You can... |
62,412,380 | 62,412,450 | How to add at the end of a linked list? | I'm trying to make a function that adds at the end of a linked list but I get a segmentation fault.
I don't really know what's wrong with my code. I first check if the list is empty. If it is not empty then I first find the end of the list using n I use a while loop to do this, then once that loop is done I then set n-... | When head is NULL, you are doing:
if (!head) {
head->next = tmp;
}
but there is no next for a NULL pointer, so this invokes undefined behavior.
You should instead do:
if (!head) {
head = tmp;
}
Here's a demo.
Also, avoid the NULL macro, and use nullptr instead.
|
62,412,528 | 62,412,591 | Printing vector elements with algorithm and/or functional library | I was wondering if there is any way to print elements of vector only with using algorithm and/or functional library.
I've done it with std::for_each() but I still need to use lambda function (and with my own named function), is there any way to avoid it?
Here is my line of code that I need to replace with that new vers... | This version doesn't need a lambda:
std::copy(v.begin(), v.end(),
std::ostream_iterator<int>(std::cout, "\n"));
|
62,413,368 | 62,413,444 | Copy a char vector to another vector | I'm trying to create a function to copy an vector into another one :
#include <iostream>
#include <vector>
int clone(std::vector <char> X, std::vector <char> Y){
for(int i(0);i<X.size();i++){
Y[i]=X[i];
}
return 0;
}
When I call the function, nothing appears on the prompt window.
| There are 2 issues with your code. The first is that any modification to Y will not be visible at the call site, since you are passing the vector by value. Instead, you need to pass it by reference.
Second, you are indexing X incorrectly (assuming X is not as large as Y). Instead, you could just push_back the values.
H... |
62,413,815 | 62,413,885 | Monitoring a shared variable with read write access by multiple threads in C++ | I am looking for a better implementation of the below code segment to minimize CPU usage. I have a variable that has read/write access for multiple threads and needs to be monitored as below.
while(true){
mutex.lock();
int flag = external_flag;
mutex.unlock();
if(flag == 3){
break;
... | Use an atomic variable since that will be faster than a full-blown mutex and as well as likely lock-free. For instance,std::atomic<int>
or std::atomic_flag depending on what you are doing.
However, depending on what you are exactly doing in your code, you may want to use a condition variable like std::condition_varia... |
62,414,035 | 62,414,336 | Unable to get `std::enable_if` to work for unscoped enum | I'm trying to build a utility ToString function that either calls std::to_string or a custom to_string method defined somewhere else. This is what I came up with for version 1.0:
Context
The code here is a close approximation to what I'm working with for context. I have enums from a 3rd party library that are defined u... | You need either
move
std::string to_string(ThirdPartyNamespace::Unscoped value)
into namespace ThirdPartyNamespace to be found thanks to ADL
or, change your ToString to
template <typename T>
std::string ToString(const T& value)
{
using std::to_string;
using Helpers::to_string;
return to_string(value);
}
... |
62,414,122 | 62,423,513 | Distirbute Candy - Finding minimum reproducible example of the problem | The question is to distribute candies to N children.Each child has a rating. Distribution should be such that each child have at least one candy and children with higher rating gets more candies than their neighbors. Find minimum number of candies for such distribution.
Approach:
iterate each child.
if (rating... | If you only need an example that exposes an error in your code, use 3 2 2 and stop reading.
I would suggest a very literal solution to the problem:
Initialize a result array of equal size as the A array with value 1 for each position (each child gets at least one candy)
Forward iterate the arrays and apply following ... |
62,414,174 | 62,414,576 | Is the compiler forced to evaluate if expressions depending on template parameters? | Consider this code snippet:
#include <iostream>
struct A {
void f() { std::cout << "f"; }
void g() { std::cout << "g"; }
template <bool b>
void call() { (b ? f() : g()); }
};
int main()
{
A().call<true>();
}
Depending on the template paramter passed to call, either f or g will be called. My que... | All template expressions are evaluated at compile time, because templates don't exist at runtime. You can use if constexpr which is garantueed to be evaluated at compile time:
template <bool b>
void call() { if constexpr (b) f(); else g(); }
In you example (for b = true) this will become
void call() { f(); }
regardl... |
62,414,294 | 62,414,675 | Cmake cannot add "-fPIE" flag to makefile | I'm trying to compile C++ code with python embedded in it. The compiler does not compile my code with '-fPIE' flag even though I've added it in CMakeList.txt. Here's my CMakeList:
cmake_minimum_required(VERSION 3.3)
project(TestCython)
add_executable(main main.cpp)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_R... | Note that most of the time this error has nothing to do with the PIE flag but is rather something else screwy about your build, unfortunately it’s a bit hard to tell because your CMake config is a bit screwy.
This particular error however is probably because you’re setting your properties incorrectly; Setting CMAKE_CXX... |
62,414,709 | 62,424,906 | How do I load a cheerp-wasm program in absence of a 'path' module? | Cheerp has a cheerp-wasm target that compiles C++ to both a .js and its associated .wasm file. The way I understand it is that the .js file is effectively a loader for the webassembly.
This loader calls require("path") to import required filesystem functionalities to load the .wasm as a file. The environment in which m... | Cheerp retrieves the wasm file in different ways based on the environment.
The supported environments are: browser, node.js, d8 and js.
The node environments assumes that there is a path module for reading the wasm from the filesystem.
It seems that this is not available in your environment.
We plan to allow more flexi... |
62,414,954 | 62,415,249 | Why does putting const on the left side of an ampersand valid when referring to a pointer but not on the right? | I was wondering why this line is considered valid:
Entity* const & e = this;
But this line is not:
Entity* & const e = this;
What does the ampersand actually doing here? Why is putting const on the left of it valid but not on the right? By the way, these lines are part of a constructor in a class called Entity.
|
What does the ampersand actually doing here?
It is a punctuator that that designates a reference type. It is similar to how the asterisk designates a pointer type.
Why is putting const on the left of it valid but not on the right
Because const qualifier applies to whatever is on the left side of it1. And if const i... |
62,415,074 | 62,415,422 | Difference between shared library (.so) a Linux executable file without extension? | To clarify, this is a question about binary Linux executables, not scripts, which can also be executable and also often lack an extension.
In my experience, most Linux binary executables lack a file extension; e.g. most of the files in the /bin directory on Linux systems lack an extension.
On the other hand, most of t... |
One of the main differences is that a shared library does not have a main() function. It also contains position independent code that may or may not be the case for executables. If you do put a main() function in the library, you still need to link it with a normal object file (containing no main() function).
Yes. To ... |
62,415,232 | 62,415,274 | GLFW_PRESS throws "lvalue required as left operand of assignment" | I am trying to make a simple GLFW key callback function using the provided code in the documentation:
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_W && action = GLFW_PRESS) {
glTranslatef(0.25f, 0, 0);
}
if (key == GLFW_KEY_A && action = GL... | The problem was a syntax error, using = instead of ==.
|
62,415,285 | 62,417,996 | Updating learning rate with Libtorch 1.5 and optimiser options in C++ | With the release of the 1.5 stable version of the C++ API for PyTorch, there are some changes in some of the object interfaces. For instance, now
optimizer.options.learning_rate();
won't work (here the optimiser being used is Adam) since learning_rate has changed to lr (see https://github.com/pytorch/pytorch/releases)... | The optimisers now behave like their Python counterparts and the learning rates need to be set per parameter group.
for (auto param_group : optimizer.param_groups()) {
# Static cast needed as options() returns OptimizerOptions (base class)
static_cast<torch::optim::AdamOptions &>(param_group.options()).lr(new_lr);
... |
62,415,313 | 62,415,487 | How to make HTML5 email validation regex work in C++? | I am trying to validate email both on the client-side and on the server-side. The client-side is JavaScript(web front-end). The server-side is written in C++11.
The regex I am using to validate email is provided by the HTML standard (here)[https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type=email)]. I ... | The / at both ends of the JavaScript regex literal are regex delimiter characters, they are not part of a regular expression pattern.
In C++, you set the regex using either regular or raw string literals, do you do not need to include regex delimiters into the pattern.
So, if you have const regex = /abc/ in JavaScript,... |
62,415,894 | 62,415,953 | C++ function template requires & for array parameter | In this MCVE, the compiler complains that processArray can't match the parameter list (arr). The fix is to replace T elements[SIZE] with T (&elements)[SIZE]. Why do I need to do this, and under what circumstance? I wouldn't use & to pass an array into a function ordinarily. (Only reason I thought of it is that's how C+... | This is because of array decay. Unless you pass an array by reference, it is going to decay into a pointer. That means
void processArray(T elements[SIZE])
is really
void processArray(T* elements)
and there is no way to get what SIZE is for your template since a pointer doesn't know the size of the array it points t... |
62,416,152 | 62,422,940 | How to cast each variant type with variadic template | What I want to do is to cast each "VariantType" (union of different types) argument to it's type before calling some function from a shared library. what I'm doing so far now is down below. it's just 3 different types and 2 arguments and it takes a lot lines. but I want to achieve this with variant number of argument w... | I've finally found the simple way to cast each argument with a variadic template (kinda reinvent the wheel std::visit).
template<typename... Targs>
void visit(const char* func_name, int visiting_arg, VariantType front, Targs... p_args) {
if (visiting_arg == 0) {
call(func_name, p_args...);
return;
... |
62,416,742 | 62,418,007 | How to add libjpeg-turbo Android NDK as static library | I want to use libjpeg-turbo (exactly only libjpeg) in my Android NDK project. I can't find how to completely add the library to my project.
Firstly, I build it by using BUILDING.md (as four ANDROID_ABI: arm64-v8a, armeabi-v7a, x86, x86-64).
Secondly, I prepare in my project src/main/cpp folder libjpeg and put in ANDRO... | You receive the compile error because your CMake code doesn't specify the location of libjpeg header files. You can specify the directory containing the libjpeg headers by setting the INTERFACE_INCLUDE_DIRECTORIES property for the imported libjpeg target.
add_library( libjpeg STATIC IMPORTED )
set_target_properties( li... |
62,417,048 | 62,417,453 | build a standalone exe file form a QT+openCV project running in QT Creator | I just recently programmed a project in QT Creator framework which both uses QT libraries such as QT_Widget and also openCV libraries such as openCV_tracking .
my project includes .ui , .pro , main.cpp and some classes with .h and .cpp files.
my .pro file is :
QT += \
core gui \
concurrent widgets... | I tried this a while ago but eventually gave up, although it definitely is possible.
The reason Qt hides how to do it so much is that they much prefer that people dynamically link to their libraries as it both allows users to update/change the Qt dll's as they please and (which I think is the real reason) it makes it m... |
62,417,469 | 62,417,829 | An efficient data structure for access by ID and finding the weighted random item | Could you, please, help me with the data structure that allows O(logN) (or at least O(sqrtN)) operations for the following:
Insert an item having ID (int64_t) and health (double)
Remove an item by ID
Find an item that is weighted random by health
The preferred language is C++ or C. By the weighted random I mean the f... | I can't think of a way to do it with the existing STL containers but I can think of a way to do it if you're willing to code up your own binary tree. The trick is that each node maintains the total health of all the nodes to its left (it doesn't need to worry about nodes to its right as you'll see below). Then, if you ... |
62,417,880 | 62,417,953 | std::greater on a an std::pair of a double and a class | Does std::greater work when you have a std::pair of int and a class?
I am trying to create a priority queue of pairs, ordered by the first element:
std::priority_queue<std::pair<double, classA>, std::vector<std::pair<double, classA>>, std::greater<std::pair<double, classA>>> priorityQueue
But I get an error that says... | std::greater is just a wrapper for a call to operator < of the template type. For std::pair we can check the reference site here and we see it says
Compares lhs and rhs lexicographically by operator<, that is, compares the first elements and only if they are equivalent, compares the second elements.
So, it uses the ... |
62,418,096 | 62,418,211 | Error occurred when using thread_local to maintain a concurrent memory buffer | In the following code, I want to create a memory buffer that allows multiple threads to read/write it concurrently. At a time, all threads will read this buffer in parallel, and later they will write to the buffer in parallel. But there will be no read/write operation at the same time.
To do this, I use a vector of sha... | You have a race condition in put caused by new_slab(). When new_slab calls memory_.push_back() the _memory vector may need to resize itself, and if another thread is executing put while the resize is in progress, memory_[index_] might access stale data.
One solution is to protect the _memory vector by locking the mute... |
62,418,293 | 62,418,722 | How to tell if SSL_read has received and processed all the records from single message | Following is the dilemma,
SSL_read, on success returns number of bytes read, SSL_pending is used to tell if the processed record has more that to be read, that means probably buffer provided is not sufficient to contain the record.
SSL_read may return n > 0, but what if this happens when first records has been processe... | SSL_read() returns the number of decrypted bytes returned in the caller's buffer, not the number of bytes received on the connection. This mimics the return value of recv() and read().
SSL_pending() returns the number of decrypted bytes that are still in the SSL's buffer and haven't been read by the caller yet. This w... |
62,418,895 | 62,418,940 | How to show large integer numbers on C++ | I am developing a single code that calculates Fatorial Number on C++.
The code
// Exemple: 5! = 5 x 4 x 3 x 2 x 1 = 120
#include <iostream>
using namespace std;
int main() {
int number, total;
cout << "Calculate fatorial number" << endl;
cout << "-------------------" << endl << endl;
cout << "Type a... | You need to either use an existing library that deals with large numbers, or implement your own. There's many options, gnu multi-precision, boost, etc...
If you choose to implement your own, you'll store digits in something like:
A string "90120304153543643626424262"
A std::vector<int> of digits (base 10)
{9,0,1,2,0,... |
62,419,009 | 62,453,862 | How should I implement a temporarily child object of an existing parent? | I know the question is going to sound weird, so let me start of with the issues:
Problem 1
I'm making a Monopoly game (for which a Monopoly class has been made that has a PlayerList member, containing players), and I had implemented an Auction class. I recently discovered that I have a lot of comparable code in the Auc... | I have thought about using std::shared_ptr<Object> for a while, and I think I have found the solution to the second problem, although it still has the little downside that every member that needs to be modified in child classes, has to be a shared_ptr, even when you wouldn't make it a pointer. See the code below, repre... |
62,419,141 | 62,423,225 | How to test HTTPS requests (SSL) through CURL in gtest? | I am going to send HTTPS requests through curl and would like to test it using gtest. How should I proceed with it?
| Most probably you will need to introduce a wrapper around curl library you use and mock it for the most part (see gmock intro). This will help you to test the interactions with the library itself. Given no HTTPS request will be really performed, the tests will be reliable, fast and small.
Above technique will not help ... |
62,419,213 | 62,419,367 | How do I expose an enum to users of my library in a public header file but also use it internally? | If I am creating a library that exposes one public header file, which may take or return a publicly exposed enum, how would I use that enum internally without also creating a circular dependency in header files?
For example :
Public.h
#include "Internal.h"
namespace PublicFunctions {
enum Access{
READ,
... | An include guard cannot help you because if public.h is included first, the logical case for the library's clients, you will wind up with
// public.h already included so #include "Public.h" is ignored
namespace InternalFunctions {
FileObject GetFileObject(PublicFunctions::Access a);
// PublicFunctions::Acces... |
62,419,256 | 62,419,672 | How can I determine how many AVX registers my processor has? | Currently I'm developing function that counts integral using AVX registers. I want to know if there are enough of them on my computer. How can I find out that?
| Assuming a CPU with AVX at all (i.e. not Pentium/Celeron, even latest-generation):
32-bit mode always has 8 architectural YMM registers. 32-bit mode is mostly obsolete for high-performance computing.
64-bit mode has 16 YMM regs, or with AVX512VL, 32 if you include using EVEX-encoded 256-bit versions of instructions.
I... |
62,419,261 | 62,419,555 | Do store instructions block subsequent instructions on a cache miss? | Let's say we have a processor with two cores (C0 and C1) and a cache line starting at address k that is owned by C0 initially. If C1 issues a store instruction on a 8-byte slot at line k, will that affect the throughput of the following instructions that are being executed on C1?
The intel optimziation manual has the ... | Generally speaking, for a store that is not soon read by subsequent code, the store doesn't directly delay that subsequent code on any modern out-of-order processor, including Intel.
For example:
foo()
*x = y;
bar()
If foo() doesn't modify x or y, and bar doesn't load from *x, the store is independent and may start ex... |
62,419,750 | 62,465,829 | Qt: memcpy failed.. How to copy? | My question today is about Qt and the memcpy() function..
I got a QByteArray i_byte_array containing my raw data that I need. First thing I tried is to copy those data in a char* l_array.
Which gives me:
void blablafunctionblabla(const QByteArray& i_byte_array)
{
char* l_array = (char*)malloc(i_byte_array.size());
... | Actually memcpy does not ignore the null character. I guess the IDE (maybe Qt Creator) ignores the null character so you can't see the entire content of the char string.
If you import the l_array to a QByteArray by the following way:
QByteArray ba = QByteArray::fromRawData(l_array, i_byte_array.size());
You will see t... |
62,419,884 | 62,420,013 | How to force check pointer value | I'm writing simple cycle code which needs check simple custom thread lock, and when this lock is passed thread will continue
static bool* lock;
...
while (*lock);
// TODO: process to the next step
...
but when I'm checking compiled assembly I see the next code
static bool* lock;
...
bool lock_value = *lock;
while (loc... | Short answer: infinite loops without side-effects are Undefined Behaviour. This makes your code formally meaningless, and the compiler is free to assume that Undefined Behaviour never happens. Since while (*lock); is a simply reading a scalar and causing no side-effects, this causes UB, so the compiler goes ahead and d... |
62,419,886 | 62,419,899 | Why is my If statement being ignored in my For loop? | #include <vector>
#include <iostream>
int main() {
std::vector<int> nums = {2,4,3,6,1,9,7};
double evenR = 0;
double oddR = 0;
for (int i = 0; i < nums.size(); i++ ) {
evenR = nums[i]%2;
std::cout << evenR;
if (evenR = 0) {
std::cout << "YAY";
std::cout << nums[i] << " is even!... | C++ uses "==" for checking if something is equal to something else. A single "=" is an assignment. You are assigning evenR to 0, not checking it.
|
62,419,982 | 62,421,307 | What are "blocks" used for in C++ when we have functions and lambdas? | I found this strange construct that apparently comes from C and is adopted into Objective-C and C++ (as an extension). There's even new development for it in clang. I was really surprised when I saw this and I've never seen anyone use this.
According to the specs, it seems like you can declare "blocks" with the synta... | This is Objective-C (or Objective-C++) for a block and is equivalent to lambda's in C++. For example, the block
int (^sqr)(int) = ^(int x) {return x*x};
might look like this in C++:
auto sqr = [](int x) {return x*x;}
clang support both Objective-C and Objective-C++.
|
62,420,186 | 62,422,107 | CopyFile to a custom location, with string conversion problem | I am trying to make this application copy itself to appdata, which requires the USERNAME, which I already have.
But, for some reason, the file doesn't copy to this place. I tried a lot of string conversion to char, but none of them worked for the strcat() and CopyFile() functions.
Here is the code:
char user[UNLEN + 1]... | You are not allocating enough memory for PathChr. You are allocating only 1 char, not Path.length() number of chars. You need to use [] instead of () when calling new, eg:
char *PathChr = new char[Path.length() + 1];
...
delete[] PathChr;
Alternatively, forget using new[], just use the std::string you already created... |
62,420,214 | 62,420,227 | Why doesn't the 'i' increment up through every iteration of the loop? (C++) | I'm new to this method of iteration, why doesn't the 'i' increment up through every iteration of the loop?
The goal of this snippet is to remove duplicates from the sorted array.
int main()
{
vector<int> nums{ 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
int length = 0;
for (int i : nums)
{
if (nums[i] != nums[i + 1])
{
... | i will take the values from the vector, 0, 0, 1, 1, etc ...
It doesn't take on index value (positions)
If you had
vector<int> nums{ 0, 0, 1, 10000, 1, 2, 2, 3, 3, 4 };
You'd get a crash.
|
62,420,566 | 62,420,582 | Is it UB to cast void* param to various types? | void WorkHorse(void* ptr, int tag) {
if (SomeFunction(tag)) {
Foo* foo_ptr = (Foo*)ptr;
// do stuff
} else {
Bar* bar_ptr = (Bar*)ptr;
}
}
I know this is generally a bad design but curious if it's technically UB.
|
Is it UB to cast void* param to various types?
No, casting void* to a pointer to object type is not UB. If it was, then void* would be mostly useless.
However, indirecting through the converted pointer may be UB in some cases; typically when the address doesn't contain an object of appropriate type.
As you pointed ou... |
62,421,234 | 63,572,681 | fold expression and function name lookup | I am learning fold expressions in C++17. I have the following code
#include <iostream>
#include <vector>
namespace io {
template<typename T>
std::istream &operator>>(std::istream &in, std::vector<T> &vec) {
for (auto &x : vec)
in >> x;
return in;
}
template<class... Args> void scan(Args &... args) {
(std::c... | This was a Clang bug. Clang versions 11 and earlier did not properly implement two-phase name lookup for the operator in a fold expression, and would incorrectly perform the first-phase lookup from the lexical scope in which the instantiation of the fold-expression happened to be performed rather than doing the first-p... |
62,421,356 | 62,421,596 | Easy access C++ vector with offset index | I have a bunch of element data, for example 1000 data with the "tag" was started at integer number 9 so the last tag was 1008. I would create a vector that easy enough to access specific tag using vector index,
std::vector<double> element_data(1009)
but if the tag start at higher integer it would produce garbage at 0... | The std::vector is a container that stores elements indexed from 0. If 1000 is the size of your data that is known at compile-time, you may improve the design using std::array instead. That is something that we know without digging into the details of your application.
Let's return to your question. You have an entity ... |
62,421,541 | 62,421,612 | C++ convert string to int | Used stoi() method to convert string to int, but it converts to int even when there is alpahabet.
string str1 = "45";
string str2 = "31337 test";
int myint1 = stoi(str1); // 45
int myint2 = stoi(str2); // 31337
str2 is converted to int, but I don't want this convertion since it has alphabet. If there any way to catc... | You can check the number of characters processed.
string str2 = "31337 test";
std::size_t num;
int myint2 = stoi(str2, &num); // 31337
// ^^^^
// num (the number of characters processed) would be 5
if (num != str2.length()) {
...
}
|
62,421,626 | 62,423,470 | How to add an object into an existing layout in qt? --Solved | I am working on a qt project and I am trying to add an object as a widget into my layout, how can I do that?
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
GLobj obj; //this is the object I want to add and it extends QGLWidget
QWidget *window = new QWidget;
QGridLayou... | The QGridLayout::addWidget method expects a pointer to an instance of a QWidget-derived class, thus if GLobj happens to be something like:
class GLobj : public QWidget
{
...
you can do:
grid->addWidget(&obj);
|
62,421,713 | 62,423,210 | Buffer Allocation With GetModuleFileNameEx | I am currently trying to get the full filepath from my executable by providing a process ID, and this works "fine" in the since that its able to return some of the information needed, however for some reason it becomes corrupted and this can be seen when trying to return it as a plain string: C and if you iterate over ... | First off, the contents of your array are uninitialized if OpenProcess() fails. There is no need to use OpenProcess() on the calling process ID. Use GetCurrentProcess() instead, or simply use GetModuleFileName() instead.
That said, the real problem is not with memory allocation, but rather is that you are mixing ANSI a... |
62,421,821 | 62,428,787 | How to decrese the possibility of the producer acquiring the lock whereas the consumer could not get the lock when using std::condition_variable? | How can I decrease the possibility of the producer(i.e. main thread in the code snippet code below) acquiring the lock whereas the consumer(i.e. wait thread) could not get the lock? It is would be better if you could tell me a method to avoid it. I don't think it is a good idea to use std::thread::sleep_for or std::thr... | You can wait for done completely without a lock, if you make it an atomic variable. This would even make much more sense to me in this case than using a mutex. However, this does not change the whole concept of busy waiting, that is, spinning in a loop until done is set.
Alternatively, you can wait for done to be set w... |
62,421,907 | 62,422,093 | How to initialize vector<unordered_map<*,*>> | Is there a way to do this initialization of my vector of unordered maps in one line?
vector<unordered_map<int,int>> lookup;
for (int i = 0; i < vector_size; i++)
{
unordered_map<int, int> map;
lookup.push_back(map);
}
| vector<unordered_map<int, int>> lookup(vector_size);
Syntax - vector<container or data_type> vector_name(size, initial_value)
|
62,421,921 | 62,423,475 | extract elements from a pointer to pointer to array of structures | I have a problem with a point to a pointer to an array of structures.
I declare and initialize three points to structure which has a member val.
I create a pointer arr to an array of pointer to structure.
Then I create a pointer pa to pointer arr and a pointer pa1 to pa.
I encounter the problem when I try to extrac... | You have to make a diagram, what is stored where and how:
For example:
// Allocated values (they are completely unrelated and may point into different locations):
a1 = 0x11111100;
a2 = 0x22222200;
a3 = 0x33333300;
// Where each of those addresses points to the place in memory with one constructed element of a
// next... |
62,422,503 | 62,422,721 | Is there a C++ structure like a map but instead of key to values I get a handle to a value? | I need an structure kinda like a Map, but I dont care about the key value, only the value correspondent to the key.
On a map, I need to make things like this:
map[1] = "value1"
map[2] = "value2"
It gives me the responsibility to not choose coliding keys. I could solve this by doing:
let handle = randomValue();
map[han... | IIUC, you want a container with the following features:
ability to add a new element and get a numeric handle to it
ability to remove an existing element
You do not need a mapping container here because you have no given key. But you want direct access from the handle. So what you need is a vector. I you never remove... |
62,422,538 | 62,423,564 | Cannot convert from string to template C2664 | I created List (a class with template), its constructor receives a value T. I'm trying to set that type of value in a switch of a class called Menu (also with templates). When I tried to run Menu.run() all the switch options work except for string.
The error is
Error C2664 'List<T>::List(const List<T> &)': cannot c... | In your main function the compiler has to compile all of your code. Even if it will optimise it out later because it can see dataType == 1 the c++ standard says it must generate the code for all the data types first.
You could fix this by using if constexpr so that the compiler only compiles the code that is actually b... |
62,422,918 | 62,423,155 | How to pass struct from c++ to function in c? | I have a C++ file which is like below:
int myNum[10] = {10, 20, 20, 40, 50, 60, 70, 80, 90, 100};
struct rfid
{
int AntennaID;
char *tid;
};
for (int i = 0; i < 10; i++) {
AntennaID = myNum[i];
struct rfid p1 = {AntennaID, tid};
cout << "roll no : " << p1.AntennaID << endl;
cout << "roll no ... |
Make a header that will compile for both C and C++.
// shared.h
typedef struct rfid_
{
int AntennaID;
char *tid;
} rfid;
#if defined __cplusplus
extern "C"
#endif
void passInfo(rfid *p1);
Implement your function in C.
// c.c
#include <stdio.h>
#include "shared.h"
void passInfo(rfid *p1)
{
// whateve... |
62,423,360 | 62,424,195 | How to make traits to accept a parameter pack? | I define some type traits like this:
template <typename T>
struct has_something
{
static constexpr bool value = false;
};
template <>
struct has_something<int>
{
static constexpr bool value = true;
};
template <typename T>
constexpr bool has_something_v = has_something<T>::value;
And a function template wh... | If you want to make the trait accept a parameter pack and it's value be true only when the parameter pack has a single type and that type is int you need to change only little on your code:
#include <iostream>
#include <type_traits>
template <typename...T>
struct has_something : std::false_type {};
template <>
struc... |
62,423,365 | 62,424,185 | Inserting node in Hash table with open addressing [Optimizing the logic] | I am trying to understand a data structure, hash table with open addressing.
I am currently reading on the source code provided by geekforgeeks, but I have a few questions on the code.
Below, is the pasted function for inserting Node from geekforgeeks.
//Function to add key value pair
void insertNode(K key, V val... | The three conditions to have a valid index are:
The object at the index is NULL
OR the object is not NULL, but its key is the same of the one we're inserting
OR the object is not NULL, but its key value is -1
Since the negation of all three conditions occurs, we don't have a valid index, and the loop rolls on.
In lin... |
62,423,493 | 62,423,824 | Mistake on using pointers-to-members in Clang | The following code compiles gcc successfully
template<typename T>
class F {
public:
template<typename V>
static void foo(V T::*) {
p<bool> = nullptr;
}
template<typename V>
static inline V T::* p;
};
struct A;
template class F<A>;
int main() {
}
and clang compilation fails with
<source>:... | The code is valid from a pure language perspective. That is a valid variable template, and the resulting variable is itself of a valid type (a pointer to member). As a matter of fact, Clang complains even without the explicit instantiation.
And to drive the point home, Clang has no problem with this variable template i... |
62,423,981 | 62,435,870 | fmt with Howard Hinnant's date: why "{}" from fmt::to_string? Best practice for fmt and date? | TL;DR: I am implementing custom formatter for fmt and Howard Hinnant's date library. With date::year_month_day d{};, why does fmt::to_string(d) return "{}" while fmt::format("{}", d) works fine, returning "0000-00-00"? Example on godbolt.
I'm using date library and trying to switch from iostreams to fmt. I need to for... | This is an unfortunate effect of the argument-dependent lookup: fmt::to_string calls format which ends up being resolved to date::format instead of fmt::format. The fix is to fully qualify the call to format in fmt::to_string since it depends on a user-defined type.
Update: this has been fixed in https://github.com/fmt... |
62,424,164 | 62,427,330 | QNetworkAccessManager delete later while requests are added | I have one QNetworkAccessManager to handle all my requests.
The manager can receive an action to send a post request at anytime the application is running.
I noticed there is almost a 70s timeout time before a QNetworkReply finishes when there is no internet.
In the constructor of the class I create the manager with:
m... | connect(mgr, &QNetworkAccessManager::destroyed, reply, &QNetworkReply::deleteLater);
QObjects offer the destroyed() signal. So you can connect your managers destroyed() with the open replys deleteLater(). When your manager is destroyed all open replies will be deleted. In case the reply finishes with the manager stil... |
62,424,298 | 62,424,350 | Proper way to print address of character array | So, I have been digging into character array's lately, and I am trying to print the address of each element of a character array.
char a[4] = {'i','c','e','\0'};
for(int i = 0; i < 3; ++i){
cout<<(void*)a[i]<<" ";
cout<<&a[i]<<" ";
cout<<a[i]<<endl;
}
The code above gives me the following output:
0x69 ice i
0x6... |
I am trying to print the address of each element of a character array
(void*)a[i] is converting the element (the char) itself to void*, not the address of the element.
You should get the address of each element as:
cout<<(void*)&a[i]<<" ";
// ^
Or better to use static_cast.
cout<<static_cast<void*>(&a[i])<... |
62,424,509 | 62,424,870 | Success callback Emscripten FETCH API in C++ class | I am working with WebAssembly and try to make an HTTPS request from C++. I have seen the solution of Emscripten FETCH API and tried to use it.
To test it, I created a Test class where I send the request like this :
void Test::sendRequest() {
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
... | You can't use a non-static member function as a callback directly.
However, most callback interfaces have a "user data" field somewhere for communicating back to the originator.
emscripten_fetch_attr_t has a void* userData member where you can store any pointer you want.
This pointer is passed as userData in the argume... |
62,424,749 | 62,425,060 | Overuse of Pragma Pack(1) | What causes padding due to overuse of #pragma pack(1)? What actually happens in backstage?
#pragma pack(1)
typedef struct
{
union
{
uint8_t SAM;
#pragma pack(1)
struct {
uint8_t sm:1;
uint8_t sm1:3 ;
uint8_t sm2 :1 ;
uint... | Your annotated code:
#pragma pack(1)
// from here on the compiler will align fields on 1 byte
typedef struct
{
union
{
uint8_t SAM;
#pragma pack(1)
// there is no use for this pragma on a bit field
// packing was already at 1 byte
struct {
uint8_t sm:1;
... |
62,424,810 | 62,425,092 | Inheritance from inner class | I implemented a binary search tree in C++, and now I'm trying to inherit from it.
The base tree:
#ifndef TREE_HPP
#define TREE_HPP
class tree {
public:
class node {
public:
virtual int foo() { return 1; }
node() = default;
virtual ~node() = default;
};
node* root;
tree() : ... | Welcome to StackOverflow!
What virtual methods do is enable you to call your method based on the actual class instantiated instead of the type of the pointer.
So in your case, root->foo() would call the method based on the actual class, and not always call the node implementation.
To call the derivedNode implementation... |
62,425,017 | 62,425,501 | How to register Qt C++ object to use it in QML | I try to register ColorsSource *pSource object to use it in QML but I get erreor in string:
"QQmlContext *context = myObject->rootContext();"
undefined reference to __imp__ZNK12QQuickWidget11rootContextEv
main.cpp
#include "ColorsSource.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQuickW... | You are missing the quickwidgets Qt module. Thats why it cannot find these Symbols. If you use qmake, add QT += quickwidgets to your pro file.
But that won't be your Problem. QQuickWidgets are widgets to display some QQuick code, to be used in a Widgets application. But as you use a QQmlApplicationEngine, you are worki... |
62,425,019 | 62,426,620 | address changes when i assign to a pointer a pointer from a derived class in C++ | I'm a brand new in C++ and I'm experimenting with Polymorphism. I have the following code:
#include <iostream>
class Base1
{
protected:
int b1;
public:
int m() { return 1; }
};
class Base2
{
protected:
int b2;
public:
int n() { return 2; }
};
class Der : public Base1, public Base2
{
protected:
... | The sample of OP (simplified a bit)
struct Base1 {
int b1;
};
struct Base2 {
int b2;
};
struct Der: Base1, Base2 { };
may result in the following memory layout:
// start of Der
// start of Base1
0000: Base1::b1 // type int
// start of Base2
0004: Base2::b2 // type int
So, when struct Der is instanced part of it... |
62,425,049 | 62,425,316 | I cannot seem to modify the framebuffer | I am trying to modify the framebuffer on Linux. I am running the program through a virtual terminal (tty). I cannot seem to modify the pixel I want. Here is my code:
#include <stdio.h>
unsigned char buffer[4 * 1366 * 768];
const int framewidth = 1366;
void placepixel(int x, int y, int r, int g, int b, int a){
... | The problem appears it would seem, from a failure to account for 4 bytes of buffer-space for each pixel. Consider the following desk-check
pixel(0,0)
(framewidth*y) + x + 0 -> 0
(framewidth*y) + x + 1 -> 1
(framewidth*y) + x + 2 -> 2
(framewidth*y) + x + 3 -> 3
pixel(1,0)
(framewidth*y) + x + 0 ->... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.