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,481,677 | 62,481,771 | Why move on std::map is failing to move a element from one map to other | I am trying to practice how to move one map element to other - hence I tried below code:
using namespace std;
int main(void)
{
/* Initializer_list constructor */
map<char, int> m =
{
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Move element ... |
Why move operation is failing for std::map STL container - I was expecting that after m['a'] would be empty?
That expectation is ill-founded.
The statement
auto s = move(m['a']);
leaves m['a'] as is for couple of reasons.
That statement can be thought of as:
int&& s = move(m['a']);
I.e it just captures reference t... |
62,481,901 | 62,491,193 | gdb `list` command only shows one line number instead of contents when attaching to a process | I invoked gdb to attach a current running process with this command sudo gdb binary PID. After that I set breakpoints and typed continue in gdb. Then I sent a request to this process to hit the breakpoint. After that, when I type command list, it only shows one line instead of multiple lines as expected, and it only sh... |
when I type command list, it only shows one line instead of multiple lines as expected, and it only shows line number instead of contents
This is most likely happening because GDB has no access to the source. The sudo is the key here. Your source likely resides on a filesystem that doesn't allow root access, such as ... |
62,481,908 | 63,345,531 | Clearing background in raylib from class method makes window flicker | Hi there I'm learning c++ so I'm not sure if this is a stupid mistake on my part. I'm trying to do something simple with raylib, I'm trying to simply clear the background by calling a method in a class. When I try to do this from the class, the window flickers horribly and sometimes freezes. But when it's called inside... | It looks like you're re-defining your draw function. So it's most likely calling the empty draw function definition in your header.
viewer.h
void draw(){} //This is most likely what is being called.
void draw(); //Use this if you want to define it in .cpp
Either you can keep the .cpp definition and go with void draw()... |
62,482,203 | 62,483,710 | How do i take user input of an Arithmetic Expression like 5-8+7*4-8+9 or 1+5? | I am solving a problem for finding maximum value of an arithmetic expression. But I am having problem in taking input for the expression as no of characters are not fixed.
Input Format:
The only line of the input contains a string s of length 2n + 1 for
some n, with symbols s0 , s1 , . . . , s2n.
Each symbol at an eve... | Your output seems to be correct, but as already mentioned in the comments, your values are read as characters, not as digits, so a conversion needs to be done.
In order to do this, it might be helpful to understand that, in ASCII, the digits have following value:
Character ASCII-code value
'0' 48 0
... |
62,482,227 | 62,483,144 | Proper way to add c++ includes to eclipse | I normally use eclipse for java, now I need to do some cpp stuff. I'm using vcpkg for dependency management and cmake to build by binary:
cmake CMakeLists.txt "-DCMAKE_TOOLCHAIN_FILE=$VCPKG_CMAKE"
which is working fine. However, eclipse cannot find these dependencies and what I did was:
project properties / c/c++ gen... | so I added cmake4eclipse add built the project with that, under project properties added under:
c++ build / cmake4eclipse / symbols(tab)
CMAKE_TOOLCHAIN_FILE=$VCPKG_CMAKE
and that sorts that out.
You could probably just add include as described above to the path:
$VCPKG_HOME/installed/x64_linux/include
or something ... |
62,482,269 | 62,483,055 | How to convert float array to byte array in C++ (Arduino) | How to convert array of floats to array of bytes in Arduino.
Basically convert all float variables of the array to bytes (and round all variables to the nearest integral value) in an efficient way.
Convert this:
float mlx90640To[768];
to:
byte bytearray[768];
| I guess that I maybe do not fully understand the question. It maybe an XY-Problem.
But a fast and efficient solution could be the below.
#include <iostream>
#include <cmath>
using byte = unsigned char;
float mlx90640To[768];
byte bytearray[768];
int main() {
// Convert all float values
for (size_t i{}; i < ... |
62,482,307 | 62,482,560 | Using methods for the objects in class | How to call methods which I declared in class for my private variables? This code causes Fail: non-declared method At. I want in function Top() to use method At() which I declared earlier. Please, help :)
For Example:
class A{
public:
void At(size_t i){
Check_i(i);
return one[i];
... | use pointer 'this', void Top(size_t i) {return this->At(i);}
|
62,482,322 | 62,482,391 | Using templates in classes | I used a template within a c++ class. However, when I try to call a function using a template from another function in the class, I get an error.
What should I fix?
void MyClass::Display()
{
cout << "sum : ";
cout << setw(30) <<Add();
}
template <typename T>
T MyClass::Add()
{
T sum=0;
for (int i = 0;... | You want to use Add(). But you do not specify the template argument for Add() you want to use.
You can specify it by: Add<*type*>()
|
62,482,835 | 62,482,906 | Anonymous Unions data member value conflicts | I'm using anonymous union and tried for a simple program. but i found whatever i'm inputting in Varname variable the value is not being fetched. Please let me know where the gap is. Thanks in advance. Here is a code of the program.
using namespace std;
int main(){
union{
char varName[100];
char var... | A union can contain only one of it's members at any time. It's only legal to read the member that was last written. You probably wanted to use struct. Note that C++ does not allow anonymus structs, so you need to give it a name:
#include <iostream>
using namespace std;
int main(){
struct {
char varName[10... |
62,483,802 | 62,483,948 | Add a element to list | I am trying to add an element to my List,but it fails.
The List always seems to have not changed when I try output it.
sample input : 1 3
sample output: 1 3
Can somebody tell me why and how to solve it?Thanks.
here is the Node and List
struct Node {
int value;
Node* next;
Node(const int& val = 0, Node* ne... | In List::insert_to_end you only change the local variable temp, which has no effect on the state of the list (and leaks memory). This should work:
void List::insert_to_end(int val) {
Node* temp = head; // start with head
while (temp->next != NULL) { // iterate until end, then temp points to the last node
... |
62,483,835 | 62,484,464 | Qt signal multiple definitions | I don't understand, I have a header :
#pragma once
#include <QObject>
#include <QString>
#include <QtQml>
#include <qqml.h>
#include <iostream>
class MainWindow : public QObject
{
Q_OBJECT
Q_PROPERTY(QString userName READ userName WRITE setUserName NOTIFY userNameChanged)
public:
explicit MainWindow(QObj... | userNameChanged is a signal not a slot. You can emit this signal anywhere you want, and there is no need to implement it. It seems that you want to emit this signal once a user name is set in the setUserName function. So do it as follows:
void MainWindow::setUserName(const QString &userName) {
std::cout << "SET USE... |
62,484,385 | 62,517,372 | Alternate way to write in a file instead of using "<<" in c++? | When we load a file using fstream header, we use >> and getline() to get one complete line.
When writing it to an output file we use <<
Is there any other alternate way to write the line in the output file instead of <<?
| it is very simple. look the code below
#include <iostream>
using namespace std;
int main()
{
char a('a');
// cout
cout.put(a); // can only be used for characters
string hello;
//cin
cin.getline(hello);
//or
getline(cin,hello);
}
see, it was too easy;
|
62,484,744 | 62,484,761 | Why can't I use a template integer when initializing a std::vector? | I'm trying to create a class BigInt that contains a std::vector with D elements.
template<int D>
class BigInt
{
public:
std::vector<short> digit(D, 0);
};
I'm getting an error stating that 'D' is not a type
| The problem is default member initializer (since C++11) only supports equal-sign (or braced) initializer, but not
parentheses initializer.
You can
template<int D>
class BigInt
{
public:
std::vector<short> digit = std::vector<short>(D, 0);
};
You can also use member initializer list in constructor instead o... |
62,485,249 | 62,485,276 | Overridden function does not reflect in the base class, is this a normal behavior? | Given the following code:
class Base {
public:
virtual void Test() {
cout << "Not Overridden" << endl;
}
};
class Derived : public Base {
public:
void Test() override {
cout << "Overridden" << endl;
}
};
int main() {
Base o = Derived();
o.Test();
return 0;
}
Someone like m... | Yes, it's normal behavior, polymorphism only works with pointers and references.
With raw pointer:
int main() {
Base* o = new Derived();
o->Test();
delete o; //when done with using it delete it from memory
//...
}
An alternative to this memory management would be to use smart pointers.
With smart point... |
62,485,486 | 62,552,442 | Is there a way to make vim run the “make” command in another terminal window? | I mainly use vim as an editor for C/C++ programming. Unfortunately, I'm not quite satisfied with the way my build process works. I know that it's possible to type in (or map to a key) :make to run the make process. I dislike the way this command works, though, as it runs the build process in the same terminal window wi... | You can achieve this by using xdotool and i3 config-file mappings. These mappings require that the last command executed in the terminal of the window rightwards was make.
set $prevR xdotool key --clearmodifiers --delay 2 super+l ctrl+p Return super+h
set $prevRclr xdotool key --clearmodifiers --delay 2 super+l ctrl... |
62,485,553 | 62,485,779 | C++ ctime with ansi escapes | #include <iostream>
#include <string>
#include <ctime>
using namespace std;
#define WIDTH 118
#define HEIGHT 60
void clearScreen(void) {
cout << "\033[2J\n";
}
void moveCursor(int row, int column) {
cout << "\033[" << row << ";" << column << "H";
}
void waitDelay(int sec) {
long startTime =... | Your function waitDelay works well. The mistake is here cout << message[i]. cout is buffered stream. You should use flush
|
62,485,721 | 62,486,659 | expected unqualified id before return 0 | I'm new to C++. I have errors. But, i dont know how to fix it. Could anyone please help me? Thank you.
P - Print numbers
A - Add a number
M - Display mean of the numbers
S - Display the smallest number
L - Display the largest number
Q - Quit
Errors : expected unqualified id before return 0
error : expected ';... | I have written this for you. Since, you're a learner, I think that you should be practicing better things like STL functions and not using using namespace std; at top.
You may find some things new, but don't be frightened, just search them on some website like cppreference and see what that entity do and how to effecti... |
62,485,855 | 62,485,965 | C++ struct to Delphi Record dll call | I am trying to convert c++ struct to delphi Record for dll call
// c++ struct
typedef struct dll_info_t
{
char version[32];
char r_type[128];
char b_date[32];
char c_list[32];
char build[32];
}dll_info_t;
LIBEX_EXPORT int LIB_API Dll_get_lib_info(dll_info_t* info);
// Delphi Converted
dll_info_t = re... | char version[32] is not the same as AnsiChar, because that AnsiChar is a single character. You need an array of AnsiChar, (version: array [0..31] of AnsiChar) just like what is used in the C code. You'll need the proper declaration for all of the members of the record.
type
dll_info_t = record
version: array [0..... |
62,486,210 | 62,486,570 | Are constant "flags" considered good style? (c++) | I am currently working an a library and I wonder if it's considered good style to have all-caps constants like:
constexpr int ONLY_LOWERCASE = 1;
constexpr int ONLY_UPPERCASE = 2;
And so on. I plan on using it to let the library user control the behavior of the functions like:
doSomeThing(var, ONLY_UPPERCASE);+
Thank... | It's seems like you are using integer structure to store boolean data. It might considered as a better way to use boolean structure for this purpose, for memory usage reasons.
One way of archive this target is using enum or enum class that inherit from bool:
enum class string_case : bool {
ONLY_LOWERCASE,
ONLY_... |
62,486,307 | 62,486,569 | Why does the std::size on an array passed by value do not work? | Why does the std::size() do not work on a statically allocated array passed by value?
void print_elemTab(int tab[])
{
// ...
int size = std::size(tab); //error
// ...
}
void test_tab()
{
const int TAB_SIZE = 5;
int tab[TAB_SIZE] = {};
// ...
cout << std::size(tab) << std::endl; //prin... | Array designators used in expressions are implicitly converted (with rare exceptions as for example using them in the sizeof operator) to pointers to their first elements.
So in this call
print_elemTab(tab);
the argument expression has the type int *.
On the other hand, a function parameter having an array type is ad... |
62,486,645 | 62,492,426 | How to make if statement in Makefile based on platform? | I am having trouble with crypto wallet, which does not probably matter that much. The issue is that makefile contains files which is used for x86 architecture and I have AARCH64 files, but can't seem to find a way, how to deal with that...
So I would like to change, based on platform(in this case x86), this:
crypto/r... | You've given a list of file names and not indicated how you use them, so I'll assume you're assigning them to variables.
We can start with a simple conditional:
ifeq ($(PLATFORM),x86_64)
do something
endif
ifeq ($(PLATFORM),aarch64)
do something else
endif
Crudely, we could do this:
ifeq ($(PLATFORM),x86_64)
SO... |
62,486,720 | 62,488,610 | C++ | Anonymous namespace colliding with namespace std | #include <queue>
using namespace std;
namespace {
class priority_queue;
}
priority_queue pq;
How can I distinguish between the two priority_queue names? I tried ::priority_queue to get the global one but to no avail.
| It is simple, just change
using namespace std;
to
//using namespace std;
Now you have to type std::priority_queue for the standard one and priority_queue or ::priority_queue for the custom one.
|
62,487,323 | 62,487,453 | Can I pass a vector as an initial_sum and a different function to std::accumulate? | I have the code below. Our exercise is using STL algorithms.
Is there is a way to use std::accumulate for this code?
If you have a different STL algorithm for this code it is also fine! (We will also test on our time complexity.)
void multiplyAndAddVector(const int num, std::vector<double>& tomultiply, std::vector<doub... | std::accumulate is not an appropriate algorithm here, since it only gives you a single value as a result.
You need to read 2 ranges, and modify one, for which you can use std::transform like this:
std::transform(toMultiply.begin(), toMultuply.end(), // input range 1
toAdd.begin(), ... |
62,488,173 | 62,843,375 | How does C++20's memory model differ from that of C++11? | C++11 introduces a new memory model that lets the abstract machine "running" C++11 code have a notion about multiple threads. It also introduces a set of memory orders by which memory load/store operations abide.
The wikipedia page of C++20 says that it has
a revised memory model.
The reference it gives says that the... | As @PeterM suggests, its' a (subjectively) minor change due to issues discovered ex-post-facto with the formalization of the C++11 memory model.
The old model was defined so that different regimes of memory access could be implemented on common architectures using more or less-costly sets of hardware instructions. Spe... |
62,488,270 | 62,490,176 | Unexpected result when initializing variable in C++ using curly braces | I'm using atom to practice C++ (I'm very new). I just learned to initialize variables like the following:
#include <iostream>
using namespace std;
int main() {
int myInt {};
return 0;
}
When I build and run the previous code in codelite I receive no errors. However, if I compile my atom file dailyPractice10.... | Because this feature is added from c++11.
if you will like to try below command.it will work.
$ g++ -std=c++0x -o dailyPractice10 dailyPractice10.cpp
|
62,488,465 | 62,489,045 | How to use and access static pointer-to-member value s_ptm inside class? | We can declare and use instance-level pointer-to-member value/func inside class.
And using obj.*(obj.ptm) or ptr->*(ptr->ptm) pattern to access.
But if declare them as static type-level s_ptm value/func, how to initialize and access/use them?
class C
{
public:
static int s_i;
static int C::* s_ptm; //declar... | Pointers to static members are just plain pointers. You cannot assign a pointer to a static member to a pointer to member. The good news is: You don't need it. Pointers to members enable you to point to a member and then given an instance you can access its member via that pointer. For a static member this isnt needed,... |
62,488,476 | 62,488,556 | In C++11 and beyond, Is there a way to initialize a vector in an initializer list? | For a class containing a vector of strings, suppose we want a constructor which can either pass in a list or a single value. How can the second constructor call the first in an initializer list?
class A {
private:
std::vector<const char*> paths;
public:
A(std::vector<const char*>& paths) : paths(paths) {}
A(const... | You are creating a temporary vector, thus you should use a const reference in your first constructor:
class A {
private:
std::vector<const char*> paths;
public:
A(const std::vector<const char*>& paths) : paths(paths) {}
A(const char* p) : A(std::vector<const char*>{ p }) {}
};
Alternatively, think about using r-... |
62,488,643 | 62,489,987 | Why is this if statement triggered in this C++ code? | This code is supposed to reverse a linked list. The following code returns an empty linked list even when provided with a non empty list.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* curr, *prev, *next;
if (head == NULL)
{
return head;
} ... | Pretty simple, you have to initialize the pointers, else it leads to unexpected behavior that includes not showing it at all or just showing it if an initialized cout is triggered - but it doesn't have to do anything and that's up to your compiler implementation.
//cpp17
listNode* curr{}, *prev{}, *next{};
//befor... |
62,489,128 | 62,491,456 | Practical use cases for alignof and alignas C++ keywords | I just learnt about alignof and alignas C++ keywords but I can't think about any practical case where a developer would want to use these keywords.
Does somebody know any practical use case for these keywords?
| A common use case for the alignas specifier is for the scenario where you want to pass multiple objects between different threads through a queue (e.g., an event or task queue) while avoiding false sharing. False sharing will result from having multiple threads competing for the same cache line when they are actually a... |
62,489,239 | 62,490,428 | Is std::stack contiguous? | I wanted to find the maximum element in a stack, and thought of using std::max_element.
Then I came to know that std::stack does not have begin() and end() functions. After surfing the net, I saw a hack:
stack<int> s({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto end = &s.top() + 1; // instead of std::end
auto begin = end -... | Is std::stack contiguous? I would say, it doesn't matter. std::stack is not a container, but an adapter, and its idea is the stack abstraction and a deliberate restriction of interfaces.
Even if it were contiguous, accessing elements of std::stack by any means but .top() would be a violation of its semantics. If you ne... |
62,489,411 | 62,489,625 | Can someone help me understand these parameters/arguments? | I have been given some code for a Binary Search Tree and tasked with adding some functionality to it. But first, I would really like to gain a better understanding of the parameters/function definition for one of the functions given to me. The code:
void printTree( ostream & out = cout ) const
{
if( isEmpty( ) )
... | const after function declaration means that it is safe to use this function for const object of your class. Such functions can't change any fields in your object.
ostream & out is a global object std::cout that control output to a stream buffer of implementation-defined type. In simple words this object helps you to pr... |
62,489,558 | 62,489,611 | why does int myVar {5} give an error and not work? | i am taking a c++ course and the instructor said to make variables like this:
int main() {
int myVar {5};
return 0;
}
this gives me an error:
"expected ";" at the end of declaration"
what is wrong?
| Uniform initialization requires C++11.
If you use
g++ --std=c++11 [...]
it should work.
test> g++ foo.cpp
foo.cpp:3:6: error: expected ';' at end of declaration
int x{7};
^
;
1 error generated.
test> g++ --std=c++11 foo.cpp
test>
with
test> more foo.cpp
int main()
{
int x{7};
}
|
62,489,769 | 62,490,008 | How to do recursion based on tuple elements? | I'm not sure if this is possible, but I would like to be able to recursively call a function based on the elements of a tuple. So for example a tuple such as std::tuple<int,float,double> should call expand_nested 3 times, and in turn invoke it's callback function with a parameter of type either int, float or double.
#i... | Syntax for parameters pack in expand_nested should be:
template <typename T, typename ... Rest>
void expand_nested(tree_item<T> ti, tree_item<Rest>... rest)
This
ti.callback(ti.param);
expand_nested(ti, rest...);
will give you infinite recursion (you are calling the same function with the same number of arguments of ... |
62,489,787 | 62,489,872 | std::thread causes program to abort | I have the following code snippet:
#include <thread>
int main(){
std::thread trial([](){ return 2;});
//trial.join()
return 0;
}
From this I get the following output:
terminate called without an active exception
[1] 17963 abort (core dumped) ./a.out
Now, this doesn't happen when I call .join() after I... |
Could somebody explain what's going on?
From the documentation of the destructor of std::thread:
If *this has an associated thread (joinable() == true), std::terminate() is called.
In the example, you failed to join the thread, therefore it is joinable when it is destroyed, therefore the process std::terminate() is... |
62,490,271 | 62,491,328 | Conditional class member based on template | I want to have a class that receives a mutex type as template parameter to be (conditionally) thread-safe. If the mutex type is equal to NoMutex(my mutex empty implementation), I don't want to add this mutex member to my class so I can save space.
I want to do something like this:
class NoMutex{
// Same interface as st... | Empty data members can be optimized away using empty base-class optimization (EBO). That is, although a stateless class has non-zero size (at least 1 byte), it doesn't consume additional memory if used as a base class:
template <typename Mutex>
struct CompressedMutex
{
Mutex mutex;
Mutex& getMutex() { return mu... |
62,490,372 | 62,538,017 | Qt Visual Studio 2015 Add-in compilation problem | I use Qt Add-in in my project. But i dont understand , what i do uncorrect.
My .pro file:
QT += core gui network
TEMPLATE = app
TARGET = MMworker
DESTDIR = ../Debug
CONFIG += debug
LIBS += -L"../../../../boost_1_70_0/stage/lib"
DEPENDPATH += .
MOC_DIR += .
OBJECTS_DIR += debug
UI_DIR += .
RCC_DIR += .
Get a lot ... | Error was in inlcude additional dependensies(removed) and included dirs(added)
|
62,490,972 | 62,491,288 | Cython example for sending array/vector to a c++ script | Say we have a 1 dimensional numpy array or list that we use as an input to a function, i.e., func(np.array[1.5, 2.5, 3.5]), where this function comes from a wrapped c++ class and our goal is to print the values of this array or vector inside the c++ script.
However, I don't know how to define the c++ function for this... |
a is a variable that contains a pointer to zero or more int.
n is a the number of values that a contains.
You can index a using the standard C++ array access syntax a[i]. Make sure i < n.
The C++ header would then look like:
void func(int *a, int n);
The .pyx file would be something like
cdef extern from "myheader.h... |
62,491,255 | 62,493,311 | How to connect with SQLConnect from ODBC? | I'm trying to connect to SQL Server with ODBC and C++ but It can't connect I don't know why. The DSN is
already set in User DSN list.
Windows 10 64 bits
Compiler: VC++ 2010
ODBC version: 2017.175.02.01
SQL Server 2019
# include "stdafx.h"
# include <windows.h>
# include <stdio.h>
# include <stdlib.h>
# include <sql.h... | This will not do what you think it does:
(SQLWCHAR*)"db1",
If SQLWCHAR* is a pointer to a wide-character, then casting a non-wide string-literal will not produce the results desired, since casting will not magically convert the non-wide string literal to a wide string. The ODBC function is failing due to the "db1" str... |
62,491,316 | 62,491,827 | CMake include library in another library | I have a given project structure
.
├── CMakeLists.txt
├── lib
│ ├── lodepng
│ │ ├── CMakeLists.txt
│ │ └── src
│ │ ├── lodepng.cpp
│ │ └── lodepng.h
│ └── pixel_reader
│ ├── CMakeLists.txt
│ └── src
│ ├── hello.cpp
│ └── hello.h
├── main.cpp
With the followi... |
Why is my code not finding the 'lodepng.h' file or (and even more important)
Because you probably didn't give it correct path. One way to fix that would be to give the exact path in hello.h
#include "../../lodepng/src/lodepng.h
Second way is to use target_include_directories:
target_include_directories(pixel_reader P... |
62,491,337 | 62,491,703 | Boost split string by Blank Line | Is there a way to use boost::split to split a string when a blank line is encountered?
Here is a snippet of what I mean.
std::stringstream source;
source.str(input_string);
std::string line;
std::getline(source, line, '\0');
std::vector<std::string> token;
boost:split(token,line, boost::is_any_of("what goes here for bl... | You can split by double \n\n unless you meant blank line as "a line that may contain other whitespace".
Live On Coliru
#include <boost/regex.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <sstream>
#include <iostream>
#include <iomanip>
int main() {
s... |
62,491,625 | 62,491,715 | base ten number to array of bool that repricent a binary/base 2 number | I am trying to create a function in C++ that will take in a den number and return a bool array that represents a binary/base 2 number I need the array to be 16 items long any help would be appreciated thank you.
| You can use std::bitset<n> directly without any function as follows
#include <iostream>
#include <bitset>
int main(){
constexpr size_t myInt = 2;
constexpr std::bitset<16> binaryRepresentaion {myInt};
std::cout << binaryRepresentaion;
}
The out is
0000000000000010
Live
I borrowed constexpr from Berto99. I... |
62,491,755 | 62,491,939 | constexpr construction of a POD struct with a char[] field | How can I make the function below constexpr?
This is a function that I use to create a POD struct that is defined in a "C" header file that I cannot change.
I ended up with the following static function helper (which works) to make these structs, I believe it is not constexpr, as the strncpy call violates constexpr.
st... | A bit of twiddling around std::integer_sequence and I got it:
#include <utility>
#include <iostream>
extern "C" {
#define SIZ_WAYPOINT_NAME 9
typedef struct {
char seven;
char name[SIZ_WAYPOINT_NAME];
double lat;
double lon;
double crs;
double az2; ... |
62,491,888 | 62,492,073 | C++ multiply float by fraction | just started C++ from a MATLAB background and getting confused.
float farenheit, celcius;
cin >> farenheit;
celcius = (farenheit - 32) * (5 / 9);
cout << "Temperature (c): " << celcius;
why does multiplying by 5/9 not work as expected, but this does?:
float farenheit, celcius;
cin >> farenheit;
celcius = ((farenheit -... | Thanks everyone,
C++ interprets 5 and 9 as int values so 5/9 is also an int.
5/9 = 0.566 which is truncated down to 0.
To fix this, append .0 or .f to the values be interpreted as a double or float respectively.
|
62,492,020 | 62,492,228 | Is std::less supposed to allow comparison of unrelated pointers at compile-time? | Consider this code:
#include <functional>
#include <typeinfo>
template <typename T>
inline constexpr const void *foo = &typeid(T);
int main()
{
constexpr bool a = std::less<const void*>{}(foo<int>, foo<float>);
}
Run on gcc.gotbolt.org
If I use < instead of std::less here, the code doesn't compile. This is not ... | I don't think there's a clear answer to the question that you're asking. This is a specific case of LWG 2833: marking a library function constexpr does not explain the circumstances under which calling the function will yield a constant expression.
Until this issue is resolved, I think you simply cannot rely on std::le... |
62,492,143 | 62,492,310 | function pointers and arbitrary parameters | Imagine I want to write a function that does something with the values of two functions (like a comparison, as example).
f1 and f2 are examples, but it should work for more functions, independent of number and type of arguments.
double f1 (double x, double y, double z) {
return pow(x,3)+2*pow(y,2)+3*z;
}
double f2... | I can't see the target here, so it's hard to make it a generic solution, but basically you can do something like that:
template<typename FuncA, typename FuncB>
void compare(FuncA func_a, const std::vector<double> &vec_a, FuncB func_b, const std::vector<double> &vec_b) {
double res1 = func_a(vec_a[0], vec_a[1], vec_... |
62,492,181 | 62,509,886 | Efficient parallel union of sets with OpenMP | I need to calculate a global std::set (or equivalently a global std::unordered_set) in an OpenMP parallelised programm. At the moment every thread has a local std::set which then later the union is calculated from using
#pragma omp critical //critical as std container inserting is not thread safe
global_set.insert(loc... | You should read up on OpenMP reductions, and, in particular user-defined reductions. That lets you pass the problem to the OpenMP implementation, which will very likely perform the reduction up a tree.
Of course, whether that is beneficial is not clear; it may be that it simply introduces a lot of copying and memory al... |
62,492,189 | 62,492,514 | ES6 Modules with top-level await on embedded v8 | How would one make top-level await in ES6 Modules? I have gotten regultar ES6 modules to work, but I can't find anything about top-level await in ES6 modules with v8.
here is my code:
v8::Local<v8::Module> FactoryModule(v8::Isolate* isolate, v8::Local<v8::Context> context, const char* moduleName, const char* code) {
v8... | Top-level await in V8 is under active development, see the tracking bug: https://bugs.chromium.org/p/v8/issues/detail?id=9344
|
62,492,262 | 62,492,570 | Create Executable from Linux using Qt 5, C++ and OpenCV | I've been trying to deploy an executable version of my program, I tried in many ways as
Running it in release mode
linuxdeployqt tool
GitHub + Jenkins
but those hasn't worked for me, I can deploy the program in the development enviroment, but I need to install it in different computers. If if's possible to create the... | I would suggest you to try using CQtDeployer from https://github.com/QuasarApp/CQtDeployer
You can find instalation guide in this video , even though it isn't in english language, everything is described step by step in there.
Hope that would work for you.
|
62,492,288 | 62,492,592 | Can't receive the correct output from multiple files using g++ | I just learned about C++ classes in multiple files, but I cannot get the output I expect from it...
(main.cpp)
#include <iostream>
#include "Dog.h" //include to be able to use the class
using namespace std;
int main(){
Dog myDoggy();
cout << "here";
return 0;
}
(Dog.cpp)
#include "Dog.h" // includes the... | The following rule apply for ambiguity between variables and functions: If it looks like a function, it is a function.
Based on: C++ reference
In case of ambiguity between a variable declaration using the
direct-initialization syntax and a function declaration, the compiler
always chooses function declaration; see dir... |
62,492,738 | 62,493,109 | Exporting FEATURE_FLAG recursively to makefiles, CPP and Header files |
FEATURE_FLAG is applicable to feature_folder - being newly introduced in the build system based on below condition in the top level makefile.
ifdef FEATURE_AAA
export FEATURE_FLAG=0
else
export FEATURE_FLAG=1
CPP and Header files inside the feature_folder further include some headers based on FEATURE_FLAG as below.
... | You have set the make variable FEATURE_FLAG. Make variables exist in your makefile, they do not exist (automatically) in your compiler when it compiles your code.
If you want to pass a value from your makefile into the compiler as a C or C++ preprocessor macro definition, you have to put it on the compiler's command l... |
62,493,020 | 62,494,459 | Regex to match a repeating pattern of a number followed by any kind of delimiter? | I have a text file that consisted only with numbers separated by delimiters. The delimiter can be comma, space, line break etc other than number.
1, 2, 3, 4
1 2 3 4
1|2|3|4
1hello2hello3hello4
I am looking for a regex to match this repeating pattern throughout the text file. And the expected outcome will be either "m... | You could use the following regular expression to obtain the fixed string that serves as a delimiter between consecutive strings of digits, or conclude that at least two delimiters are unequal. The delimiter string, provided there is a match, will be the contents of capture group 1. The attempted match will be unsucces... |
62,493,070 | 62,493,119 | Why does my operator + overload call my copy constructor despite being passed by reference? | I've done some research, but I have not been able to find an explanation for the behavior of my code (I may not be asking the right questions). I'm working in C++, using VS2019.
The code regards the Points class found in the Data Structures and Other Objects textbook.
My class as it exists now:
class point {
private:
... | Creating a temporary point and changing its values will not call the copy constructor.
You are returning an object here, not a pointer or a reference to an object:
point operator + (const point& A, const point& B) { //Adds x1 to x2, y1 to y2
when you return from your function a new object is created from the one that ... |
62,493,219 | 62,493,260 | Dividing 2 long values produces wrong output in c++ | I am dividing 2 long values and use the ceiling of the result. However my code produces wrong output.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main(){
long first = 100;
long second = 1000;
long output = ceil(first/second);
cout<<"output = "<<output<<endl;
}
Here the exp... | Because of order of evaluation of long output = ceil(first/second);
The first operation is first/second, 100/1000. Once you are using integer types (long is an integer) the result will be a long and it is truncated towards zero. 100/1000 =0
Then you have:
ceil(0) = 0 // as expected
long output = 0
|
62,493,573 | 62,494,128 | Why Android Studio compiles C++ to ARMv7 if my phone is ARMv8? | I have an Mi 9 phone, which has a SnapDragon 855, which as far as I could tell runs ARMv8.
I created a simple C++ NDK project in Android Studio, and tried to link a library compiled for aarch64 which is ARMv8, however it complains because it's trying to compile for ARMv7.
I think ARMv7 can run on ARMv8, but why does it... | modify build.gradle like following:
defaultConfig {
ndk {
abiFilters 'arm64-v8a'
}
}
|
62,493,770 | 62,495,714 | How to add roll in camera class | I am building a camera class and have taken help from the online tutorials for building this class.
Now i want to add roll in the camera and could not find any reading material which would explain how to add Roll in camera.
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 500.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, ... | To roll the view, you have rotate the up vector (Up) around the line of sight (Front).
Define a rotation matrix around Front by Roll:
glm::mat4 roll_mat = glm::rotate(glm::mat4(1.0f), glm::radians(Roll), Front);
Transform the Up vector by the matrix:
Up = glm::mat3(roll_mat) * Up;
|
62,494,294 | 62,510,454 | Are C++ atomics preemption safe? | From what I understand of atomics, they are special assembly instructions which guarantee that two processors in an SMP system cannot write to the same memory region at the same time. For example in PowerPC an atomic increment would look something like:
retry:
lwarx r4, 0, r3 // Read integer from RAM location r3 int... | This is similar to this question: Anything in std::atomic is wait-free?
Here are some definitions of lock-freedom and wait-freedom (both taken from Wikipedia):
An algorithm is lock-free if, when the program threads are run for a sufficiently long time, at least one of the threads makes progress.
An algorithm is wait... |
62,494,740 | 62,494,755 | Random error core dump :Error in `./a.out': free(): invalid next size (fast): 0x00000000010e8d70 *** Aborted (core dumped) | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using std::string;
int edit_distance(const string &str1, const string &str2) {
std::vector<std::vector<int>> strMat(str1.length()+1,std::vector<int>(str2.length(),0));
for(int i=0;i<=str1.length();i++){
strMat[i][0] = i;
}
for(... | What happens is that you are going out of bounds when writing to the vector.
You shouldn't use C style [] to access the array instead you should use .at(index) because it does bounds checking.
std::vector<std::vector<int>> strMat(str1.length()+1,std::vector<int>(str2.length(),0));
The inner vector is of size str2.le... |
62,494,791 | 62,497,315 | CMake passes C++ arguments to nvcc | I'm working on a project that mixes C++ and CUDA. In addition it links 3rd party libraries, specifically we suspect this problem comes from aws-sdk-c++.
The problem is that when we link against our libraries that uses AWS, a -pthread flag is added to the compile options of our target. Our target project has both .cpp &... | Looks like there was a bug in CMake mixed with CUDA 10.0.
Upgrading to CMake 3.17.3 as suggested here didn't solve it until I upgraded to CUDA 10.2, in that case CMake 3.17.3 worked
|
62,494,872 | 62,494,906 | C++ return value type (integer) does not match the function type | #include <iostream>
#include <ctime>
using namespace std;
void randNum()
{
int num1 = (rand() % 12) + 1;
int num2 = (rand() % 12) + 1;
int answer;
answer = num1 * num2;
return answer, num1, num2;
}
int main()
{
srand(time(NULL));
}
I get the error return value type does not match the functio... | You can't return 3 things. You may wrap it in a struct if you wish. And make your function return the struct instead of void. In main, call your function
#include <iostream>
#include <ctime>
using namespace std;
struct three_values {
int a;
int b;
int c;
};
three_values randNum()
{
three_values retur... |
62,495,284 | 62,495,861 | Qt5: Send Headers in a QOAuth2AuthorizationCodeFlow request | I am using networkauth for connecting to an OAuth application. I have been able to successfully authenticate after I receive the QOAuth2AuthorizationCodeFlow::granted signal.
Had it been a normal QNAM request, it would have been easy. But with networkauth, I don't have access to AccessToken. So I cannot directly send a... | I found the solution to my question. AccessToken can be obtained by this->myObject->token() and the Header can be set using
m_networkRequest.setRawHeader("Authorization", "Bearer " + this->myObject->token().toUtf8());
So my code snippet becomes
// private
// QOAuth2AuthorizationCodeFlow * myObject
connect(this->myO... |
62,495,428 | 62,497,462 | MayI know why this code is not giving any output? | Please help me to solve the query that this code runs infinitely at a particular line.
It does not give any output as at the end of the code I write the code to print the vector. Even after I assign any value to vector "result" manually still it is not giving any output. why is it so?
#include<bits/stdc++.h>
using name... | Your program has complete Undefined Behaviour.
Let's get started with the first problem. In the following check code
long int value, strValue; // not initialised
for (int i = 0; i < events.size(); i++)
{
// ...
// here it should have been "setpassword" (i.e. all are small letters)
if (events[i][0] == "setPas... |
62,495,482 | 62,495,508 | What does unordered_map returns when looking for a key that doesn't exist | I have an unordered_map<char, mystruct> h.
What does this return if h doesn't contain a key x?
mystruct ms = h['x'];
| If the specified key 'x' doesn't exist, std::unordered_map::operator[] will insert a value-initialized mystruct firstly, then return the reference to the inserted mystruct. After that ms is copy-initialized from the inserted mystruct.
Returns a reference to the value that is mapped to a key equivalent to key, performi... |
62,495,737 | 62,496,063 | Difference of value of **(ptr+1) in char and int | Please help me out as to why in below code outputs are different:
int z[][3] = { 1, 2, 3, 4, 5, 6 };
printf("\n**(z+1): %d", **(z + 1));
Output: (z+1): 4
char y[][3] = { "A", "F", "G", "J", "M", "P" };
printf("\n**(y+1): %c", **(y+1));
Output: (y+1): F
Why in the above two outputs, first is checking the 4th index whi... |
Why in the above two outputs, first is checking the 4th index while in second output prints 2nd index ?
That's not actually close to describing what is happening.
To understand what is happening, write the examples into their actual meaning
int z[][3] = { 1, 2, 3, 4, 5, 6 };
printf("\n**(z+1): %d", **(z + 1));
is ac... |
62,495,891 | 62,672,196 | Passing glm.mat4 from Python back to C++ (glm::mat4) | I have a boost python application that exports a class to Python, performs a calculation and returns the output back to C++:
import engine # c++ library
import glm # pyglm
class Game(engine.Application):
def __init__(self):
engine.Application.__init__(self, title, fullscreen)
self.shader = engine.S... | Ended up contacting the developer about this issue and this was there response:
This is what matrix objects look like in C++ code:
template<int C, int R, typename T>
struct mat {
PyObject ob_base;
uint8_t info;
glm::mat<C, R, T> super_type;
};
That is most likely why it's not quite compatible to glm matric... |
62,496,473 | 62,496,723 | Read all point and insert into array | I came across this gdal code to read the elevation point for specific location.
This code allow me to just read only one point. The elevation file information:
Upper Left X = 103.0000 Upper Left Y = 4.0000
Lower Right X = 104.0000 Lower Right Y = 3.0000
No. of columns = 3601, No. of rows = 3601
How can get read all... | According to the documentation at https://gdal.org/doxygen/classGDALRasterBand.html#a75d4af97b3436a4e79d9759eedf89af4 you can just specify the range you want to read.
constexpr int rows=3601;
constexpr int cols=3601;
std::vector<float> buffEleveation(rows*cols);
// Since we want to read all the data we set:
// nXOff/n... |
62,496,699 | 62,496,744 | How to convert float (*)[6] to float** type? | I want solve a 2D array using Runge Kutta method. However, I am experiencing the error given below which I couldn't solve. Can any one help me to solve this error?
[Error] cannot convert 'float (*)[6]' to 'float**' for argument '2' to
'void rnnW1_1(float**, float**)'
#include<stdlib.h>
#include<stdio.h>
#include<coni... | Simple, change
void rnnW1_1(float **W1_1, float **rsh)
to
void rnnW1_1(float (*W1_1)[6], float (*rsh)[6])
Incidentally m is undeclared in the code you posted. I'm hoping that doesn't make a difference to my answer. Please always try to post complete code.
|
62,496,902 | 62,497,027 | does std::vector copy/move elements when re-sizing? | I was messing around with move c'tors for a learning / refresh exercise and I came across something unexpected to me. Below I have a class person that contains a std::string m_name;. I am using this as a test class for copy/move c'tors.
Here is the code for quick reference:
#include <iostream>
#include <vector>
class ... | If it needs to relocate, something similar to std::move(xold.begin(), xold.end(), xnew.begin()); will be used. It depends on the value type and the vector usually does its own internal placement new . but it'll move if it can move.
Your move constructor
person(const person &&other) noexcept;
has a flaw though: other s... |
62,497,189 | 62,497,340 | Shrink a vector from N1 down to N2 items without triggering the default constructor and using only move semantics | Could you help me with an efficient way to shrink an std::vector<T> from N1 down to N2 (N2 <= N1) items in it without requiring T to have a default constructor (i.e. resize() is not an option because it requires a default constructor because it can be used to grow also), and using only move semantics (without requiring... | If you need to do it in-place, maybe just erase will be enough:
v.erase(v.begin() + N2, v.end());
|
62,497,276 | 62,497,435 | Performance difference between various specifiers in range_declaration of range-based for loop | I have seen many types of type specifiers used while declaring range for a range-based for-loop like:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (const int& i : v) // access by const reference
std::cout << i << ' ';
std::cout << '\n';
fo... | None of them is expected to perform faster or slower. You have to measure to find out on your specific platform. Or read the assembly code, which you may find out is identical for some or all of them (you can try here: https://godbolt.org/).
As an aside, if your loop bodies are actually writing to cout on every itera... |
62,497,362 | 62,497,745 | Why do I need to do 'using namespace std' instead of 'using std::cout'? | everyone.
I have learnt that it is often desirable to write in my codes using std::cout instead of using namespace std in order to avoid namespace conflicts. In the following script I only use cout and if I write std:: cout instead of using namespace std; it does not work.
Can anyone please help me understand why? In g... | Your code works okay with:
using std::cout;
statement for cout, but the compiler must know the location of string (actually it's std::string) too which you're currently using. You must define:
using std::string;
When you enter:
using namespace std;
It calls the entire namespace called std which contains a variety o... |
62,497,449 | 62,497,540 | Array pointer notation C++ (when moving array) | I have written this code,
which should move my array by 1:
// Declare and initialize Array
int temp;
int dim[5] = { 6, 7, 8, 9, 10 };
int array_size = sizeof(dim) / sizeof(dim[0]);
cout << "Array-Size: " << dim[array_size - 1] << endl;
// Move by 1 position
for (int i = 0; i < (array_size - 1); i++)
{
temp = dim... | dim[i] is syntactic sugar for *(dim + i). You can replace all array notation with the equivalent pointer notation.
// Declare and initialize Array
int temp;
int dim[5] = { 6, 7, 8, 9, 10 };
int array_size = sizeof(dim) / sizeof(dim[0]);
cout << "Array-Size: " << *(dim + array_size - 1) << endl;
// Move by 1 position... |
62,498,071 | 62,913,192 | Function gets called multiple times | So, inside the game loop function that tracks user input is called multiple times. I guess this happens because game loop goes like 40 iterations each second and if I hold down the key for a 0.5 second, function gets called 20 times. I tried to handle this with sfml events too but it didn't work window.setKeyRepeatEnab... | Use two boolean flags: One for checking if the key is pressed or not, and one that is used to check if the action have happened yet.
In short something like
if (key_is_pressed)
{
if (!action_have_happened)
{
// Perform action...
action_have_happened = true;
}
// Else: Action have already... |
62,498,076 | 62,502,609 | Matrix assignement value error in opencv C++ with mat.at<uchar>(i,j) | I am learning image processing with OpenCV in C++. To implement a basic down-sampling algorithm I need to work on the pixel level -to remove rows and columns. However, when I assign values with mat.at<>(i,j) other values are assign - things like 1e-38.
Here is the code :
Mat src, dst;
src = imread("diw3.jpg", CV_32F);/... | The second argument to cv::imread is cv::ImreadModes, so the line:
src = imread("diw3.jpg", CV_32F);
is not correct; it should probably be:
cv::Mat src_8u = imread("diw3.jpg", cv::IMREAD_GRAYSCALE);
src_8u.convertTo(src, CV_32FC1);
which will read the image as 8-bit grayscale image, and will convert it to floating po... |
62,498,491 | 62,501,447 | how does std::pmr::memory_resource makes performance difference with std::container? | for exmaple std::pmr::vector<int>l1 is faster than regular vector<int> l2. how?
what makes a major difference? How is it different than a smart pointer?
| template <typename T> std::pmr::vector<T> is an alias for template <typename T> std::vector<T, std::pmr::polymorphic_allocator<T>>. The only runtime differences are in how it allocates and deallocates memory for the elements.
The advantage of std::pmr::vector is that different allocation strategies don't have different... |
62,498,858 | 62,499,035 | How to get base object's data in a new derived object? | (Beginner in OOP.)
I have a person class which stores the name of the person. In a derived class instance printer, I need that name so that I can do further tasks with it.
#include <iostream>
#include <string>
class Person{
public:
std::string name;
};
class Printer: public Person{
public:
void print(){
... | You have made the member vars public but this is not the right approach for the OOP, the right one is to have them under private access specifier and use setters and getters.
Now to your mistakes:
You use void for main but with c++ you can only use int for it.
You use std::string as an argument for printf but it can'... |
62,498,862 | 62,510,869 | SetCurrentConsoleFontEx() doesn't work with custom installed fonts | I have a custom font installed on my environment (Pixel Operator Mono) and I'm developing some console application which needs this font. This is my function:
void set_font() {
CONSOLE_FONT_INFOEX cfi;
cfi.cbSize = sizeof(cfi);
cfi.nFont = 0;
cfi.dwFontSize.X = 0;
cfi.dwFontSize.Y = 27;
cfi.Font... | First make sure that the custom font and other normal fonts are in the same code page (usually 437), which can be set through SetConsoleOutputCP.
Next, for the setting of FontFamily, try to modify to FF_MODERN << 4 | TMPF_VECTOR | TMPF_TRUETYPE for testing.
Here is the Sample:
#include <iostream>
#include <Windows.h>
u... |
62,499,049 | 62,499,109 | Is there a way to multiply a string and an integer in C++? | In Python, there is a way to multiply a string, for example, "A" * 3 would return "AAA". However, this syntax doesn't work in C++, it just gives me an error, invalid operands of types 'const char [2]' and 'int' to binary 'operator*'. Is there a way to multiply a string like this in C++?
| There is no such operator in C++.
But you can write a function that takes a string and a number as argument, and return the repeated string.
std::string also has a constructor that repeats given character a number of times. This may be useful since you used a string of one character as the example.
|
62,499,115 | 62,536,876 | OpenGL Collisions between 2 spheres sometimes not detected | For this project i use OpenGl.
I'm trying to detect the collision between two spheres, I think it's pretty simple.
It works but sometimes (very often actually...) the collision between these two spheres is not detected, and I really don't know why...
I tried to change the algorithm of detection and it allways ends by a... | I finally manage to find out what was happening.
The problem is that my world is avoiding collisions. What I mean by that is: when two objects collide, they automatically bounce against each other.
This behaviour was the problem because the goal of my hunting ball is to collide against the other objects so.... randomly... |
62,499,765 | 62,500,303 | std::reduce with functor | I tried to use std::reduce with a functor to calculate the number of characters in an array. GCC gives an error, while it compiles and works in MSVC. link here
#include <iostream>
#include <array>
#include <numeric>
#include <cstring>
int main()
{
std::array arr{ "Mickey","Minnie","Jerry" };
struct StringLengt... | I agree with dewaffled that this is a bug. The libstdc++ implementation of std::reduce looks like this:
template<typename InputIt, typename Tp, typename BinOp>
Tp reduce(InputIt first, InputIt last, Tp init, BinOp binary_op) {
using value_type = typename iterator_traits<InputIt>::value_type;
static_assert(is_in... |
62,499,814 | 62,499,995 | Why does my program display the null vector? | I don't understand why my program displays the nul vector :
#include <vector>
#include <iostream>
template <class T>
std::vector<int> collect_values(const T & t, int first, int next_to_last) {
std::vector<int> v(next_to_last-first);
for(int i=0; i<next_to_last - first; i++) {
v[i] = t(v[i]);
}
... | in collect_values
std::vector<int> v(next_to_last-first);
because next_to_last-first values 5 you create a vector sized 5 where all the elements value 0
v[i] = t(v[i]);
because t returns the square or its parameter but each element values 0 the vector is unchanged reassigning all the entries with 0
return v;
... |
62,499,825 | 62,499,915 | Is there a reason not to use the newest C++ standard? | I have seen that the default standard in IDEs is usually not the newest released standard, not even the newest standard in the IDE.
For example JetBrains' Clion has C++20 and C++17 but the default option is C++14.
Is there a reason not to use the newest released standard?
| As a general rule, use the latest standard if you can.
But, there are some reasons why you may in some situations choose to use an older one.
Your code makes use of features that changed behaviour in newer standards or were removed outright. If you don't have time to update your code, compiling for the older standard ... |
62,500,492 | 62,522,001 | Intel TBB program does not terminate, possible misuuse of reference counter | I have the following TBB code snippet. The code does not work as expected.
#include <iostream>
#include <tbb/mutex.h>
#include <tbb/tbb.h>
using namespace std;
using namespace tbb;
tbb::mutex printLock;
class Task1 : public task {
public:
task* execute() {
printLock.lock();
cout << "Task 1 start" << std::e... | The issue is near asynchronous task. When Task 5 finishes, it signals Task 4 to decrement its refcount that reaches zero and Task 4 is run again. So, there is a loop. As a result it leads to a race on refcount of Task 3 that causes an additional loop. For asynchronous pattern, you need to use continuation passing appro... |
62,500,676 | 62,501,033 | C++ Reading an entire file directory | I've made a short program that reads a set number of text files and extracts some targeted information out of them. However, this relies on me adding all those text files into the project folder and renaming every single one of them individually to give their names a pattern.
What I'd like to make my code read ALL file... | You want to utilize std::filesystem::directory_iterator in C++17 standard library.
A minimal example:
#include <filesystem>
#include <fstream>
int main()
{
for (auto& file : std::filesystem::directory_iterator{ "." }) //loop through the current folder
{
std::ifstream fs{ file.path() }; //open the fi... |
62,500,854 | 62,501,906 | Get time spent by process in Kernel space | I am interested in how to do this in Windows
The only API I found that could do this was GetProcessTimes. I returns true, fills the creation time and exit time structure, but the kernel and user time ones remain 0. I tried Sleeping, calling APIs that execute in kernel-mode thinking I could get it to change, but it rema... | I can see three issues with your code. Firstly, this:
time = (*(reinterpret_cast<unsigned long*>(&pKernelTime)
) / 10000000ul);
should be this:
time = (*(reinterpret_cast<unsigned long long*>(&pKernelTime)
) / 10000000ull);
Then, also, change time to be an unsigned long long.
Secondly, time as been truncated... |
62,501,186 | 62,504,001 | Accelerating hough transform algorithm in dm script using C++ | Recently I tried to run Vincent Hou's Hough Transform script in https://www.felmi-zfe.at/dm_script/ for an image (1024*1024). The script take around 4mins on my computer. Then I tried to use the sampleInterface example in Gatan DMSDK to transform the dm script into C++ files and compile it into a DM plugin then tried t... | This is not actually a DM-scripting question, but if you want to compute an image-array in the SDK you have to address the native, underlying number array (which is 1D and of a specific number type.)
Typical code for this is found in the SDK example, specifically in the DMSDK\LibrarySuite\LibrarySuite.cpp in the functi... |
62,501,294 | 62,630,004 | Quickly press this key when a specific key is pressed. How prevent the trigger key to be pressed? (c++) | I'm sorry if the title is unclear.. buuut I didn't know how to put things shorter :c
The (extract) code below is supposed to quickly press / send key 'A' if key 'U' is pressed / sent. But if I press 'U' it will first send 'U', then several 'A' right after. How can I make it such that key 'U' is not sent at all? I have ... | You're calling GetAsyncKeyState() in a loop. If detects if the key is pressed down. It is calling the function multiple times during the time that key is pressed. When you press a key it's typically for 5-25 milliseconds, so GetASyncKeyState() is detecting the key press multiple times.
GetASyncKeyState() returns a s... |
62,501,395 | 62,501,540 | OpenGL can't update vertex buffer with VAO procedure | I'm attempting to move a vertex by modifying it's positional vertex attribute. As a test, I have added the line vertices[0] = 0.4f; both before and after the creation of my VAO procedure, to see whether I am able to modify the vertices array after an initial render. When I add it before the VAO creation, it modifies th... |
[...] From what I understand, a VAO is a construct for storing a rendering procedure, [...]
No it is not. A Vertex Array Object stores states.
When glBufferData/glBufferSubData is called, then the buffer object's data store is initialized respectively updated.
When glVertexAttribPointer is called, then states are set... |
62,501,852 | 62,502,833 | How can i optimize this below program? | You are given an array A of length N. For any given integer X, you need to find an integer Z strictly greater than X such that Z is not present in the array A. You need to minimize the value of Z.
INPUT:
First line : Two space seperated integers N and Q denoting the number of elements in array A and the
number of queri... | Your complexity by query is O(n)*(Z-X),
you might already reduce to O(n)+(Z-X) with:
ll x;
std::cin >> x;
x++;
auto it = mp.find(x);
if (it != mp.end()) {
while (it != mp.end() && it->first == x) {
++it;
++x;
}
}
std::cout << x << std::endl;
But I think that building intervals in pre-processing... |
62,502,283 | 62,512,030 | Is it safe to implicitly convert a `uint8_t` (read from a socket) to a `char`? | I am confused by the C++ conversion rules regarding unsigned-to-signed and vice versa.
I'm reading data from a socket and saving it in a std::vector<uint8_t>. I then need to read a part of it
(assuming it is ASCII data) and save it in a std::string. This is what I'm doing:
for (std::vector<uint8_t>::const_iterator it =... | From implicit conversions - Numeric Conversion/Integral conversions:
To unsigned
If the destination type is unsigned, the resulting value is the
smallest unsigned value equal to the source value modulo 2n where n
is the number of bits used to represent the destination type. That is,
depending on whether the destinati... |
62,502,441 | 62,502,610 | Arduino function parameters | Code
#include <SPI.h>
#include "Ucglib.h"
Ucglib_ILI9341_18x240x320_HWSPI ucg(/*cd=*/ 8, /*cs=*/ 7, /*reset=*/ 5);
void functionBar()
{
ucg.begin(UCG_FONT_MODE_TRANSPARENT);
ucg.clearScreen();
ucg.setRotate270();
ucg.setColor(94, 88, 107);
ucg.drawBox(0,0, 320, 20);
ucg.setColor(255,255, 255);
ucg.se... | The type of the parameter in ucg.getStrWidth is const char*. So use this type as a parameter in your function too.
|
62,502,899 | 62,504,642 | Using too many alternative operator in boost::qi caused segmentation fault | I generated a simple code using qi::spirit:
#include <boost/spirit/include/qi.hpp>
#include <string>
using namespace std;
using namespace boost::spirit;
int main() {
string str = "string";
auto begin = str.begin();
auto symbols = (qi::lit(";") | qi::lit("(") | qi::lit(")") | qi::lit("+") |
... | Your problem is a classic mistake: using auto to store Qi parser expressions: Assigning parsers to auto variables
That leads to UB.
Use a rule, or qi::copy (which is proto::deep_copy under the hooed).
auto symbols = qi::copy(qi::lit(";") | qi::lit("(") | qi::lit(")") | qi::lit("+") |
qi::lit("/") | qi::lit("-") |... |
62,502,915 | 62,503,451 | How do I organize a vector based on two factors: id and quantity? (C++) | So, what I'm trying to do is:
I have a vector of structs.
This is the struct:
struct item {
int id;
int quantity;}
I will have a vector of them. I don't know how to get it to be organized by the id, except when two items have the same id: In that case, whichever item had a larger quantity would come first. Do you thin... | you can use predefined sort function and write your own comparator function and pass it as a third argument.
this comparator function return bool value which tell the sort function the exact order we want.
comparator funtion for your case is given below :
bool cmp( item a, item b)
{
if( a.id == b.id ) // if id is s... |
62,503,195 | 62,503,400 | How to convert unsigned char* to an unsigned char array in C/C++? | My function looks something like this:
void Example(const unsigned char* bytes)
{
unsigned char buffer[2048] = {0};
strcpy(buffer, bytes);
}
This does not work. How do I make this work?
| you do need to convert anything. if you want to copy from one
void Example(const void *bytes, size_t len)
{
unsigned char buffer[2048];
memcpy(buffer, bytes, len);
/* ...*/
}
example usage
int foo(void)
{
char str[] = "Hello world";
Example(str, sizeof(str));
}
|
62,503,418 | 62,507,297 | Adding Different Components in Tab Control Win32 | I am creating a Windows desktop application using win32 api in visual studio 2019. I know there are many other options avialable to build UI like MFC, XAMAL and C#, but i needed to build it in win32. I have learnt some basics in win32 api but recently i was working on tabControll and there i got an issue or i missed so... | The tab control triggers the WM_NOTIFY signal when the tab page is switched, so as long as we process the WM_NOTIFY message, we can control the tab control message.
In the WM_NOTIFY message:
wParam: a control ID that identifies the WM_NOTIFY message sent.
lParam: a pointer to the NMHDR structure.
Therefore, we can dete... |
62,503,887 | 62,504,220 | C++ function is leaking memory, I'm new to C++ and not sure how to fix it | I'm very new to C++ and is trying to compile a program, however it's leaking memory and this part of the code.
char* ReadString(u_int address, unsigned int size) {
char* data = new char[size];
for(int i=0; i < size; i++){
vm_readv(reinterpret_cast<void*>(address + (sizeof(char)*i)), reinterpret_cast<voi... | Don't use raw new and delete. It was never good practice to use new whenever you need to create an object in C++. If you need a string then use std::string. It's resize method lets you resize it and some_string[i] lets you access the i-th character. I assume vm_readv reads a single character, though I am a bit confuse... |
62,504,276 | 62,504,414 | Is there a common way to implement invariants? | This is a basic example where i want to add intvariants, for example that my age can't be under 0.
#include "InvariantTest.h"
#include <iostream>
#include <string>
using namespace std;
int age;
string name;
void setAge(int a) {
age = a;
}
void setName(string n) {
name = n;
}
string getNameandAge() {
s... | Usually you’d want to at least add a debug assertion assert(a > 0) (this will throw an exception when running the debug build of your program) in addition to the if (a > 0) age = a;
You can also probably throw a full-fledged exception instead of asserting when the contract is not upheld, so that the program will termin... |
62,504,326 | 62,504,367 | How do I fix LoadIcon() Function not displaying icon? | I am trying to use a custom icon for my 3D game's application window (see My first question on this site for details on the 3D game) using the LoadIcon() function. I initialized the instance handle like I saw on a code forum site (not anything similar to this one and I'm not even signed up for it) which was to call th... | LoadIcon only loads art assets from resources compiled into EXEs and DLL. It takes a resource ID as a second parameter. (The fact that it's typed a string makes it confusing). Also, I don't think you can load png files directly via LoadIcon.
Add you .ico file to your resource file (.rc file) with your Visual Studio p... |
62,504,576 | 62,505,194 | Call `+=` on a PyObject in C++ | I'm writing a Python module in C++.
At a certain point, I need to add a PyObject of an arbitrary type to another one. In other words, do the same as a += b would do in Python. But I haven't been able to find a function in the API that does that.
I tried to do the following,
PyObject* increment(PyObject* a, PyObject* b)... |
At a certain point, I need to add a PyObject of an arbitrary type to another one. In other words, do the same as a += b would do in Python. But I haven't been able to find a function in the API that does that.
The function you weren't able to find is PyNumber_InPlaceAdd.
x += y
at Python level is equivalent to
sum =... |
62,504,752 | 62,504,817 | How to write the same function with same name that handles different class arguments almost similarly in C++? | I have two different classes
class A_class {
public:
string member_to_add_to;
}
and
class B_class {
string member_to_add_to;
}
They both are almost similar with a slight difference in member variables. There is no inheritance involved. They both are used in different sections that do not merge together. I kno... | Use a template function:
#include <iostream>
#include <type_traits>
struct A {
char const* data;
};
struct B {
char const* data;
};
template <typename T,
std::enable_if_t<std::is_same_v<T, A> || std::is_same_v<T, B>, int> = 0
>
void doSomething(T const& arg) {
std::cout << arg.data << '\n';
}
int m... |
62,505,008 | 62,507,397 | SOLVED - "fatal error: opencv: no such file or directory" in Sublime Text for c++ | I'm not having any success with #include <opencv>, no matter what I try. [EDIT: I've also tried #include <opencv2> and #include <opencv4>, but there was no difference].
For context, I'm on Ubuntu 20.04, using Sublime Text 3, the latest version of OpenCV is installed on the system (at /usr/local/include/opencv4/opencv2)... | An #include refers to a file, not a folder. A file so specified is looked for in the list of include paths.
-I /usr/local/include/opencv4/opencv2 adds that path to the list of include paths. The path, however, looks broken to me -- OpenCV has the legacy API in opencv/, and the updated API in opencv2/, but in either cas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.