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 |
|---|---|---|---|---|
64,943,682 | 64,943,873 | Assert that type is unsigned integer or enum type with maximal size | I'm trying to make it possible to write the following to statically assert that a variables type is an unsigned integer with size less than or equal to four bytes.
I started with the following:
template<typename T>
using is_uint_le32_t = std::integral_constant<
bool,
std::is_integral<T>::value
&& std::is_unsigned... | We can use std::condtional to either get an enum type's underlying type or leave any other type alone:
#include <type_traits>
namespace std_compat {
#if __cplusplus >= 202002L
using ::std::type_identity;
#else
template <typename T>
struct type_identity {
using type = T;
};
#endif
}
template <t... |
64,944,751 | 64,944,953 | If statement is working, but return inside of if statement is not. What am I doing wrong? | I'm working on HackerRank's problem "Comparing Two Linked Lists". My function that compares the two Linked Lists is below:
bool compare_lists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
if(head1 != nullptr && head2 != nullptr){
if(head1->data != head2->data){
return 0;
}
... | Try to answer this question: What does the method return when head1 == head2 (1) and head1->data == head2->data (2) and neither of them is nullptr (3) ?
bool compare_lists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
//if(head1 != nullptr && head2 != nullptr){
if (true) { // neither of them is n... |
64,944,804 | 64,945,470 | C++:Adding an element to a tuple | I am going through the custom implementation for tuples , which is described in C++ template second edition.
I need a help to understand how the pushFront actually work. What are the steps that compiler does in order to put the new element in the start of the tuple
template <typename... Elements>
class Typelist
{
};
t... | I scratched my head so much reading that example that I went and hunted down the book. The book is not full of incomprehensible examples, but they're spread out and incrementally implemented. Only a few are shown in the OP's question.
The first part involving is showing how to use partial specialization to push a type ... |
64,944,930 | 64,993,248 | How to call changeValue of QSpinBox only when user changed value | This is my QSpinBox slot method:
void MainWindow::on_sbObjectSize_valueChanged(int arg1)
{
/*do something*/;
}
I need to distinguish when this value was changed by user (by typing value or click on arrows) and when it was changed from the code (eg. using ui->sbObjectSize->setValue(1)).
Is it possible to do this ... | Yes, you can do it by checking the value returned from sender(). Let's say you have a button in your UI in your main window and clicking on the button changes the spin box value, then sender()'s value will be the address of the button pointer. qDebug() is really nice, since it will output other information available in... |
64,945,079 | 64,951,652 | Calculating a hash value for composite classes | I have a class structure like the following:
class A
{
int x,y,z;
int w[4];
};
bool operator==(const A& a1, const A& a2)
{
for (int i=0; i<4; ++i)
if (a1.w[i] != a2.w[i])
return false;
return (a1.x == a2.x && a1.y == a2.y && a1.z == a2.z)
}
class B
{
int q,p;
vector<A> a;... |
Is there a performant way to turn my integer members into suited input
First, let's try something naive and readable, and see if it's good enough.
Here is an incremental version of the algorithm:
struct Djb2Hash {
unsigned int hash = 5381;
void Add(char c) {
hash = hash * 33 + c;
}
};
Then add some more... |
64,945,082 | 64,947,555 | Correct use of explicit template instantiation for functions? | I'm currently on an exercise for which I'm supposed to use template matrices as paramters in all my functions and force the needed data types in a header. I don't really know how to do it yet though.
There's a header with the following function and a second function with the same syntax (and also the same template name... | As per parktomatomi's comment adding
template <typename multityp>
in front of the body declaration did the trick:
template <typename multityp> void matsum ( multityp **matrix1, multityp **matrix2, multityp **ergebnis, int zeilen, int spalten ){
//Does stuff
}
|
64,946,230 | 64,946,280 | Initializing an int array with less values then that are declared, will it only add 0 as values? | I was reading up on C++, and the site says that if you initialize an int array with less values then declared as such
int x[6] = {19, 10, 8};
that it replaces the rest of the values with a random number. "In such cases, the compiler assigns random values to the remaining places. Oftentimes, this random value is simply... | The site is horribly wrong!
(in this point, I don't know the rest, but one has to say it clear ;)
Their example:
// store only 3 elements in the array
int x[6] = {19, 10, 8};
Here, the array x has a size of 6. However, we have initialized it with only 3 elements.
In such cases, the compiler assigns random values to t... |
64,946,320 | 64,946,744 | Function that only accepts enumeration types | Man, I can't stand this damn templates no mo'
So suppose I have this function...
void sort(vector<int>& vec)
{
// stuff
}
How can I make that function accept vectors of all enumeration types without overloading it 10 goddamn times?
I don't know much about templates but was thinking about doing something like this.... | Just if you use fresh C++ (what I recommend if possible). There is a working example using concepts (c++20). Just tested at gcc 10
#include <type_traits>
#include <vector>
#include <concepts>
template<typename T> requires std::is_enum<T>::value
void sort(std::vector<T> & vec)
{
// stuff
}
int main()
{
... |
64,946,336 | 64,946,539 | Assign a string to a string return type function without copying | I want to learn how to write efficiently(who doesn't), and I wanted my example to involve familiar and simple concepts. I'm actually using Qt, but I hope it is not a problem, since the question is quite general. I have a function that goes like this:
QString elide(const QString& text, int length)
{
if (text.length(... | C++ does not guarantee copy elision for the way elide() uses return. This can be discussed in more detail, but it will become clear that this is going to be irrelevant. There's another, more fundamental issue at play. The bottom line is that you have no guarantee that returning from elide() elides the implicit copy, he... |
64,946,917 | 64,947,901 | List in C++ Standard Template Library (STL). I made the following program and I don't know how to make a function to print the list | #include <iostream>
#include <list>
#include <iterator>
using namespace std;
class Profesor
{
public:
string nume, departament;
int grad, vechime;
Profesor(string n, string d, int g, int v);
};
Profesor::Profesor(string n, string d, int g, in... | Add a function to Profesor to output it's current variables:
void output() const {
cout << " * nume: " << nume << endl;
cout << " * departament: " << departament << endl;
cout << " * grad: " << grad << endl;
cout << " * vechime: " << vechime << endl;
}
Create a funct... |
64,947,288 | 64,947,337 | Inheritance construcor | I tried to make a constructor of derieved class. I've got one error which I can't understand. I mean I've a derieved class which constructor looks like: header file
Person(string surname_, string name_, int day_, int mounth_, int year_) :date(day_, mounth_, year_);
And .cpp
Person::Person(string surname_, string name_... | The declaration of the constructor must end with a ; right where you put the :. The part that begins with : belongs in the definition only.
|
64,947,299 | 64,947,858 | Immediately calling destructor after setting in the fluent interface in C++ | I want to create a class only for setting params for function.
I'm using a fluent interface for that.
Some function returns the object to setting params and real code will execute in the destructor of this object.
First of all, is it a good idea? Is this a common way to improve code readability when I have a lot of par... | In general the destructor is a good place if you want force that something happens even if an exception occured (but be aware that destructros are declared noexcept(true) by default).
I personally use it for "finally" blocks (with noexcept(false)). But usually in C++ you don't need finally because of RAII.
I think you ... |
64,948,325 | 65,151,106 | Undefined symbols for architecture x86_64 when writing unit tests with gtest and clang 12 | I'm trying to add unit tests for some functions defined in this file:
src/server/game/Miscellaneous/Formulas.h
My test file looks like this:
#include "gtest/gtest.h"
#include "Formulas.h"
#include "SharedDefines.h"
using namespace acore::Honor;
using namespace acore::XP;
TEST(FormulasTest, hk_honor_at_level)
{
... | You can solve by adding:
LoginDatabaseWorkerPool LoginDatabase;
to your FormulaTest.cpp.
|
64,948,521 | 64,948,662 | Move, Copy assignment, Copy constructor seems to work without definition | I am working on a simple matrix template class for practice purposes, I have defined my constructor and destructor but on testing the class, I found out that Move and copy operations works without any flaws and I didn't define them. I really do not understand what's going and I don't trust what is happening.
#ifndef MA... | If you don't declare a special member function, then sometimes the compiler implicitly declares and/or defines the functions.
See the table in this answer for more detail.
Your code causes undefined behaviour in several ways; one possible upshot of undefined behaviour is appearing to work correctly -- for now. You shou... |
64,948,645 | 64,950,478 | ERROR while debugging SFML code in Visual Studio Code | I made a project that is using SFML library on linux, it's working pretty fine. I start it by launching this script exec.sh:
g++ -c main.cpp -I/usr/include
g++ main.o -o sfml-app -L/usr/lib -lsfml-graphics -lsfml-window -lsfml-system
export LD_LIBRARY_PATH=/usr/lib && ./sfml-app
And here is the code de in the main.cpp... | Try installing library to your system path.
For Arch based Linux -
sudo pacman -S sfml
For Debian based Linux -
sudo apt-get install sfml-dev
And just use following g++ command -
g++ -c main.cpp -o main.o
g++ main.o -o sfml-app -lsfml-graphics -lsfml-window -lsfml-system
It is better to use a IDE for it. You can use... |
64,948,778 | 64,949,748 | Namespace and classes with its methods definitions in single header file.How can use it in more than one header or cpp file? | Actually, It is working fine when I include in single cpp file, however,on including more than one file, it's giving already defined in other obj. This file is quite large and I have download for my project.How can I use this file in more than one cpp.
I am using visual studio 2019.
Error:
Severity Code Descripti... | You need to mark your function definitions inline. That's what the inline keyword is for: it allows a function or object to be defined in multiple translation units so long as all of the definitions are identical. Remember that including a header file does nothing but paste the text from that header into another file... |
64,949,135 | 64,949,331 | spurious "containment" in std::set of pointers | A set of pointers is reporting that it "contains" a brand-new object, even though this object was just created, and has a memory address which differs from those already in the set.
#include <iostream>
#include <set>
#include <vector>
using namespace std;
class foo {
public:
int x;
foo(int x) : x(x) {}
};
... | Thanks all for the comments. Here is a solution that achieves the desired behavior:
int main() {
set<foo*, bool (*)(foo*, foo*)> my_set([](foo* left, foo* right) {
if (left->x == right->x)
return std::less<foo*>{}(left, right);
return left->x < right->x;
});
// ....
return 0;... |
64,949,453 | 64,959,330 | std::codecvt do_out skipping characters after 1:N conversions | I've tried to write an automatic indenter, however - it's skipping characters when it added new characters to the stream. I've tried debugging it and verified that from_next and to_next as well as from and to are working correctly.
Surely I've missed something in the specs but here is my code, maybe you an help me:
v... | After some more digging I found the solution to my problem. I got a detailed explanation of std::codecvt from this website: http://stdcxx.apache.org/doc/stdlibref/codecvt.html
It turned out, that I forgot to override these two methods:
virtual int do_length(state_type& state, const extern_type *from, const extern_typ... |
64,949,975 | 64,950,012 | Find minimum and maximum values input by the user without using an array | I know in theory that I would, for the maximum, replace the current value with the new integer that the user inputs if it is higher than the latter, and vice versa for the minimum, but I can't how to make this happen with my code. Essentially I am asking if there is a way for me to compare two integers without storing ... | Just compare and update if it should be updated:
if (maxValue < 0 || intVal > maxValue) maxValue = intVal;
if (minValue < 0 || intVal < minValue) minValue = intVal;
detail:
if ( // if
maxValue < 0 // there are no value yet (this is the first value)
|| // or
intVal > maxValue... |
64,950,098 | 64,950,197 | How to create a custom shared_ptr? | Say I have a library SXY which gives me a picture from a file:
Picture * pic;
pic=get_picture("directory/file")
And I share it over multiple functions. But I want to call picture_close(pic) to dellocate it only when I am done and all these functions went out of a scope. shared_ptr already does that but if I do:
share... | I think you're asking how to provide custom-deleter capabilities to a std::shared_ptr, and then utilize that by attaching your pre-allocated point therein. The most common use of this would be some pre-existing handle-type APIs that require such workflows.
One way to do it is like the following code. I've provided mock... |
64,950,200 | 64,954,690 | User defined Class elements and their manipulation | i am needing to create a class with elements for a savings account, i have to ask the user for account type, name, ID, balance, and closure percentage. I then have to display what was just inputted, and then at the end call an imbedded class function to calculate the closure percentage via the inputted percentage and t... | When you write SavingsAccount SA or SavingsAccount AccountType, Name, ID, Balance, CP_percent those both are creating new SavingsAccount objects. If you want to act on the one object you should not be creating new ones.
"member function GetInitialValues", currently your function is not a member function. Make it a memb... |
64,950,254 | 64,950,279 | How to fix: unable to get index of element in a set | If I have a set of strings:
std::set<string> my_set;
And I want to find the index of an element in this,
I did:
auto it = std::find(my_set.begin(), my_set.end(), string_to_find);
auto index = std::distance(my_set.begin(), it);
for ( auto s : store){
if(s.name == my_set[index]){ //line causing error
s.item ... | As the error message suggests, std::set doesn't have operator[].
You have already got an iterator, so you can use that to access an element.
auto it = std::find(my_set.begin(), my_set.end(), string_to_find);
if (it != my_set.end()){
for (auto s : store){
if(s.name == *it){
s.item += 1;
}... |
64,950,479 | 64,950,677 | c++ print shapes in the console (cmd) | I’m building a maze game in C++ and I’m trying to use shapes to identify characters in the game i.e. walls as squares, triangles as enemies and a star shape as the player. How can I print such elements in the console cmd? I have been researching a lot on http://msdn.microsoft.com/en-us/library/windows/desktop/ms682073%... | There are several solutions to this problem, each with its own drawbacks and advantages.
Emoji (or more precisely Unicode)
This is my recommendation for simple games and shapes as it is the most simple to implement and relies on the underlying console to do the heavy lifting. Also how the other program was most likely... |
64,950,532 | 64,950,571 | Recursive function showing segmentation issue C++ | This code is for recursive function practice. When I run the code, it stops at the "POWER" cout line, then my compiler shows a segmentation error. The function that follows the POWER line is supposed to recursively raise number "a" to the power of number "b". I'm not sure how to fix this, can anyone help?
#include <ios... | The issue is quite straight forward, you are doing the recPower function with b. In the function, if b is not 0, you call recPower with an unmodified value of b (whilst ever modifying a). This will always end up with infinite recursion which is going to overflow your stack.
A solution could be:
int recPower(double a, i... |
64,950,675 | 64,950,692 | Locally compiled c++ code is improperly looping | The following never terminates on my system.
#include <iostream>
using namespace std;
int main(){
int solutions[1000][4] = {};
for(int a=0; 3*a<=1000; a++){
for(int b=0; 5*b<=1000; b++){
for(int c=0; 7*c<=1000; c++){
cout << "enter" << "\t" << a << "\t" << b << "\t" <... | When a = 0, b = 4, c = 140, 3*a+5*b+7*c becomes 1000 and write to out-of-bounds solution[1000] happens. It seems this out-of-bound write happened to break the loop counter.
Allocate one more element to avoid this out-of-bounds write.
int solutions[1001][4] = {};
|
64,951,059 | 64,951,100 | X86 architecture - Set Vector size with unsigned long long | When I am trying to set vector size with unsigned long long in x86 architecture, I am seeing below error:
unsigned long long sz;
vec.resize(sz);
error C4244: 'argument': conversion from 'unsigned __int64' to 'const
unsigned int', possible loss of data
Why is this error? what is the behavior of unsigned long long in ... | Use size_t sz like a normal person, that's the arg type std::vector::resize(size_t) expects, so using the same type will mean there's no implicit conversion and thus no narrowing.
unsigned long long is a 64-bit type, but size_t is only 32-bit, in 32-bit code.
You can't have a std::vector larger than SIZE_MAX, so it's ... |
64,951,115 | 64,951,134 | How to get set of character of string in same order as in parent string in C++ | I have a string and want to remove duplicates from it, but I want it in same order. std::set or std::unordered_set does not seem to help. I there any DS or have to tackle this manually? Example:-
"ddbbccaa" should be "dbca".
|
iterate over the input string
add characters to result string when you haven't seen the character before
#include <iostream>
#include <string>
#include <unordered_set>
std::string removeDuplicates(const std::string& str) {
std::string result;
std::unordered_set<char> seen;
for (char c : str) {
if... |
64,951,373 | 64,953,070 | group 4 numbers into a 4 digit number in C++ | How to group num1num2num3num4 into a number and prime1prime2prime3prime4 into a number to make sure their combination is not identical??
srand(time(NULL));
int num1 = 2 * (rand() % 5) + 1, num2 = 2 * (rand() % 5) + 1, num3 = 2 * (rand() % 5) + 1, num4 = 2 * (rand() % 5) + 1;//odd number
int prime1 = 2 * (rand()... | Is it what you're looking for ?
int fourDigits1 = num1 + num2 * 10 + num3 * 100 + num4 * 1000;
int fourDigits2 = prime1 + prime2 * 10 + prime3 * 100 + prime4 * 1000;
std::cout << fourDigits1 << " ";
std::cout << fourDigits2 << " ";
|
64,951,637 | 64,952,057 | Which operators should I implement in my class? | I have created my own class like this:
template<class T>
class ball
{
T size;
T price;
};
Now I want to support comparing two balls only according to the first value size in this case should I implement all those operators for ball class??
==, !=, >=, <=, >, <
This doesn't sound efficient or correct.
|
Which operators should I implement in my class?
In general, at minimum you should implement those operators which you use. And the ones that are required by concepts that you need the class to fulfill.
If you want the class to be equality comparable, then ideal design is to also let the class be comparable using oper... |
64,951,658 | 64,951,880 | I/O Prioritization of Windows OS | I was studying Jeffrey Richter Book (Windows via C/C++). In one section, he is talking about I/O prioritization. I know what is prioritization and what are priority class, priority level, and also a base priority now.
I know, I can change the priority of processes and threads with SetPriorityClass and SetThreadPriority... | As noted in that paper, it's up to the I/O device driver to handle priority based on the thread priority, and at the time of that paper, there are only two levels, normal and background, which a device driver may ignore.
A device driver could implement the two levels of priority with two I/O request queues, one for nor... |
64,951,700 | 64,951,735 | C++ re-enable the default c'tor? | How may I re-enable the default c'tor if I wrote one of my own?
I know that writing a c'tor will disable the default one
| You might implement it as default (or with custom implementation if needed):
struct C
{
explicit C(int) {} // Disable default constructor
C() = default; // re-enable it :)
};
|
64,951,914 | 64,952,432 | ESP32 attempt reconnect to when network drops without halting loop (Arduino) | I have an ESP 32 collect data from a moisture sensor, which it then serves on our network. Our WiFi turns off between 1am and 6 am (because no one is using it). The ESP does not automatically try to reconnect, so it gathered data all night which I straight up can not access now.
For obvious reasons I do not want it to ... | Given that you've tagged esp8266 wifi, I'm assuming you're using that library. If so, then wifi.begin will not block execution. The library sets autoreconnect by default, so it'll automatically reconnect to the last access point when available. Any client functions will simply return an error code while disconnected. I... |
64,952,234 | 64,952,418 | Display() resets the entire array C++ | I tried creating a hash map storing its inputs as linked list nodes using separated chaining. The first display function gives a desirable output, but the next one resets the entire array to empty nullptr. I used the same class object so shouldn't it give the same result each time? Was it because of the destructor some... | Make all member functions that are not supposed to change the object itself const. This ensures that the function can be used when the object is used in a const context and will also enable the compiler to help you if you make a mistake. It will give you compilation errors if you try modifying the object in the functio... |
64,952,412 | 64,952,435 | Infinite recursion with std::move | I have a class that mimicks a std::vector.
For this, I want to have a function push_back that accepts both an lvalue and a rvalue.
void push_back(const T& obj) {
push_back(std::move(obj));
}
void push_back(T&& obj) {
buffer[numElements] = obj;
numElements = numElements+1>=Sz-1 ? Sz-... | Issue is that, in
void push_back(const T& obj) {
push_back(std::move(obj));
}
you got const T&& with std::move.
So only viable candidate is void push_back(const T&), so infinite recursive call.
|
64,952,636 | 64,952,671 | CMAKE GLFW linking problems | I wanto add glfw dependency by cmake in CLion but i get weird error, this is the CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(hello_gl)
set(CMAKE_CXX_STANDARD 14)
find_package(glfw3 3.3 REQUIRED)
target_link_libraries(hello_gl glfw)
add_executable(hello_gl main.cpp)
CMake Error at CMakeLists.txt:8 ... | It worked when I tried to link glfw lib after adding the executable
cmake_minimum_required(VERSION 3.17)
project(hello_gl)
set(CMAKE_CXX_STANDARD 14)
add_executable(hello_gl main.cpp)
find_package(glfw3 3.3 REQUIRED)
target_link_libraries(hello_gl glfw)
Here is the right CMakeLists.txt
|
64,952,705 | 64,953,290 | Comparison between void pointers in C++ | What's the size of the pointed memory by a void pointer?
In the example below, I'm comparing two void pointer that are pointing to the same "raw data" but with different type so different size...how it can works? Is it linked to the == operator?
#include <iostream>
using namespace std;
int main()
{
char a = 'a';
... |
I'm comparing two void pointer that are pointing to the same "raw data" but with different type so different size...how it can works? Is it linked to the == operator?
That is not exactly what you are doing. You are interpreting char and int values as pointers to void. Size does not matter at all in this case.
You are... |
64,952,813 | 64,993,212 | Express Vector and orientation in a different referencial in C++ with Eigen | Let's say I have three referencials (A,B and C)
I know the following values:
the position of B in A (as an Eigen::Vector3d)
the orientation of B in A (as an Eigen::Quaterniond)
the position of C in B (as an Eigen::Vector3d)
the orientation of C in B (as an Eigen::Quaterniond)
How can I find the position and the orie... | I answer my own question with the following code as an example:
Eigen::Affine3d B2A = Eigen::Affine3d::Identity();
B2A.translation() << 2 , -1 , 1;
B2A.linear() << std::sqrt(2)/2, 0, std::sqrt(2)/2,
-std::sqrt(2)/2, 0, std::sqrt(2)/2,
0 , -1, 0;
Eigen::Affine3d C... |
64,952,858 | 64,952,945 | C++ variadic templates: elegant way of listing all array elements depending on variadic template size | Is there some elegant way to express a function call depending on some n which can be derived from template arguments
f(my_array[0], ... , my_array[n-1]);
inside a class template looking like this?:
template <int... numbers>
class Abraham {
static constexpr std::size_t n = sizeof...(numbers);
some_type my_array[... | The standard library has std::index_sequence for this kind of thing
template <size_t... Is>
void foo(std::index_sequence<Is...>) {
f(my_array[Is]...);
}
void foo() {
foo(std::make_index_sequence<n>{});
}
Demo: https://godbolt.org/z/zhbGdb
|
64,953,179 | 64,953,341 | How do I delegate this constructor? | For an c++ assignment I need to work with a Point class and with that Point class I need to make a Triangle class.
I used the following constructors for the Point class:
//constructor 1
Point()
{
x = 0;
y = 0;
}
//constructor 2
Point(double i, double j)
{
x = i;
y = j;
}
My first constructor for th... | Here's a slightly refactored version of your code that reflects more modern C++ practice (since 2011):
struct Point {
Point() = default;
Point(double i, double j) : x(i), y(j) {}
double x = 0;
double y = 0;
};
struct Triangle {
Triangle() = default;
Triangle(Point i, Point j, Point k) : a(i), ... |
64,953,181 | 64,953,355 | Combination of objects in c++ | I want to generate combination of vectors of a vectors of vectors.
For ex: if
std::vector<std::vector<int>> arr = {{1,2},{1,3},{1,4},{1,5}}
Comb(arr, 2) shall return:
{
{{1,2},{1,3}},{{1,2},{1,4}}, {{1,2},{1,5}}, {{1,3},{1,4}}, {{1,3},{1,5}}, {{1,4},{1,5}}
}
(i.e, considering vectors as objects that needs to be combi... | std::vector<std::vector<std::vector<int>>> Combinations::combs(std::vector<std::vector<int>> const &vecs, int r) {
std::vector<bool> v(vecs.size());
std::fill(v.end() - r, v.end(), true);
std::vector<std::vector<std::vector<int>>> sol;
do {
std::vector<std::vector<int>> row;
for (int i =... |
64,953,702 | 64,953,756 | How to have a timer in main.cpp in qt creator to update the GUI when a button is clicked? | I am creating a laundry machine simulation with my team for school. I have simulation.cpp where I have functions to control the GUI and main.cpp where I only call one Work() function which is supposed to check whether the user has clicked on a button (e.g. adding coins). There are many classes and interfaces in between... | You can "connect" to Events. Qt will enter the event loop on exec() and call the connected functions when events occur.
You already did that on your timer. You just call the TimerSlot() whenever the timer fires.
Your problem is just the accessibility of your variables. Right now, you cannot access "dr" to call "dr->Wor... |
64,953,708 | 64,954,736 | write a steam to disk in c++ in chunks | I am quite new to the C++ world, and I am trying to write a file stream to a disk.I am able to do the following:
const Aws::String objectKey2("filename.tar");
Aws::S3::S3Client s3_client2;
Aws::S3::Model::GetObjectRequest object_request2;
object_request2.SetBucket(bucket_name);
object_request2.SetKey(objectKe... | Given the following...
auto &retrieved_file2 = get_object_outcome2.GetResult().GetBody();
retrieved_file2 is actually of type Aws::IOStream & with Aws::IOStream being typedef'd via...
typedef std::basic_iostream<char, std::char_traits<char>> Aws::IOStream;
Hence, you can't simply cast a pointer to retrieved_file2 to ... |
64,953,932 | 64,954,201 | Template type paremeter not expanding as desired | I was experimenting on c++ TMP when I noticed how powerful templates can be.
But at some point I wondered why is the following code invalid yet it uses variadic template type expansion(1). When non-type variadic expansion works fine(2). The diviation doesn't make sense as in both the expanded parameters will not be usa... | As max66's comment said, option 3 likely won't have any runtime overhead. But you could do this if you wanted something cleaner:
template<typename... T>
auto initAll2(int forAll){
std::array a={std::conditional_t<true, int, T>{ forAll }...};
}
|
64,954,163 | 64,963,227 | Double braces required for list-initialization of container std::array | List-initialization of containers of user-defined types does not behave as I would expect.
See this snippet:
#include <array>
struct A {
char C;
int s;
};
int main(int argc, char * argv[]) {
A x = {'x'}, y = {'y'};
std::array<int, 2> i = {1, 2}; // Ok
std::array<A, 2> a = {x, y}; // Ok
//std... | Braces, nested however deeply, are matched against the structure of the object being initialized before considering any type information. Since std::array<T,N> must contain a true T[N] (rather than be one), the structure is that there is one object inside the array—that is, the array. Two opening braces are therefore... |
64,954,391 | 64,954,483 | string with embedded null characters | Is there any way that I can use istringstream to read strings with embedded null characters? For example, if I have a char array "125 320 512 750 333\0 xyz". Is there any way that I could get "xyz" after the null character?
#include <iostream>
#include <sstream>
using namespace std;
int main() {
std::string strin... | Just properly initialize string with the proper size of the char array. The rest will follow naturally.
#include <sstream>
#include <string>
#include <cstring>
#include <iostream>
#include <iomanip>
int main() {
const char array[] = "125 320 512 750 333\0 xyz";
// to get the string after the null, just add str... |
64,954,936 | 64,955,842 | MSVC: C++20 modules that import each other fail to compile | Support for C++20 modules has been recently added in MSVC 16.8. If I'm not mistaken, one of the advantages of using modules is that circular import dependencies are now supported. However, the following test project still fails to compile in the latest version of the Microsoft compiler.
computer.ixx
export module compu... |
If I'm not mistaken, one of the advantages of using modules is that circular import dependencies are now supported.
I am not aware of any version of module proposals, standards, or implementations that has ever supported circular dependencies. In pretty much every version of modules as a concept, going back to even p... |
64,954,991 | 64,955,719 | C++ Type Traits if_v (automatic type deduction + ensure same type) | Consider the following code
#include <type_traits>
template<bool Test, class T, T val1, T val2>
constexpr T if_v = std::conditional_t<Test,
std::integral_constant<T, val1>,
std::integral_constant<T, val2>>::value;
int main()
{
constexpr... |
I'd also like to ensure that both input values are of the same type. But I am not sure how to achieve this while using auto.
What about using SFINAE ?
I mean
template <bool Test, auto v1, auto v2,
std::enable_if_t<std::is_same_v<decltype(v1), decltype(v2)>, int> = 0>
constexpr auto if_v = std::conditional_t... |
64,955,049 | 64,955,765 | C++ template specialization and function returned value | How would I specialize the getValue() function in the following example to return a value based on a type? How to achieve this in the class definition? Is it possible?
template <typename Type>
class Abc
{
public:
Type init;
Abc() : init(getValue()) {}
private:
template<> static uint8_t g... | You can use std::is_same to write a non-templated function that returns a value depending on the template parameter of the class:
template <typename Type>
class Abc
{
...
static Type getValue() {
if (std::is_same<Type, std::uint8_t>::value) {
return 123;
} else if (std::is_same<Type... |
64,955,301 | 64,955,404 | How to redo an action indefinitely if condition is not met? | So, here's my code:
#include <conio.h>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int n;
int a[10];
int main()
{
cout<<"Insert amount of data\n";
cin>>n;
for (int i=0; i < n; i++){
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
if (a[i]<1 || a[i]>3)... | You have mastered for loops that uses a condition already, so lets add a do-while-loop loop
Instead of:
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
You could do:
do {
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
} while(a[i] < 1 || a[i] > 3);
You chould also add error checking. If the user closes the... |
64,955,602 | 64,956,062 | ofstream file does not write | I tried to write my own method to save a Eigen::MatrixXd object in a textfile. However, the file is empty after running this method. While debugging, I saw that the file does not open as I want. Can anyone tell me why?
#include<Eigen\Dense>
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
vo... | I had a typo a for loop should have looked like that
for( int i = 0; i < m; i++){}
I did not think of it as my compiler did not give me an error.
|
64,955,776 | 64,962,093 | Is it legal to define a hidden friend in an explicit specialization of an otherwise non-defined member class of a class template? | The rules for legal placement of explicit specializations as per [temp.expl.spec] are not entirely easy to grasp, particularly when mixing with hidden friends, so as to avoid the immolation[temp.expl.spec]/8 of my specializations and friend functions I wish a second opinion(1) on the following:
Is it legal to define, ... | Yes, an explicit specialization of a templated class (which includes class templates and member classes of class templates) is a class, and so multiple definitions are allowed under the usual circumstances. Those definitions are treated as if there were but one in the program, so f is OK as well. (It’s not clear that... |
64,956,088 | 64,956,227 | VisualStudio - Fatal error LNK1168: cannot open myfile.exe for writing | Sometime, while I try to compile my project, VisualStudio show me this error:
1>LINK : fatal error LNK1168: cannot open C:\Path\myfile.exe for writing
and It not allowes me to compile the project.
It seems that myfile.exe is open and running in background yet, although I closed it. I opened Win TaskManager but the fi... | I had this error already many times. Though your myfile.exe is not shown in TaskManager, It is present in background yet. If you open the cmd as administator and type:
tasklist | FIND "myfile.exe"
You can see your process running.
So at this point type the command:
taskkill /IM myfile.exe /F
in order to force the p... |
64,956,164 | 64,959,158 | RegCreateKeyEx succeeding, but no key added | I am trying to get into C++ programming on Windows for reverse engineering purpose, and I am stuck trying to had a Windows registry key. The functions RegCreateKey and RegSetValueEx are returning ERROR_SUCCESS, but the key is missing when checking the registry.
Here is the code:
void AddRunKey() {
wchar_t subkey[51... | I see several mistakes in your code.
You need to escape the \ characters in your file path.
You misspelled CurentVersion in the key path. It needs to be CurrentVersion instead.
You are calling RegSetValueEx() and RegCloseKey() unconditionally whether RegCreateKeyEx() succeeds or fails.
You need to specify the value siz... |
64,956,422 | 64,956,470 | Calculating sum formula in c++ | I am having trouble rewriting this question into c++. This is what I've came up so far. I think I am missunderstanding the question. What am I doing wrong?
Calculating sum formula:
double sum(double n) {
double formula = (n/n+1);
for(int i=0; i<n; i++) {
formula += i;
}
return formula;
}
in... | This one should works
double sum(double n) {
double formula = 0;
for(int i=1; i<=n; i++)
formula += double(i)/double((i+1));
return formula;
}
|
64,956,682 | 64,956,713 | Is a parameter type with `T&&` in it and `T` deduced always a universal reference? | With reference to
template<typename T>
void fun(ParamType param); // ParamType is some form of T, e.g. T, T&, T const, ...
fun(expr); // expr is an expression
I know that && "somewhere" in ParamType is not enough for ParamType to be a universal reference, for instance ParamType = std::vector<T>&& is an rvalue referen... |
what are the requirements on the "form" of ParamType for it to be a forwarding reference?.
From the standard (latest draft):
[temp.deduct.call] A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template
Is a parameter type ... |
64,956,946 | 64,957,894 | Unable to disable System restore point | DWORD Val = 0;
HKEY dwo;
RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Policies\\Microsoft\\Windows NT\\SystemRestore", 0, KEY_ALL_ACCESS, &dwo);
RegSetValueEx(dwo, "TurnOffSystemRestore", 0, REG_DWORD, (LPBYTE)&Val, sizeof(DWORD));
RegCloseKey(dwo);
Hello, I want to disable System restore but I can't do that and
I thin... | Update:
DWORD Val = 1; //set the value to 0 to enable
HKEY dwo;
RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Policies\\Microsoft\\Windows NT\\SystemRestore", 0, KEY_ALL_ACCESS, &dwo);
RegSetValueEx(dwo, "DisableSR", 0, REG_DWORD, (LPBYTE)&Val, sizeof(DWORD));
RegCloseKey(dwo);
|
64,957,134 | 64,957,156 | What does the '.' after the 60 mean in the expression? | What does the '.' after the 60 mean in the expression?
double timeSaved(int limit, int avgs, int dis)
{
double time_limit = 60.*dis/limit;
double time_avgs = 60.*dis/avgs;
double tsave = time_limit-time_avgs;
tsave = 10*tsave+.5;
tsave = ((int)tsave)/10.0;
return tsave;
}
| It is a floating point literal. Two possible syntax for a floating point literal are (cppreference):
digit-sequence(optional) . digit-sequence exponent(optional) suffix(optional)
or
digit-sequence . exponent(optional) suffix(optional)
Note that exponent and suffix are optional. Further in the first there is a digit-s... |
64,957,366 | 64,957,465 | How does `select` handle multiple events at the same time? | I am trying to understand the following code. If I have 50 connections to this server and I send data through one of these sockets, the select block with the inner loop will capture what I send and echo it back. But what happens if within a very short time-frame of the first message, I send another one? So fast that th... | Yes, multiple descriptors can be ready to read in a single iteration. The return value of select() is the number of descriptors that are ready, and it can be more than 1. As you loop through the descriptors, you should increment a counter when FD_ISSET(sd, &readfds) is true, and continue until the counter reaches this ... |
64,957,453 | 64,957,657 | I've got int number and the functions must return double number | i have a little problem , i make all the variables double
then i still have result = int number and i really don't know why
thx ♥
#include <iostream>
using namespace std;
const double pi {3.14159} ;
calc_radius_circle( double radius){
return pi * radius * radius ;
}
double area_circle() {
double ra... | You need calc_radius_circle to return a double so your code should look like this.
#include <iostream>
using namespace std;
const double pi {3.14159} ;
double calc_radius_circle( double radius){
return pi * radius * radius ;
}
double area_circle() {
double radius {};
cout << "\n Enter the radius ... |
64,957,872 | 64,957,964 | OpenGL Shader Program causing screen to go black when used | So in my OpenGL code, whenever I try using a shader program in my project, the screen just stays black.
I've purposely made an error in the shader code to make sure the error checking worked, and it did, so when I went to fix it and run the program again it just gave a black screen.
I've went into other projects to mak... | The 4th component of the clip space coordinate should be to be 1.0:
gl_Position = vec4(vertexPosition, 0.0, 0.0);
gl_Position = vec4(vertexPosition, 0.0, 1.0);
The clip space coordinate is a Homogeneous coordinates. The normalized device coordinate is a Cartesian coordinate it is computed by dividing the x, y and z co... |
64,957,941 | 64,969,625 | Oboe C++ Threads - How to read and write to a queue without blocking | I am trying to write a buffer for an audio system with Oboe, the do and don'ts are
Callback do's and don'ts You should never perform an operation which
could block inside onAudioReady. Examples of blocking operations
include:
allocate memory using, for example, malloc() or new;
file operations such as opening, closing... | You can use a thread-safe lock-free queue for reading/writing data. This will avoid the need for mutexes, will be much faster and should fix your "popcorn" issues.
An example implementation can be found here: https://github.com/google/oboe/blob/master/samples/RhythmGame/src/main/cpp/utils/LockFreeQueue.h
|
64,958,214 | 64,958,475 | Confusion about time complexity with hash maps | On leetcode I find it is common to "ignore" the worst-case time complexity involving hash maps. I thought in software interviews that it was standard to assume "worst case" as they often do. Below is my solution to a simple problem. The problem is to find the first non repeating char in a string. I understand that hash... | It is on average O(N) because hash map is on average O(1) per lookup and you do O(N) of them.
On average means by averaging over all possible inputs. That means there might exists an input array that breaks a particular hash and achieves O(N) or much worse on every lookup.
Worst-case is heavily implementation specific ... |
64,958,646 | 64,958,708 | Why am I getting a segmentation fault? What am I doing wrong? | Problem: A program to count the number of times a number repeats in an array using recursion.
What I've done: I've tried every way I know, I've gone with an output array for storing indices of the number, and just ++ to another number on finding a match to current number. Nothing seems to work, it's one error or anothe... | There are quite a number of mistakes in this code:
j is uninitialized, and even if it weren’t, you are not using the value of j correctly.
There is a missing return on the recursive call to ind() (is that what the re was supposed to be?).
You are passing the original values of a and size to the recursive ind(), causin... |
64,958,726 | 64,961,322 | Calculating end point of line not working | I two rectangles with an angle displaying a line, and I want the second ones position to be the end point of the first one.
The origin of the lines is the start point, and I can get the angle via a function(I am using the SFML library for defining/displaying the rectangles).
The first part of the Code looks like this, ... | You are creating lines that looks like at angle 0:
This is because the width is 1, height is 10, and the origin is (0.5, 0), note that this example shows y increasing downwards, not upwards.
But you are using maths that calculates the end point like this at angle 0:
This is because x equals cos(0) * length, which equ... |
64,958,790 | 64,958,837 | Is there a way of having a variable number of typenames in a template function, like parameter pack? | I'm on a microcontroller, so in order to avoid the new operator, I reserve some memory to be used in a placement new operator call. I'd like to determine the minimum size of that memory by supplying a number of types to a constexpr function that will return the largest type in the list.
struct A
{
int foo;
int ba... | Something along these lines:
template <typename... Ts>
constexpr size_t max_sizeof() {
return sizeof(std::aligned_union<0, Ts...>::type);
}
|
64,959,367 | 64,968,412 | How to wait for QProgressDialog construction? | Before long operation is executed, I'm invoking QProgressDialog to inform user about the progress of the execution. The long operations is waiting for thread to be terminated.
The problem is, when I use show method of QProgressDialog, the progress dialog is not fully constructed and the thread goes into the wait method... | You can wait for the thread to finish with some timeout. If the thread is finished, close the progress dialog. If it isn't, process the application events.
auto dialog = new QProgressDialog();
dialog->setWindowTitle("Wait");
dialog->setRange(0, 0);
dialog->setLabelText("Aborting optimization");
dialog->setCancelButton(... |
64,959,561 | 64,959,678 | Checking for a default Constructor using class templates with std::void_t | Below is the snippet which is trying to check for the presence of a default constructor at compile time. Compiling this with
clang version 11.0.0
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin
using options clang++ --std=c++17 -o test_default_ctor test_default_ctor.cpp
#inc... |
template<typename T>
struct has_default_ctor_2<T, std::void_t<decltype(T{})>> : std::true_type {};
As you are checking whether T{} is well-formed, you allow also types which may be initialized by means of aggregate initialization. Test3 is an aggregate class prior to C++20 as it has no user-provided constructor. Fr... |
64,960,034 | 64,998,834 | Output issue with .CSV file | Whenever I attempt to output a line, it outputs the data from the file vertically instead of outputting the full line horizontally. My main goal is to output each line individually and remove commas and repeat till no more lines are in the CSV file.
An example when I run the code:
cout << data[1] << "\t";
Output:
Hugg... | Please change your main function as follows
int main()
{
vector<vector<string>> data;
string readLine;
ifstream myIFS;
myIFS.open("SalesAssociateAnnualReport.csv");
int lineCounter = 0;
while (getline(myIFS, readLine))
{
lineCounter++;
if (lineCounter > 1)
{
... |
64,960,135 | 69,077,040 | Waiving of access checking rules for explicit function template specializations in C++20 | [temp.spec]/6 was added to C++20 by implementation of P0692R1 (Access Checking on Specialization) [emphasis mine]:
[temp.spec]/6 The usual access checking rules do not apply to names in a declaration of an explicit instantiation or explicit specialization, with the exception of names appearing in a function body, defa... |
What is the correct behaviour in C++20 here, is the program above well-formed (GCC bug / Clang not fully implemented) or are GCC and Clang correct to reject it?
As already cited in the OP, [temp.spec]/6 supports this feature, and the program is well-formed. Particularly, all of snippets (A) through (D) below are well... |
64,960,243 | 64,965,042 | Storing an std::assume_aligned pointer C++ 20 | In C++ 20 we're getting assume aligned, this would be very usefull for audio code where pointers to aligned blocks of floats are passed around all the time. Let's say we have the following span type:
template<typename T>
struct Signal
{
const T* data
size_t size;
};
How would one indicate that the data pointer... | It seems that the assume-aligned hint is a property of a particular pointer object, and it cannot be made a property of a pointer type. However, you might try to wrap that pointer by an (inline) getter function and use std::assume_aligned for its return value. For example, in my experiment, when I used the pointer retu... |
64,960,271 | 64,960,546 | Compiler cannot find specialized class template | I want to use partial template specialization but it seems I am missing something.
Here is what I've tried:
template<class T1, class T2>
class AClass {};
template<class T>
class AClass<T, T> {}; // specialized class.
AClass<int,float> aClassIntFloat; // works just fine
AClass<int, int> aClassIntInt; // works just fi... | First of all, you have already successfully defined a partial specialistation:
AClass<int, int> will instantiate class AClass<T, T> with T=int
AClass<int,float> will instantiate class AClass<T1, T2> with T1=int and T2=float
You can easily check this by adding a public test method and invoking it for aClassIntFloat ... |
64,960,376 | 64,960,660 | Qt Checkable QActions | I have two QActions in a right-click menu. I'm trying to check one action and show a tick next to it. While positive is checked and if I check positive a second time, it should return the program to the default mode and remove the tick. If negative is checked after positive, the tick should move to negative. I revised ... | You literally have to do what you said: uncheck the other action. Since the actions are specific to the given context menu, you should capture them. IIRC, the actions automatically check and uncheck each time you click on them, so that should be already happening without any additional code.
The actions have to be made... |
64,960,476 | 64,960,507 | Reassign variable of type auto that is currently std::unique_ptr | I am currently experimenting with the ESP32-CAM, which is a microcontroller with integrated camera that you can program through the Arduino IDE (with C++11). For capturing images with the cam, there is a library called 'esp32cam', which contains the function esp32cam::capture(). This function apparently returns a varia... | Try changing this:
auto lastPic = std::unique_ptr<esp32cam::Frame>();
void takePicture() {
lastPic = esp32cam::capture();
}
to this:
auto lastPic = std::unique_ptr<esp32cam::Frame>();
void takePicture() {
lastPic = std::move (esp32cam::capture());
// ^^^^^^^^^
}
(Because std::unique_ptr is moveable but n... |
64,960,528 | 64,960,559 | Are there any performance differences between representing a number using a (4 byte) `int` and a 4 element unsigned char array? | Assuming an int in C++ is represented by 4 bytes, and an unsigned char is represented by 1 byte, you could represent an int with an array of unsigned char with 4 elements right?
My question is, are there any performance downsides to representing a number with an array of unsigned char? Like if you wanted to add two num... | There will be many performance downsides on any kind of manipulation using the 4-byte array. For example, take simple addition: almost any CPU these days will have a single instruction that adds two 32-bit integers, in one (maybe two) CPU cycle(s). To emulate that with your 4-byte array, you would need at least 4 separ... |
64,961,132 | 64,961,411 | Variadic template declaration from single integer argument? | Is it possible to statically declare N same-type template arguments from single integer type template argument? Potentially something similar to this:
template < int N >
class MyTemplatedType {
// base type, known
typedef float base_t;
// instance of some other templated class with *N* template arguments
... | You can write a meta-function that accepts N, base_t, and SomeOtherClass, and recursively calls itself with a smaller N, each time tacking on base_t to the end of a growing parameter pack:
template <int N, typename T, template<typename...> typename C, typename ...Ts>
struct expand {
using type = typename expand<N-... |
64,961,283 | 64,961,307 | C++ whats the difference between these two codes to make an array of objects? | I’m really confused about these two lines of codes. What’s the difference between them?
One is created on heap and the other on stack?
classname *arrayofobjects[50];
and
classname *arrayofobjects = new classname[50];
| classname* arrayofobjects[50]; declares a stack array of 50 elements, where each element is of type classname* (a pointer to classname). classname* arrayofobjects = new classname[50]; heap-allocates an array of 50 of objects classname, constructs them with their default constructor, and sets arrayofobjects to a pointer... |
64,961,339 | 64,961,530 | Accessing static member function gives: ld: symbol(s) not found for architecture x86_64 | I am sure this is a noob C++ question and just reflects my poor understanding.
I have a file
A.cxx contains,
#include "Rishab.h"
#include <future>
void functionToRun() {
while (true) {
Rishab::hello();
}
}
int main() {
std::future<void> futureVariable = std::async(std::launch::async, functionToRun);
}
Ri... | The error message is telling you that the linker, while trying to combine all the separately-compiled object code for each translation unit (i.e. each file containing source code), it could not resolve the existence of the function void Rishab::hello().
This most likely means that you did not actually provide the objec... |
64,961,350 | 64,961,515 | Executing a node script with child_process | I have a simple node index.js file that uses an event emitter to emit data every two seconds. Within this file I export the reference of the event emitter as I wish to use it in another file user.js. When I run the index.js everything works as expected. Then when I open another ternimal and run the user.js it writes to... | Here is a slightly different approach: you can run the user.js as the parent and have index.js on a child process.
User.js
const newEvent = require("./index");
const { spawn } = require("child_process");
const userEmitter = newEvent.emitter;
userEmitter.on("save-user", (user) => {
console.log("Saving user data", us... |
64,961,651 | 64,962,382 | C++ Microsoft Visual Studio Array Problems | Please forgive me for some of the errors I have made within my code, but I am new to this and since COVID is preventing me from reaching regular help, I thought I would turn here to ask for some help, rather than googling non-stop. We do not use "std::cout" just so you know. Also I am not quite getting how to update th... | Your code has several flaws.
First of all, you don't need to loop the functions inside the switches:
for (int index = 0; index < SIZE; index++) // this line is not needed
addCodes(codes, SIZE);
because it is effectively looping over loops in the functions. You need to iterate over one-dimensional array, so you ge... |
64,961,662 | 64,969,120 | V8 updating code using deprecated v8::Local<v8::Value> v8::Object::Get(v8::Local<v8::Value>)? | I am in the process of updating a NodeJS package, due to a breakage in NodeJS 14. This library makes use of C++ code. In NodeJS 12 the same code appears as a deprecation warning:
warning: ‘v8::Local<v8::Value> v8::Object::Get(v8::Local<v8::Value>)’ is deprecated: Use maybe version
With the code in question being:
v8::L... | The key insight is that most operations that involve JavaScript can throw an exception instead of returning a value. The MaybeLocal convention makes this explicit: a MaybeLocal is either a Local (if the function/operation returned a value), or empty (if there was an exception). If you have a v8::TryCatch or Nan::TryCat... |
64,962,215 | 64,962,283 | How to add different header folders with cmake so the project properly compiles and run | I'm creating a project with cmake and c where I need to include headers from different folders,
#include <dbus/dbus.h>
#include <audacious/audctrl.h>
#include <audacious/dbus.h>
#include <pidgin/pidgin.h>
And I added these lines to the cmake cofig file:
target_include_directories(untitled PRIVATE
/usr/include/dbus... | When you say target_include_directories it will find the corresponding headers for you. Hence, when you compiled and it didn't complain about your headers it's because you included their paths to be found during compilation.
My hunch is you're not specifying the library files during static linking. When you don't have ... |
64,962,658 | 64,962,694 | Recursive power function in C++ | I'm having some trouble with this function. The function takes a and computes it to the power of b recursively. My compiler gives me a segmentation error when I compile this, which I'm not sure how to fix. Can anyone help?
/**** Recursive power function > Computes a^b, where b can be positive or negative*****/
... | The crash is a result of infinite recursion. b never reaches 0 since you keep decrementing it on every recursive step.
You probably need to insert this clause into your code:
if (b < 0)
{
return 1.0 / recPower(a,-b);
}
else if (b == 0)
...
Of course, a to the power of a negative number will more sure be a value b... |
64,962,759 | 64,965,453 | WIN32 Dialogue Box Throws exception | I am trying to learn the win32 api using the Microsoft documentation. I have gotten to chapter 4, and I seem to have run into an issue that I am struggling to debug. The dialogue box triggered by the about button throws an exception:
Exception thrown at 0x773BDCFF (ntdll.dll) in practice.exe: 0xC0000005: Access violat... | Fail to reproduce this issue using your presented code. The following is an example based on your code piece and it works for me. You can refer to.
App.h
class App
{
public:
App(HINSTANCE hInstance, CONST WCHAR* clsName);
private:
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lP... |
64,963,075 | 64,963,946 | How to project std::tuple in c++20 constrained algorithms | Suppose we have a array of std::pairs:
using Particle = std::pair<std::string, double>;
Particle particles[] {{"Electron", 0.511}, {"Muon", 105.66}, {"Tau", 1776.86}};
We can using C++20 ranges algorithms with different projection function to sort them according to different data member:
ranges::sort(particles, {}, &P... | You can provide your own functor to do this
namespace my
{
template<size_t n>
struct get_t
{
template<typename T>
decltype(auto) operator()(T&& t) const
{
using std::get;
return get<n>(std::forward<T>(t));
}
};
template<size_t n>
inline co... |
64,963,089 | 65,016,251 | FM10420(fm10k) DPDK RX Queues become empty along with FUM_BAD_VF_QACCESS on dmesg | I am developing my own dpdk application utilizing multiple rx/tx queues. My application runs perfectly fine with Intel 82599ES NIC. However, I want to run my application on FM10420. I use an FM10420 virtual function (VF) since my PF need to be bound to fm10k driver to control the switching fabric. Upon running my appli... | After doing few tests with example/skeleton and my own dpdk application I have found that the problem is with using rte_eth_tx_buffer();to buffer my packets to TX queues. I have replaced it with rte_eth_tx_burst(); which will transmit my packets as single packet bursts. However, I guess this could affect my TX performa... |
64,964,038 | 64,964,066 | Is vector in c++ a pointer? | So lets say we have a vector v and I pass this to a function f
void f(vector<int> &v) {
cout<<&v;
}
int main() {
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
cout<<&v[0]<<"\n"<<&v<<"\n";
f(v);
}
For this I get the outputs as:
0x55c757b81300
0x7ffded6b8c70
0x7ffded6b... |
Is vector in c++ a pointer?
No. std::vector is not a pointer. It is a class.
So is v a pointer that points to the start of the vector?
No, but v (an instance of the vector class) does happen to contain a pointer to the start of the array.
why can't I access *v?
Because there is no overload for the unary operator*... |
64,964,160 | 64,964,465 | Understanding reference arguments in recursion | I have tried implementing the code for Sorted Linked List to BST from leetcode
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ .
The approach which I have used to use a recursive approach like below. But here we have to use reference (&) in head in the function argument. If I don't use, then ou... | sortedListUtil does two things: it returns the root (1), and it also changes the head (2) so that its invocations are advancing along the list from call to the other recursive call:
TreeNode *sortedListUtil(ListNode *&head, int n) {
// head should be ref, if we dont use & ,
// unexpected output will come
... |
64,964,184 | 64,964,506 | What is narrowing cast when I use initializer list? | One guy tell me that more effective to write
SomeType val{another_val};
than
SomeType val = another_val;
cause in the second case we have narrowing cast.
Can you explain what is this? And is this true that initialize with initializer list more effective?
| Using braces is another way of making your code safer, that's all. For example
int main() {
unsigned n = -1.0; // hopefully a compiler warning, undefined behaviour
unsigned m {-1.0}; // certainly a compiler diagnostic
}
|
64,964,777 | 65,018,623 | Thrust: inplace exclusive_scan of one member | I have a vector of MyElement, which is defined as follows:
struct MyElement {
int count;
int prefixSum;
}
I would like to perform an in-place exclusive_scan of count but using prefixSum as the result, without changing count. Is that possible using thrust?
As an example, for the following input (prefixSum is in... | I ended up with a similar solution. A StackOverflow answer describes how one can perform an inclusive prefix sum on just one class member.
Since I can't perform a scan on one member and "output" it on another member, instead of initializing prefixSum to zero, I use the same value as count (I do this in a previous kerne... |
64,965,115 | 64,965,464 | I included necessary header file but get "error: gai_strerrorA was not declared in this scope", ubuntu16.04, g++ 5.5 | I'm moving a code which runs on widows to linux now. Much part is using standard libraries but there are still some compile errors that I have to remove. Now, the error comes from this line
printf("[err] getaddrinfo: %s[%d] (%s, %d)\n", gai_strerrorA(ret), ret, server_addr, port);
and the error message is below.
g++... | The gai_strerrorA function is a Windows-specific extension for "ASCII" strings (as opposed the gai_strerrorW for "Unicode" characters).
The plain POSIX standard function is just gai_strerror, without any character-specific suffix (Windows uses macros to define the suffix-less gai_strerror "function" depending on other ... |
64,965,605 | 64,965,682 | low efficient std::move()? | Please take a look at the following code snippet, which seems std::move() is low efficient in this scenario.
class A {};
struct B {
double pi{ 3.14 };
int i{ 100 };
A* pa{ nullptr };
};
int main() {
B b;
std::vector<B> vec;
vec.emplace_back(b); // 1) without move
vec.empl... |
std::move() is completely redundant for this case.
Technically not a question but yes, this is correct.
Moreover, if the parameter of std::move() has a trivial move constructor, then std::move() is redundant.
Same as above.
if the trivial move constructor performs the same action as the trivial copy construct... |
64,965,723 | 64,966,382 | what does this `context_.Reset` do in v8 runtime implemation of react-native js-runtime? | I m a noob in c++ and v8 engine. when I check the source code of the implementation of v8 JSI, I found which I can not understand: Here is the constructor of the v8 runtime: (pls see comments line below)
V8Runtime::V8Runtime(const std::string &timezoneId) {
if (!s_platform) {
s_platform = v8::platform::NewDefault... | context_ is a global handle (v8::Global), its Reset(...) method is how you assign to the pointer it wraps. So it's being "reset" from being uninitialized to storing the newly created global context here.
This is probably just defensive programming. – Botje
No, defensive programming has nothing to do with it.
Just tr... |
64,966,072 | 64,966,377 | Is there a constexpr alternative to modf | I would like to get the integer and the fractional part of a float. This is easy with std::modf but the function is not constexpr. What is the reason for this and what is the alternative?
|
Is there a constexpr alternative to modf
There is no standard constexpr alternative to modf or related math functions.
but the function is not constexpr. What is the reason for this
Those functions pre-exist constexpr. They even pre-exist C++. As such, when those founctions were specified, they couldn't have been c... |
64,966,106 | 64,987,280 | Data written on Linux pipe by program 1 is sometimes read twice by program 2 | I'm trying to establish an inter process communication on Linux using named pipes. At first glance my code seems to work, but I noticed that sometimes data written to the pipe by the "main" process is read twice by the "child" process (in fact it's two separate programs).
Program 1 (write only, starts first) is a legac... | I found some helpful information here, stating:
"If all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from the pipe will see end-of-file (read(2) will return 0)"
I took out fd = ::open(...); and ::close(fd); from my onclick-function in program 1 and put them into t... |
64,966,634 | 64,967,057 | C++ Parallel_For issues | I'm currently writing a genetic algorithm for my dissertation and running into an error implementing a parallel_for loop, its probably very obvious but I'm not sure how to solve the issue.
void evaluate_population_fitness(vector<Chromosome *> population) {
std::for_each(std::execution::par_unseq, population.begin(), ... | If you'd run your code under debugger, you'd probably see that all pointers point to the same address. And that address is invalid (though debugger couldn't tell you that).
You create a local object City, which dies immediately when the current loop iteration finishes. The pointer you stored in vector is invalid.
It ge... |
64,967,668 | 64,968,141 | how to use std::copy for array of struct with values deep inside | This is my code:
struct Base
{
float value;
};
struct Metre
{
Base base;
};
struct Distance
{
std::array<Metre, 4> distances;
};
std::array<float, 4> values{10.0, 11.23, 12.34, 23.45 };
Distance dist;
std::copy(std::cbegin(values), std::cend(values), std::begin(dist.distances)->base.value);
Need to copy value... | I suppose your intention is copy the values from the values array in the dist.distances array.
A possible solution pass through std::transform()
std::transform(values.cbegin(), values.cend(), dist.distances.begin(),
[](float f){ return Metre{ Base{f} }; });
-- EDIT --
The OP asks
how to copy from dist.... |
64,967,682 | 64,967,764 | Stringifying with leading zeros | I'm looking for a way to have a fixed length Device name in C++ at compile-time, as string literal.
For example :
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define VERSION 6
#define DEVICE_NAME "MyDevice" STR(VERSION)
A fixed length with leading zeros to fit 4 digits is my desired output, Just like as "My... | Very ugly but this should do the trick:
#include <stdio.h>
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define VERSION 6
#if (version < 10)
#define DEVICE_NAME "MyDevice000" STR(VERSION)
#elif (version < 100)
#define DEVICE_NAME "MyDevice00" STR(VERSION)
#elif (version < 1000)
#define DEVICE_NA... |
64,967,871 | 64,972,818 | Getting the path of recursively iterated directories relative to the specified entry path | Consider the example in the documentation of std::filesystem::recursive_directory_iterator:
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::current_path(fs::temp_directory_path());
fs::create_directories("sandbox/a/b");
std::ofstream("sandbox/f... | You can use std::filesystem::relative, this might look like:
std::cout << fs::relative(p.path(), "sandbox") << '\n';
|
64,967,919 | 64,968,300 | Why must the template parameter pack be last? | I am facing the following inconsistency between gcc10.2 and clang11:
template<typename ... Args, typename T>
static constexpr int fuu = sizeof(T);
clang complains that a template pack must be the last thing in the template declaration:
error: template parameter pack must be the last template parameter
template<typenam... | The variable template declaration is ill-formed, and it's a gcc bug for not diagnosing it.
From temp.param#14:
... If a template-parameter of a primary class template, primary variable template, or alias template is a template parameter pack, it shall be the last template-parameter. ...
The function template is fine,... |
64,968,272 | 64,970,382 | Setting a protobuf item's value replaces a previously set variable as well | I have created a simple Protobuf based config file and have been using it without any issues until now. The issue is that I added two new items to my settings (Config.proto) and now whatever value I set for the last variable is reflected in the previous one.
The following snapshot demonstrates this better. As you can s... | This issue seems to only exist in the Windows version of Protobuf 3.11.4 (didn't test with any newer version though).
Basically what happened was that I use to first create a Config object and initialize it with some default values. When I added these two entries to my Config.proto, I forgot to also add an initializati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.