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
69,978,467
69,978,525
Converting calculation contained in string to integer - C++
I was wondering if it would be possible to store caluclations contained in a string to integer. For example: #include <iostream> #include <string> using namespace std; int main() { string variable = "-123+432"; cout << stoi(variable) << endl; } This returns -123, would it be possible to make it return 309? Also what i...
It's possible for sure, but it's quite complicated to parse arbitrary strings, work out if they contain a valid mathematical expression and then work out the result. Unless you are wanting to implement the solution yourself for fun, I would suggest looking up and using a 3rd party library that evaluates string expressi...
69,979,117
69,979,139
How can I randomly generate integers in interval <-99,99> in c++?
I tried something like this but this generate only in interval (-99,0) void input(int array [row][col]){ for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++){ array[i][j] = rand() % 99 + (-99); } } }
You can use std::uniform_int_distribution for example something like std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(-99, 99);
69,979,373
69,979,585
Adding functions to string class in c++
I am using the up to date compiler for gcc. Therefore my code can execute to_String() and stoi() but unfortunately the platform that I am trying to compile my code in has a much previous one and I want to add these two functions into the string class therefore I can use them in my code without any problem.This is one o...
These two functions aren't part of the "string class". All you need is to use alternatives that existed in 1998: The to_string function isn't even needed in this context. You can simply change it to: cout << id << " not found" << endl; You can replace stoi with atoi. It doesn't throw exceptions if the conversion fai...
69,979,450
69,979,599
Round-off error when computing value inside range
For finite values v0, v1 and value r in [0, 1] range, will the value v, computed as below, always belong to [v0, v1] range, or can it be (slightly) outside due to round off errors? double v0; // Finite double v1; // Finite double r; // In [0, 1] double v = v0 * r + v1 * (1.0 - r); if (v0 <= v1) assert(v0 <= v...
Yes, it can be. Here's an example: #include <assert.h> int main() { double v0 = 2.670088631008241e-307; double v1 = 2.6700889402193536e-307; double r = 0.9999999999232185; double v = v0 * r + v1 * (1.0 - r); if (v0 <= v1) assert(v0 <= v && v <= v1); else assert(v1 <= v && v ...
69,980,168
69,980,233
Recursive parameter pack functions without parameters C++
I'm trying to create a recursive parameter pack function as follows: template <class T, class ... Ts> void myFunction() { execute<T>(); myFunction<Ts...>(); } This doesn't compile with the error: error C2672: 'Test::myFunction': no matching overloaded function found. Does anyone know how to do what I'm tryin...
If you can use C++17 or newer, you can skip the recursion and use a fold expression like template<class... Ts> void myFunction() { (execute<Ts>(), ...); }
69,980,578
69,983,371
Using fork() and exec() to execute Python code from C++
I am trying to use exec() to run Python from C++, and use pipes to communicate between the processes. I found that the C++ process keep waiting at the exec() command after the Python process terminates, which makes it unable to execute the codes below that line. Please check my code below (I have minimized the problem ...
You aren’t waiting on the child process, so the parent exits during (or, as in your example output, before) the (relatively long) startup time for Python and the shell prints its next prompt before the child prints anything. You can see this in that if you type anything on the “(blinking cursor here)” line, it gets ex...
69,981,189
69,981,359
How to find element in map where key is a shared_ptr?
I have a map of std::shared_ptr's for both key and value and I'm trying to find the right element. Below is what I have, though, it still has a problem and won't compile. std::map<std::shared_ptr<MyObjA>, std::shared_ptr<ValObj>> aobjs; std::map<std::shared_ptr<MyObjB>, std::shared_ptr<ValObj>> bobjs; template <typena...
I have a map of std::shared_ptr's for both key and value ... thoughts? A few things come to mind: 1. It is likely not a good idea to hold a map like that - especially with respect to the keys. It doesn't make sense to have "heavy" keys, that require resource allocation, and which you are likely avoiding holding many ...
69,981,591
69,981,715
Copying memory of adresses with memcpy
Base function: template <typename T> T** shifting (T* in, int size, int dist, int pos) { auto out = new T* [size]; int k = (pos-1) * size/dist; for (int i{0}; i < size; ++i) { if (i+k >= size) { out[i] = &in[k+i-size]; } else { out[i] = &in[k+i] } } re...
Your new loop body (before your edit, but my analysis remains basically the same) is: memcpy(out + i - pos + (pos + i < size ? dist: 0), in+i*helper, helper * sizeof(T*)); Expanding that for readability (which will not hurt performance, so you should do it too): T** dest = out + i - pos + (pos + i < size ? dist: 0); T...
69,981,676
69,988,903
RC4 encryption cpp algorithm
I am writing a program that can encrypt files using the cipher RC4, In my file "test.txt" is a word "Plaintext", the program should encrypt and save it also in a file (for test I was using "cout") I thing there is a problem with the last part of the code while ( plik.read(&x,1) ) { i = ( i + 1 ) % 256; j = ( j + S ...
Your algorithm is mathematically totally correct, I just did few small corrections to other parts of your code and your code made correct output. For testing purposes lets take test examples here from Wiki, first example. Input key will be Key, input file will be Plaintext, resulting file should be BB F3 16 E8 D9 40 AF...
69,982,459
69,982,575
Using compare_exchange_strong on atomic booleans (C++)
I'm new to concurrent programming and I'm trying to compile the following code: private: std::atomic<bool> resizing_; void Resize() { if (resizing_.compare_exchange_strong(false, true)... } This throws error: no matching member function for call to 'compare_exchange_strong' and I'm not sure how I can fix this. I'v...
The first parameter of the compare_exchange_strong method is a reference to the type. This method exchanges two values, but only if the comparison of the contained value and the expected value is true. Otherwise it replaces the expected with the contained value. The idiom is like this: std::atomic<int> value; int expe...
69,982,473
69,994,284
ESP8266WiFi.h: No such file or directory
How can I make the WifiManager library work on a ESP32 board? I'm using PlatformIO to develop my code. Here are my imports: #include "esp_camera.h" #include <Arduino.h> #include <WiFiClientSecure.h> #include <PubSubClient.h> #include <ArduinoJson.h> #include <EEPROM.h> #include <WiFiManager.h> WiFiClient espClient; Pu...
The latest release of WiFiManager library (0.16) is almost a year old and doesn't support ESP32. You will need to install the library from Github to get ESP32 support. In your platformio.ini replace tzapu/WiFiManager@^0.16.0 with https://github.com/tzapu/WiFiManager.git@^2.0.5-beta
69,982,811
69,983,026
Read .csv into `map<vector<uint>>`
I am trying to read a .csv file into a map<vector<uint>>. The .csv file represents a modbus register map, in the form name,register,register,register.... eg. address,1 position,10,11 status,20,21,22 I have tried this (based on https://stackoverflow.com/a/24930415/15655948), and get a segmentation fault. register_map i...
Among other assumptions, the critical one is this: while (pch != NULL) { pch = strtok(NULL, DELIMS); //<-- pch can be NULL values.push_back(strtoul(pch, NULL, 10)); //<-- BOOM! } Here, you're calling strtok, which might return NULL. But you still go ahead and convert the string anyway. This...
69,983,044
69,983,231
Unexpected output when using fork() and system() in C++
I am trying to use fork() and system() to execute another C++ program in a child process but got some unexpected outputs. Please check my code below: main: int main(void) { pid_t pid = fork(); if (pid == 0) { std::cout<<"child started"<<std::endl; system("./helloworld"); std::cout<<...
The shell is going to print the prompt as soon as the parent exits. If you don't want the child to print things after that, then you need to make sure the parent doesn't exit before the child does. You can do that by putting #include <sys/wait.h> at the beginning of your source file and wait(NULL); right before std::c...
69,983,484
69,983,548
What does repeat n times mean in gdb debugger?
For example: bool plugin::checkQuality(string &text) { string temp = normalizeContent(text, 1); map<string, int> mapWords; matchWords(temp.c_str(), mapWords); ... } Once gdb enter this function, I can see the value as: plugin::checkQuality (this=0x7fffffffd9c0, text="This is a test", ' '...
This is just the default behavior of how GDB prints more than 10 consecutive identical elements in an array. From the docs When the number of consecutive identical elements of an array exceeds the threshold, GDB prints the string "<repeats n times>", where n is the number of identical repetitions, instead of displayin...
69,983,525
70,104,420
ATTiny85 Interrupts in Arduino IDE
I have an ATTiny85 which I program using a sparkfun programmer (https://www.sparkfun.com/products/11801) and the ATTiny Board Manager I am using is: https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json Below is my code, I am having trouble getting the interrupt t...
I was way off. Here is how to set up an interrupt on the ATTiny85 using the Arduino IDE (this example uses digital pin 4 (pin 3 on the chip): #include "Arduino.h" const byte interruptPin = 4; const byte led = 3; bool lastState = false; ISR (PCINT0_vect) // this is the Interrupt Service Routine { if (!lastState) { ...
69,983,554
69,983,853
std::getline() does not ignore white space
I am new to C++ and I have some trouble preventing getline to read the new line character at the end of my text file. I tried truncating it using a newline character and then passing to a delimiter with ',' but it just doesnt work. Can you please help me understand what is going on and why I am not able to achieve what...
std::getline only accepts a single character as delimiter: Can I use 2 or more delimiters in C++ function getline? It's more clear to use two loops to read data as below: #include <iostream> #include <fstream> #include <string> #include <sstream> static int Ncol = 5; int main() { int column=0,Nrow; std::string ...
69,983,996
69,984,829
Why does 'extern template class' technique not work as expected?
The original question has been refined. Given a source code file named main.cpp as follows: #include <string> extern template class std::basic_string<char>; template<typename T> struct A { T n = {}; T get() const { return n; } }; extern template struct A<int>; int main() { auto a = A<int...
There are at least two reasons why it doesn't work. One There is no prohibition against library class and function template instantiations being declared as extern template by the implementation. gcc and libstdc++ do just that. $ g++ -E main.cpp | grep 'extern.*string' extern template class basic_string<char>; // ...
69,984,034
69,984,310
stack corruption detected when use memset in c++ from JNI Android
I am developing an Android application using C++ native code. I have C++ code (XTTEA Algorithm in C++ native) which perfectly runs online with C++ compiler and I can get the output, but when I try to use that class method using JNI cpp class, it give me the error below: A/libc: stack corruption detected (-fstack-protec...
Your input array is 8 bytes. The data parameter is a pointer to input, and the data_size parameter is 8, so theblock_size variable is calculated as 12. Your memset() is writing 4 0x00 bytes to &data[data_size], aka &input[8], which is out of bounds of the input array. So, you have a buffer overflow that is corrupting...
69,984,321
69,984,349
Why can't I assign lambdas to function parameters as a default value?
Take the following function: template<typename T> decltype(auto) find_median(T begin, T end, bool sorted = false, auto comparison = [](auto a, auto b){return a < b;}){ assert(begin != nullptr); assert(end != nullptr); return so...
You can provide a default value for a known type, but you can't provide a default value for a deduced type like this. It's just not something the language supports. You have to provide a default for the type and the value: template<typename T, typename Cmp = std::less<>> decltype(auto) find_median(T begin, ...
69,984,598
69,985,539
Using count_if() to find the same string value
I tried using a lambda expression and count_if() to find the same string value in a vector, but it didn't work. The error message is: variable 'str' cannot be implicitly captured in a lambda with no capture-default specified std::vector<std::string> hello{"Mon","Tue", "Wes", "perfect","Sun"}; for (unsigned int i = 0...
@Steven The brackets [] of lambda functions, are called a capture list. They define the scope of variables that the lambda function uses. See this reference. When you use this formatting [&], it means you can see all the variables (by reference) of the current scope in your lambda function. So the type of variables doe...
69,984,704
69,984,714
How can I specialize std::common_type<A,B> so that it's naturally commutative?
std::common_type<T1, ..., TN> is a helper template in C++ which can find the common type which all of T1 ... TN are implicitly convertible to. According the C++ spec, a user may specialize std::common_type<T1,T2> if certain conditions apply, and: std::common_type<T1, T2>::type and std::common_type<T2, T1>::type must d...
Here is the C++20 solution I came up with: // define concept of `common_type<A,B>` existing template <typename A, typename B> concept has_in_common_ordered = requires { common_type<A,B>::type; }; namespace std { // define common_type<A,B> if common_type<B,A>::type exists: template <typename A, has_in_comm...
69,985,321
69,986,674
Inter process communication from python to cpp program
Suppose there are 3 files: f1.cpp, f2.py, f3.cpp. I am running the command on linux terminal as follows: $./f1.out | python3 f2.py | ./f3.out The output of f1 goes perfectly into the input of f2. Also, f2's output goes perfectly into f3. I am displaying the output in f3. f1 generates input for f2 after a particular in...
Since you have already declared from your command that f3 should take input from f2's output and f2 should take input from f1's output, there is no straightforward way to give console input to f3 now. The best way here would be (assuming you are only the author of f1 and f2 also) you can just read that user input in f1...
69,986,173
69,986,340
Is there a way to conditionally initialize a global static variable?
So my current code looks like the following: static Item fields[] = { {GROUP1, TEXT1}, {GROUP2, 0}, } Now I need to make change in such a way that I initialize GROUP2 only if certain condition is met else need to initialize with GROUP3. So I tried the following: static Item fields[] = (flagSet)? { {GROUP1, TEXT1}, {G...
Is there a way to conditionally initialize a global static variable? Yes. The ways are pretty much the same as conditionally initialising a non-global non-static variable. You cannot however conditionally initialise an array. You could use a bit of indirection: static Item fields_true[] { {GROUP1, TEXT1}, {GR...
69,986,484
69,987,960
Cuda compile error when "cuMemGetAddressRange" exists
Here comes the sample codes: #include <cuda.h> #include <cuda_runtime.h> #include <stdio.h> int main() { unsigned char* cu_test; cudaMalloc((void**)&cu_test, 3200); CUdeviceptr pbase; size_t psize; CUresult res = cuMemGetAddressRange(&pbase, &psize, (CUdeviceptr)cu_test); printf("cu_img_yuv si...
The message: error: ld returned 1 exit status denotes that it is a linking error ( see ld ). To see this is the case, you can run nvcc -c main.cu -o main.o and you will not get any error. This is the source-code compilation step! Solution: You need to explicitly specify linkage with the CUDA driver stub library: nvcc...
69,986,491
69,986,716
how do I swap the values at index 2 and index 3 in a vector of type integer in C++?
Problem: You have to swap the values between the 2nd and 3rd index of an array. The array is a vector array consisting of 10 elements. assuming it is; std::vector<int> arr1 = { 33,12,11,13,54,65,23,67,22,10 }; Final result: before swapping: 33 12 11 13 54 65 23 67 22 10 after swapping: 33 12 13 11 54 65 23 67 22 10 ...
Version 1: Using std::swap #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> vec= { 33,12,11,13,54,65,23,67,22,10}; std::swap(vec[2], vec[3]); for(const int &elem: vec) { std::cout<<elem<<std::endl; } return 0; } Version 2: Manually using a temp vari...
69,986,510
69,986,742
How can I initialize this pointer correctly to avoid a segmentation fault?
This is my class structure class A { public: void doSomething { bInstance -> bMethod(); } ... private: std::shared_ptr<B> bInstance } class B { public: void bMethod(); } A::A(std::shared_ptr<B> bInstance) : bInstance(bInstance){} Then using GTest, this is my test fixtu...
Just fix the order of members' declaration: // Test Fixture class ATest: public ::testing::Test { protected: ATest() : bInstancePointer(std::make_shared(...)), aInstance(bInstancePointer) {} std::shared_pt bInstancePointer; A aInstance; };
69,986,883
69,988,323
Adding value to variables in array
I am creating a menu program in which user chooses a drink like tea or coffee. The essence of the program is that the user can choose drinks in the menu through the corresponding buttons (numbers 0, 1, 2, 3). The user can choose as much as he wants until he enters the number -1, which stops the program and gives the re...
Here is my full solution with lots of refactoring and cleanup: #include <iostream> #include <iomanip> void processOrder( ) { const std::string beverage[] = { "Coffee", "Tea", "Coke", "Orange Juice" }; constexpr size_t numOfBeverageTypes { sizeof( beverage ) / sizeof( std::string ) }; int beverageCount[nu...
69,987,018
69,987,225
error: conversion from 'double' to non-scalar type '' requested" struct in c++?
I want to change one of attribute in my simple struct. I can't change anything in main function. But the compiler giving me error about scalar type - what does it exactly mean and what do i wrong? #include <iostream> using namespace std; struct Number{ int a; double b; }; double zmiana(Number *number,double ...
Here is the potential fix: #include <iostream> struct Number { int a; double b; }; double zmiana( Number* number, double scale ) { number->a *= scale; return number->a; } int main() { Number number1 = { 2, 3.14 }; Number number2; number2.b = zmiana( &number1, 2. ); std::cout << &num...
69,988,150
69,999,847
seekg after reading to the end of the file
I'm trying to use the code below on the ifstream twice - before I read anything from the file, and after I read to the end of it (using readline()). m_hexFile->m_ifsteam->seekg(0, m_hexFile->m_ifsteam->ios_base::end); test1 = m_hexFile->m_ifsteam->tellg(); m_hexFile->m_ifsteam->clear(); m_hexFile->m_ifsteam->seekg(m_he...
Solution was to check elsewhere. I had closed the stream somewhere else in the program. Using the code above on a closed stream ofcourse wont work.
69,988,354
69,988,534
Binary Search Tree using std::unique ptr
I'm trying to implement a Binary Search Tree using smart pointers and I've read that the recommended way to implement it is by using unique_ptr since a parent owns the child and there are no multiple owners in a binary search tree. Take this tree for example, 10 4 ...
Then if I call delete(temp) what will happen? The TreeNode will be destroyed. Note that delete doesn't need parentheses A unique_ptr from TreeNode 2 is pointing at TreeNode 3. What will happen to this pointer? The pointer becomes invalid, and it is undefined behaviour for the unique_ptr object to be destroyed, as i...
69,988,586
69,988,818
C++ unable cout salary from method
Entry point is int main() so I try summon pwr.GetSalary to cout outside string "Salary" and double value, however program does not print out anything. So it is base class. class Employee { public: std::string FirstName; std::string LastName; std::string Patronymic; double Salary; ...
program does not print out anything Your program(pastebin link you gave) compiles successfully and prints continuously if you change _getch() to getch() as can be seen here. But for some reason it goes on forever. Since the link that you gave have around 500 lines of code i didn't take a look as to why the condition ...
69,988,841
69,988,918
Getting Python output in real-time from C++/boost::process
From a C++ program (running under Windows 10), I use boost::process to invoke Python in order to interpret a simple Python script. I want to redirect Python script's output in real-time to my C++ program's console. My problem is that I'm getting the whole Python script output at once when the program completed, I'm not...
Python streams are (like C streams or C++ ones) buffered (for performance reasons). You may want to use some flush method in your Python code. And your question could be operating system specific. For Linux, be also aware of fsync(2) and termios(3) (and pipe(7) and fifo(7)...). For other operating systems, read their d...
69,988,956
69,989,001
void(os << args). What does void mean in this context?
I was reading about folding expressions and found an example of what was used before folding expressions: template <class... Ts> void print_all(std::ostream& os, Ts const&... args) { using expander = int[]; (void)expander{0, (void(os << args), 0)... }; } The problem is the void(os << args) bit. Wha...
It casts the result of (os << args) to void. That's it. This style is used to prevent the very rare overload of ,(comma) operator since in theory, << can be overloaded for user-defined args argument and return something that has overloaded the comma operator for X, 0 expression. That might break the initialization tric...
69,989,439
69,989,491
Replacing a pair of characters in a string with another
I want to replace a pair of characters with another pair. For example if want to replace "ax" with "57" and the string is "vksax", it will give out "vks57". Tried it this way but get a weird output that is only partially correct: #include <stdio.h> #include <stdlib.h> int main() { char dummy; int i; char string[16...
Within the for loop for(i=0;string[i];i++){ if(string[i] == 'a' && string[i+1] == 'x'){ string[i] = '5' ; string[i+1] = '7'; i=0; } this statement i=0; does not make a sense. Remove it. And instead of string[i+1] = '7'; write string[++i] = '7'; And move this call printf("%s", string) ; ...
69,991,400
69,991,735
ReportEvent: Logged messages run all lines together
I'm noticing that when logging a multi-line message using ReportEvent, it drops all line ends and runs the text together. For example, my MC file may have: MessageId= Severity=Informational SymbolicName=MSG_TEST_MSG Language=English Some text Another line of text. Last line of text. . The message in Event Viewer shows...
You have to use %n to force a "hard line break" inside the message. Source: %n Generates a hard line break when it occurs at the end of a line. This can be used with FormatMessage to ensure that the message fits a certain width. "Why does Format­Message say that %0 terminates the message without a trailing newline? I...
69,991,935
69,992,768
Need help correcting Homework code, C++ input/output
I'm in my first intro to Comp Sci course. The assignment I have is inputting a .txt file and then outputting a revised .txt file. The first problems I had was just with fixing the directories. I did and everything came out fine with the .txt files, except the professor says I have an error in the switch statement. #inc...
Your version: switch (NumIn) { case -1: a += s; break; case 0: s += 1; case 1: b += s; } To fix it, add two break statements: switch (NumIn) { case -1: a += s; break; case 0: s += 1; break; case 1: b += s; ...
69,992,199
69,992,368
Why can't the overload operator<() implement the comparison function?
I was looking at this. The author first defined operator<() in my_data and said "everything is normal". After adding a member variable, he said "operator<() does not really implement a comparison operation". I want to know what is the difference between the two and why the former is wrong? struct my_data { std::st...
With struct my_data { std::string key; std::string value; //first bool operator<(const my_data data)const { return key < data.key; } }; std::set<my_data> data; You can use the class with a std::set, but your operator < isn't using all of the object, it is just comparing a single...
69,992,395
69,994,428
Error while trying to use the boost::variant - "No matching function for call"
I'm continuously getting errors saying "No matching call for function" while using boost::variant. Below is my code snippet. struct Output { int a; float b; } typedef boost::variant<ClassA<X, Y>, ClassA<>> ClassAGeneric; class Operation: public boost::static_visitor<Output> { public: double d; int...
Here's my imagined self-contained tester: Live On Coliru #include <boost/variant.hpp> #include <iostream> struct X; struct Y; template <typename... T> struct ClassA { void operate(double d, int a, float b) const { std::cout << __PRETTY_FUNCTION__ << "(" << d << "," << a << "," << b << ")\n"; } }; ...
69,992,398
69,993,534
How to get complete SID from the SidStart member in a pointer that points to an ACCESS_ALLOWED_ACE structure?
Starting with a string variable containing a Security Descriptor String Format, I convert this string to a security descriptor (using ConvertStringSecurityDescriptorToSecurityDescriptorW function). This function gives me a "pointer" to a Security Descriptor (I put the pointer under quotation mark relative to this blog ...
Thanks to @RbMm in the comment section of my question : use (PSID)&SidStart I've added this line to my project (by replacing the TODO section in the minimum reproducible example) in order to test it : PSID pSid = (PSID)&pDaclAces[0]->SidStart And then I converted it into a readable string by reusing and readapting t...
69,992,446
69,992,500
C++: location of localtime_s in GCC
Following the documentation and compiling with gcc-11.2.0 like so g++ -std=c++17 -pthread -O3 -flto -fPIC ... I am not able to use localtime_s in my program: #define __STDC_WANT_LIB_EXT1__ 1 #include <time.h> using SystemClock = std::chrono::system_clock; const auto in_time_t = SystemClock::to_time_t(SystemClock::now...
Many of the functions specified in the standard ending with _s were originally developed by Microsoft as alternates to functions ending in _r. On Linux systems, localtime_s is not defined but localtime_r is, and has the same parameters/return type, so use that instead.
69,993,346
69,993,648
Does Boost (or another library) offer a way to lift the name of a "constructor-less" class into a function object that uses aggregate initialization?
This is kind of a follow up to this question, where I asked how I could tersely turn a template and/or overloaded function into a function object. The accepted answer was you can't do without macro, which is correct. Then I found that such a macro is offered by Boost, in the form of the BOOST_HOF_LIFT and BOOST_HOF_LIF...
If you want a function object that constructs an object of some type T given some parameters, even if T is an aggregate, that's not difficult to write in C++17: template<typename T> struct lifted_construct { template<typename ...Args> T operator() (Args&& ...args) { if constexpr(std::is_aggregate_v<T>) { ...
69,993,470
69,993,940
C++ conversion operator for base type in templated wrapper
I'm trying to write a wrapper template class that allows conversion as if the templated type was used. I'm not sure how to write the template code to make this functional. See the code below: class Base { } class Derived : public Base { } template <typename ObjectT> class Wrapper { ... // Implicit conver...
Try this: template <typename ObjectT> struct Wrapper { // Implicit conversion to base types template <class T, std::enable_if_t<std::is_base_of_v<T, ObjectT>>* = nullptr> operator Wrapper<T>() const; // Explicit conversion required for other types that are convertable template <class T, std::enable_if_t< ...
69,993,580
69,993,936
Need help to correct my one way selection code
Why when i enter totalprice>50 (42 pens & above), it wont execute the if statement? Can someone help me? This is my code: #include <iostream> using namespace std; int main() { int numbersOfPen; float totalPrice, total; cout<<"Enter numbers of pen:"; cin>>numbersOfPen; totalPrice = 1.20 * numbersOf...
Adding a debug statement shows that the if statement is, indeed, executed. However, the 30/100, as @1201ProgramAlarm pointed out, evaluates to 0. In C++, dividing two integers yields another integer, so 30/100 would round down to 0. That means nothing is subtracted so it seems like the if statement never runs. To fix t...
69,993,657
69,994,014
Why doesn't gcc emit a format warning?
#include <stdio.h> void a(signed char a) { printf("%u\n", a); } void b(short b) { printf("%u\n", b); } void c(int c) { printf("%u\n", c); } void d(long d) { printf("%u\n", d); } void e(long long e) { printf("%u\n", e); } int main() { a(-1); //no warning b(-1); //no warning c(-1); /...
Short answer: C warnings are a mystery. Use -Wformat-signedness if you want warnings here. Note that -Wformat-signedness requires -Wformat, which is already enabled by -Wall. Apparently, the compiler only checks for sign mismatches when -Wformat-signedness is used. -Wall and -Wextra don't include -Wformat-signedness. ...
69,993,920
69,994,161
Unable to get time form the NTP server in esp8266, arduino
I know I am successfully connected to the network as it's visible in my phone's hotspot. However I am unable to get the time using <Time.h> library through NTP server. Thanks in advance. I will really appreciate your suggestions. platformio.int board_build.f_cpu = 160000000L platform = espressif8266 board = nodemcuv2 f...
You must wait sometime before printing the time data. Hope this work for you #include <Arduino.h> #include <ESP8266WiFi.h> #include <Time.h> void setup() { // Starting serial monitor service // ---------------------------------------------- Serial.begin(9600); // Load time from the NTP server... t...
69,994,082
69,994,133
Find the product of elements located between the maximum and minimum elements of an array
#include <iostream> using namespace std; int main() { int n, a, b,min,max, Prod = 1, Sum = 0; cout << "Initialize an array n: "; cin >> n; do { cout << "Input the start value: "; cin >> a; cout << "Input the end value: "; cin >> b; if (!(a < b)) { ...
Your issue is that you're confusing array indexes with array values. Here you're assigning max (and same with min) to an array value. max = lpi_arr[i]; Here you're treating max (and same with min) as an array index. for (int i = max + 1; i < min; i++) Prod *= lpi_arr[i];
69,994,299
69,994,338
terminate called after throwing an instance of 'std::out_of_range' (never seen this error)
I am kinda new to programming and have never seen this kind of error, so if someone can help me it would be appreciated. I tried to use string for numbers to compare digits to one another, but got this error and I guess it doesn't work :D #include <iostream> #include <fstream> #include <string> using namespace std; i...
Let's assume you have a length of 10. That means your loop will loop until j = 9 for (int j=0; j<length; j++) At that point, what happens with the following? char ch = numeriai.at(j); char chh = numeriai.at(j+1); ch gets the value of the last character in the string (at index 9), but chh tries to read one past the la...
69,994,602
69,995,270
ESP32 not updating the variable when multiple cores are used
My plan is to collect data from ESP32's CORE-1 and use ESP32's CORE-0 for all other tasks. However, I see that the variables are not updated properly when multiple cores are used. Here in this example, I see that the value of getAllData is updated only once. const TickType_t xDelay = 1000 / portTICK_PERIOD_MS; TaskHa...
I found the answer. The problem is not with the variable itself, it is with the Arduino's Serial.flush(). From the version 1.0, arduino is using Serial.flush() to clear the outgoing serial data not the incoming serial data. So, I replaced the Serial.flush() with the following code. while(Serial.available()) { Serial...
69,995,190
69,995,448
How to Embed DirectShow Video Player to SDL Window
I'm trying to play a Video File using DirectShow library in a SDL Window, I use the library provided from Microsoft Docs and works fine when I try build it separately, but the code from main.cpp needs create a apart window in HWND to work and I want to use it in a existent SDL_Window. Code from main.cpp HWND hwnd = Cre...
DirectShow video renderers have support for so called "windowless mode" which you can utilize: Using Windowless Mode Windowless mode avoids these problems by having the VMR draw directly on the application window's client area, using DirectDraw to clip the video rectangle. Old Windows SDK offers related samlpes (e.g....
69,996,050
70,013,300
Why does the "use of local variable with automatic storage from containing function" error message exist?
I have a C++ language/compiler design curiosity question. I'm using gcc 11.2.0, -std=gnu++17 on Cygwin. Why is it an error to directly reference local variables in structures? Lambda functions do this all the time, and they are basically no different from structures containing the operator() method. As an example: stat...
All of the cases that work specifically involve you passing an expression to a constructor. Even the lambda version requires you to spell out the variables you intend to capture (or to use a default capture). This effectively counts as a way to specify the lambda's constructor (which is why you can't default construct ...
69,996,512
69,996,647
Error trying to average the elements of a linked list
I want to calculate the average of elements from a linked list: .h class List { public: List() { head = NULL; } void insertNode(int);//inserare nod la sfarsitul unei liste void printList();//afisare lista void deleteNode(int); void medie(float); .cpp void List::medie(float) { int count = 0; ...
The function is declared with the return type void void medie(float); So it means that it returns nothing. However within the function definition there is a return statement with a non-void expression. return media; So the compiler issues an error message. Also the function parameter is not used within the function. ...
69,996,737
69,996,777
C++ string returning as "
I am trying to write a function that reverses a string. I've figured out most of the code, and when I print the string to std::cout, it's showing what I need. But, when I test the code, the result is that I got " from the function. Here's my code: #include <iostream> #include <string> using namespace std; string resul...
In this for loop, in the very first iteration: for(int i = str.length(); i >= -1; i--) { result+= str[i]; } The terminating zero character '\0' is being written in the first position of the object result, because the expression str[i] is equivalent in this case to the expression str[str.length()]. So, the resu...
69,997,027
69,997,155
How to pass a second parameter in overload to std::visit?
I'm trying to pass a std::shared_ptr<std::jthread> as a parameter in this lambda, but getting an error with this std::visit. It works fine if I leave out the second parameter in the overload. The error can be seen here. https://coliru.stacked-crooked.com/a/95b62272fa49335d #include <iostream> #include <memory> #include...
You've passed a callable to std::visit that accepts two arguments. However, the number of arguments of the callable has to match the number of variants provided to std::visit. That is, std::visit(c, v) will only compile if c takes one argument, and std::visit(c, v1, v2) will only compile if c takes two arguments, and s...
69,997,130
69,997,322
C++: is it possible to make thread_local variable global?
For example, I have a thread_local variable in my code, but there are a set of functions, which access and modify it. For modularity, I took out them to a different translation unit (correct me if I'm wrong on terminology), by creating a header with their declarations and source file with their definitions. // fun.h in...
The variable var is already global. "Global" refers to the scope of the variable: it means it is declared in the outermost namespace, so its use is not restricted to a particular block, class, or sub-namespace. So a variable can be both global and thread-local without any contradiction. All you're asking for is how to ...
69,997,248
70,003,838
Initialising a vector with anoter vector, returned from a function
I'm attempting to create a vector called mems which is declared using the returned vector from my myMembers() function. For some reason when I use the line: vector<string> mems = myMembers(); It returns an error: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null ...
I've discovered the issue for the program. The split() function was causing the error, because temp was initialised as string temp = 0; which meant it was trying to initialise a string with an integer value. The correct code for the split() function is as follows: ector<string> split(string myString, char delimiter){ ...
69,997,471
69,997,498
Why is this pointer 8 bytes?
I am learning C++, and read that when an array is passed into a function it decays into a pointer. I wanted to play around with this and wrote the following function: void size_print(int a[]){ cout << sizeof(a)/sizeof(a[0]) << endl; cout << "a ->: " << sizeof(a) << endl; cout << "a[0] ->" << sizeof(a[0]) <<...
Shouldn't they be the same? No. a is (meant to be) an array (but because it's a function argument, has been adjusted to a pointer to the 1st element), and as such, has the size of a pointer. Your machine seems to have 64 bit addresses, and thus, each address (and hence, each pointer) is 64 bits (8 bytes) long. a[0], ...
69,998,343
69,998,365
How to deal when two objects share the same address?
Background: I don't know a lot about memory location neither how zero size objects work, nor how to manipulate them. Since a base class subobject of a standard layout class type with no non-static data member have zero size ( source 1 ), I expect that in the following code struct B has a zero size base-class subobject ...
So the address of the base-class subobject is the addres of an unspecified byte occupied by b, but it only has 1 byte, so b and its base-class subobject share the same address? Yes. If I didn't miss anything and the conclusion is right, how zero size subobjects are handled when "pointered" to? The value of the poin...
69,998,406
69,998,521
How to erase reverse_iterator correctly when erase and push_back happens?
I have a list container, which looks like: std::list<int> l = {1,2,3,4,5,6,7,8}; i often erase elements, so i choose std::list. but, i also want to find the elemnt in O(1), so i record the reverse_iterator. For Example: l.push_back(9); auto s = l.rbegin(); // record the iterator of 9, in order to erase it in the ...
l.rbegin().base() == l.end(), which is not the position of the last element, but the end of the list. and push_back again won't affect this existing iterator, it is still pointing to the end of the list. Then std::next(l.rbegin()).base() == l.end() - 1, which now is pointing to the last element 10. So if you want to re...
69,998,774
69,998,934
How to check if a variable can be written into a stream
I'm developing a tool class with C++14, which allows developers to print all kinds of objects easily. For the std::map object, I try to develop such a function: template<typename M, typename = std::enable_if_t< std::is_same<M, std::map<typename M::key_type, typename M::mapped_type>>::val...
Here's a simple way to make your own type trait in C++14: #include <type_traits> #include <utility> namespace is_streamable_impl { template <typename T, typename Enable = void> struct check : public std::false_type {}; template <typename T> struct check<T, std::enable_if_t<std::is_same< ...
69,999,004
69,999,052
C++ Simple Menu Program; difficulty finding middle character of user input
this is only my second time posting here so I hope I am doing this correctly. I need to have the user input a string (usrinput) of any length and make a selection 1 - 4. I have completed 2, 3, and 4, but I cannot figure out how to do selection 1. if the user enters a string "This is a Test" and selects option 1, if odd...
For your selection 1 if statement, all you need to do is check if the string evenly divides by 2 to determine if it is even or odd, no need to divide by 2. You also can just have an else statement right after the if which accounts for even numbers. if (((i = usrinput.length() % 2) == 1)) { i = usrinput.length()...
69,999,379
69,999,721
What does std::atomic::is_always_lock_free = true really mean?
I have the following code: #include <atomic> int main () { std::atomic<uint32_t> value(0); value.fetch_add(1, std::memory_order::relaxed); static_assert(std::atomic<uint32_t>::is_always_lock_free); return 0; } It compiles and so it means std::atomic<uint32_t>::is_always_lock_free is true. Then, the as...
"Lock" here is in the sense of "mutex", not specifically in reference to the x86 instruction prefix named lock. A trivial and generic way to implement std::atomic<T> for arbitrary types T would be as a class containing a T member together with a std::mutex, which is locked and unlocked around every operation on the obj...
69,999,608
69,999,811
Multiple undefined reference errors in hpp file
I am getting multiple undefined reference errors from zmq.hpp such as: `build-client-Desktop_Qt_5_15_2_GCC_64bit-Debug/../client/Headers/zmq.hpp:113: undefined reference to zmq_errno' and the others are zmq_strerror, zmq_msg_init etc. there are like 20 of them. I guess the hpp file can not find the zmq.h ? I added th...
This is a linker error, you forgot to add library to your .pro file. The line looks like this LIBS +=lib_path/lib_name
70,000,253
70,000,413
Vector Resizing in C++ works only when adding cout statement?
vector<string> solution(vector<string> inputArray) { int n = inputArray.size(); vector<string> outputString(n); int maxSize, curPos = 0; for(auto &i: inputArray) { int currentSize = i.size(); if(currentSize > maxSize) { maxSize = currentSize; curPos = ...
maxSize is uninitialised so your code has undefined behaviour. UB produces surprising results like printing something changes the behaviour of the program. By using reserve and then adding strings to the vector your code can be a lot simpler: vector<string> solution(const vector<string>& inputArray) { size_t n = in...
70,000,596
70,000,667
Why are there key_type and value_type in std::set
After reading this link: https://en.cppreference.com/w/cpp/container/set, I just found that there were two defined types: key_type and value_type in the class std::set. It seems that they are exactly the same thing. Well, this may be a stupid question but I still want to ask why. Isn't one enough? Why are there two typ...
All the stl containers have value_type, and all the associative containers (including std::set, std::map, std::multiset, std::multimap) and unordered associative containers (including std::unordered_set, std::unordered_map, std::unordered_multiset, std::unordered_multimap) have key_type, that means you can perform some...
70,000,687
70,001,246
custom qHash method is not being called
I'm using QPoint as a key in a QHash, and following the documentation, I implemented a global qHash method for QPoint like so: inline uint qHash(QPoint const &key, uint seed) { size_t hash = qHash(QPair<int, int>(key.x(), key.y()), seed); qDebug() << hash; return hash; } I'm using it like this class HashTest { ...
qHash for QPoint might not be documented but sure is defined: Q_CORE_EXPORT size_t qHash(QPoint key, size_t seed = 0) noexcept;
70,000,828
70,000,962
Cannot call non-static function on a class object in a vector
I'm bulding my own Neural Network with my own Matrix class. I'm trying to use the swishMatrix() function on a Matrix2D class object, before adding it to a vector<Matrix2D> variable. But I get this error and I have no idea why. -> no matching function for call to 'std::vector<Matrix2D>::push_back(int)'| When I use the s...
The trivial fix is to make swishMatrix return the matrix object again: Matrix2D& swishMatrix(){ for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { matrix[i][j] = matrix[i][j] * sigmoid(matrix[i][j]); } } return *this; } Never ever ...
70,001,001
70,001,408
constexpr array vs deque, memory utilization
I need to store a pre-known size of about 30 integers in my code, I have gone for constexpr std::array<size_t, 30> MAPPING{1, 2, 3, ...}; If i am not wrong, the above will be evaluated at compile time, but it would also take up a single sequential block of memory of a size of 30 integers? If it does, is it worth using...
It's not worth using std::deque here. It would also take up a single sequential block of memory of a size of 30 integers? Yes, it would take up a single sequential block of memory of a size of 30 integers in the stack This way, with a deque, we would not be using a single large sequential memory block and it might use...
70,001,881
70,001,997
How we have a return value of pop() function in JavaScript?
While I was recently studying JS coming from a C++ background, I found out that the pop() function of arrays has a return value in JS. Now, in C++ we don't have a return value for pop_back() method because according to a paper by Cargill, it is impossible to design an exception-safe stack pop function as answered here ...
None of the "Exceptions Thrown by T" cases pop up in JavaScript, because there simply is no assignment or construction operator invoked. JavaScript is a garbage-collected language, so everything is a handle to the actual object. Calling pop just shrinks the array by one and returns the handle that was there without doi...
70,002,099
70,002,143
non type template parameter pack expansion
I simply would print out a non type template parameter pack. But I can't find a valid expansion if I want to have spaces in between the elements. Example: template < int ... N > struct X { static void Check() { // this will become std::cout << ( 1 << 2 ) << std::endl; -> prints "4" std::cout << "...
With the use of a helper variable. std::size_t count{}; ((std::cout << (count++? " " : "") << N), ...);
70,002,208
70,002,670
is there any way to wakeup multiple threads at the same time in c/c++
well, actually, I'm not asking the threads must "line up" to work, but I just want to notify multiple threads. so I'm not looking for barrier. it's kind of like the condition_variable::notify_all(), but I don't want the threads wakeup one-by-one, which may cause starvation(also the potential problem in multiple semapho...
it's kind of like the condition_variable::notify_all(), but I don't want the threads wakeup one-by-one, which may cause starvation In principle it's not waking up that is serialized, but re-acquiring the lock. You can avoid that by using std::condition_variable_any with a std::shared_lock - so long as nobody ever get...
70,003,240
70,003,390
Sorting numbers of an array in descending order
I have an array of 16 numbers that i need to sort in descending order, I tried sorting them this way but can't seem to make it work. Note : I have to program an algorithm so i can't use any special functions :( #include <stdio.h> #include <stdlib.h> int main() { int i, temp1, temp2; int string2[16] = { 0, 4, 2...
There're a few problems: _Bool is a strange thing to use in C++ (maybe this question intended for C?) You didn't initialize i. This is called an undefined behavior. This may or may not work, depends on the computer, but it's never good to have something like that in your program. (i=15) is an assignment. Use i==15 for...
70,003,416
70,003,561
How to pass a std::array to a function template which can accept std::vector
I'm trying to write a template, which can accept some sequence containers: template <typename S, typename = std::enable_if_t< std::is_same<S, std::array<typename S::value_type>, S::size()>::value || std::is_same<S, std::vector<typename S::value_type>>::value>> std::string arr2Strin...
If you want to restrict your template to work for only std::array or std::vector, you can write some helper traits template <typename> struct is_array : std::false_type {} template <typename T, std::size_t N> struct is_array<std::array<T, N>> : std::true_type {} template <typename> struct is_vector : std::false_type ...
70,003,489
70,005,435
How to split set of vertices with Boost Graph?
I'm writing some algorithm in C++ for parallel graph coloring using Boost Graph and adjacency_list. I'm working with very big graph (the smallest has 32K vertices). What I'm trying to do is to take the whole set of vertices, split them in parts and assign each part to a different thread and work in parallel, but I'm st...
g.m_vertices.size()/4; is the right solutions? That depends ONLY on your requirements. If initially I have 10 vertices, then I remove some vertex in the middle (e.g. 4), only 6 vertices left (so this is the new size) but the index of the vertices go from 0 to 5 or from 0 to 9? That depends on your graph model. You ...
70,003,507
70,007,119
Mac Link .h file to .cpp files
I'm a student and have just been introduced to modularity in cpp. I don't understand my mistake though. I have 3 files. One test.cpp /**\ * @file testFile.cpp * @author TomPlanche * @brief test file links \**/ // . Importation Des Bibliothèques Nécessaires. #include <iostream> #include "fraction.h" int main...
You build your executable with: g++ testFile.cpp -o testFile but you're forgetting the second source file. You can either do everything in one line: g++ testFile.cpp fraction.cpp -o testFile but with an eye on the future, when your program may become much larger, it's a better idea to use separate compilation: g++ -c...
70,003,533
70,018,151
Multiple definition of variable First defined here error
I have this c++ project with classes' definitions inside .hpp files and methods' declarations inside .cpp files. The project uses a makefile to build and run. The program ran without errors before but LinkedList didn't work as I wanted so I re-wrote it entirely. Now LinkedList.hpp includes both the class definition and...
TileTypeStr[] was misplaced after all, moved it inside the toString() method I needed it for, then ran make clean to recompile all of the source files and make to build main.cpp. By running make and not recompiling the source files I was stuck running the bugged version of the program.
70,003,639
70,004,411
Using Address Sanitizer or other Undefined Behavior Sanitizers in Production?
In the past there have been concerns about using ASAN in production in certain environments: https://seclists.org/oss-sec/2016/q1/363 . The comment is from 2016 - what is the landscape like today? Is it recommendable to use the sanitizers here in a production system running on a user's device? The application receives ...
Sanitizers are primarily meant to be used as debug, not hardening tools i.e. for error detection at verification stage but not error prevention in production. Otherwise they may leak sensitive info to the attacker (by printing details about address space and library version to stderr on error) or obtain local root priv...
70,003,749
70,004,083
Inheritance for class with the same name but different namespace c++
Is it possible to inherit from the class with the same name, but in different namespace and how to achieve it? For example I have the following structure: namespace general { namespace gui { struct GUI { }; }} can I do: namespace proxy { namespace gui { str...
Yes, this is possible. If you are getting an error, there is something in your code you have not posted here, such as a using namespace statement. proxy::gui::GUI and general::gui::GUI are two entirely different classes. The fact that both end with GUI says nothing at all. The full/complete name of the class is always ...
70,003,917
70,008,097
How to detect a connection failure in Indy TCP Client
I have made a client and a server using Indy TIdTCPClient and TIdTCPServer in C++Builder 11 Alexandria. I can start the server and connect the client to it correctly, but if I set the server MaxConnections to a value N and I try to connect to it with the N+1 client, the connection does not fail, apparently. For example...
You are not doing anything wrong. This is normal behavior for TIdTCPServer. There is no cross-platform socket API at the OS level 1 to limit the number of active/accepted connections on a TCP server socket, only to limit the number of pending connections in the server's backlog. That limit is handled by the TIdTCPServe...
70,004,520
70,004,942
Why is this not working? (Trying to convert a text file into a binary file)
#include<iostream> #include<fstream> #include<vector> #include<string> #include<algorithm> #include <sstream> #include<iomanip> using namespace std; const string binaryfile = ".../binaryfile.dat"; void to_binary(const string& filename) { ifstream ist(filename); ofstream ost(binaryfile, ios::binary); char...
What exactly were you expecting to happen? There is no such thing as a binary file. It's just a file. A file is a series of bytes. Nothing more, nothing less. A text file is a file where each byte "means" a character. For example, the byte value 01000001 means the capital letter A. When you open a file in Notepad, Note...
70,004,605
70,004,722
the output array shows only the last element instead of inserting data at specified location in the array
#include <iostream> using namespace std; #define max 10 int main() { int items[max]; int i,n,ub,location,data; cout<<"Enter the number of items you want to enter: "<<endl; cin>>n; ub=n-1; if(ub>=max-1){ cout<<"Array is full!"<<endl; } else{ cout<<"Enter "<<n<<" elem...
You have two issues: cin>>items[n]; must be cin>>items[i]; cout<<items[n]<<endl; must be cout<<items[i]<<endl;
70,005,258
70,026,630
Why does the function ID3D11DeviceContext::Map sometimes produce a mapped subresource with a different resolution to my texture?
When using the Map function on an existing render texture, in certain situations, the output RowPitch and DepthPitch are altered, producing a subtly different resolutions. For example, if the source texture (BGRA 8bit) has the resolution 1559x1080 with a bit depth of 4, the resulting D3D11_MAPPED_SUBRESOURCE has the re...
Based on your answer, I'm guessing you're running this on a somewhat modern x86-64 CPU. From some basic math on the values you gave, the algorithm appears to be the following for your PC: RowPitch = AlignUp((BytesPerTexel * TextureWidth), 64); Here, AlignUp rounds the first argument to the smallest value larger than o...
70,005,578
70,005,868
Difference between std::string and const char*?
What's the difference between std::string and const char*? consider following example #include <iostream> #include <string> int main() { const char* myName1{ "Alex" }; std::cout << myName1 << '\n'; std::string myName2{ "Alex" }; std::cout << myName2 << '\n'; return 0; } are they the same?
std::string will give you the ability to use its member functions and most importantly to modify its contents. The initial data will likely1 be copied to a dynamically allocated memory location when the program reaches its constructor. It will also store its size. const char* is only a pointer value that points to a co...
70,005,580
70,005,726
How to iterate over the size of a parameter pack with a compile-time index parameter
I'm trying to write a variadic template function that includes a loop that iterates over each type in the parameter pack. I'm using this to build up a tuple which I then apply on the callback function which determined the template types. I thought I could do this using sizeof...(Args) as follows: template <typename ......
You can define a helper function to use index_sequence to expand the elements of Tuple and assign values through fold expression. template<class Tuple, class Message, std::size_t... Is> void assign_tuple(Tuple& tuple, const Message& message, std::index_sequence<Is...>) { ((std::get<Is>(tuple) = message.getArg<std::tu...
70,006,056
70,006,249
Pass a container type as the typename of a template in c++
I'm a beginner at templates in C++ and I would like to know if it's possible to pass a container to the typename of a template function, here is what I'm trying to do: template <typename T> int find_size(const T<int> t) { return (t.size()); } int main(void) { std::array<int, 10> test; for (int i = 0; i < 1...
With minimum changes to make it work, your code could be this: #include <array> template <typename T> int find_size(const T& t) { return (t.size()); } int main(void) { std::array<int, 10> test; for (int i = 0; i < 10; i++) { test[i] = i; } find_size(test); } basically I want my funct...
70,006,292
70,006,672
Put sin on segment in 3d
i need to put a sin function, or any other function on start of segment in 3d space. Something like that: Example But in 3d space, help me pls, i spent about 4 days for solving it, but did not get result There are 2 points in space at arbitrary positions. I need a sinusoid between these two arbitrary points. 3d segmen...
Generate point set in OXY plane and apply affine transformation to make OX axis coincide with desired vector, also you need to define one normal vector to get sin plane unambiguously. Math for affine matrix calculation (here simpler because we can choose unit-length vectors)
70,006,664
70,006,785
C++ thread pool using boost::asio::thread_pool, why can't I reuse my threads?
I am experimenting with boost::asio::thread_pool to create a thread pool in my application. I created the following toy example to see if I understand how it works but clearly not :) #include <boost/asio/post.hpp> #include <boost/asio/thread_pool.hpp> #include <boost/bind.hpp> #include <iostream> boost::asio::thread_p...
You join the pool after posting the first task. So, the pool stops before you even accept a second task. That explains why you're not seeing more. This fixes that: for (size_t i = 0; i != 50; ++i) { post(g_pool, boost::bind(f, 10 * i)); } g_pool.join(); Addendum #1 In response to the comments. In case you want to ...
70,006,764
70,006,824
Why do I get "0xC0000005: Access violation reading location 0x0000000000000000"
So in one getter method I'm simply trying to get the length of a c-style string (c-style strings give me headaches) and it works everywhere else in the code except on 1 line stated below the code #include <iostream> #include <cstring> #pragma warning(disable : 4996) using namespace std; class MyString { private: ...
MyString() :str{nullptr} { str = new char[1]; //str = '\0'; // <-- here is your mistake str[0] = '\0'; // do this instead }
70,006,919
70,007,171
Correct way to call user defined conversion operator in templated function with MSVC
I need to call a templated conversion operator inside a class like this : struct S { template<typename T> operator T() const { return T{}; } template<typename T> T test() { return operator T(); } }; int main(){ S s; s.test<int>(); return 0; } This code compil...
Syntax is correct, as work around you might be explicit with this->operator T(): template<typename T> T test() { return this->operator T(); } Demo
70,007,229
70,007,437
Why my empty string assignment doesn't clear my string
I have an exercise which looks like that: Problem statement is simple and straight forward . You will be given a non-negative integer P of length N and you need to check whether it's divisible by Q ? Integer P will be given in its decimal representation with P0 as leftmost digit and P1 as second digit from left ! Rest...
Your problem is with the digits vector. Each loop the number string just gets repopulated with the digits vector which is never cleared. Use digits.clear() to empty the vector like so: #include <iostream> #include <vector> #include <string> using namespace std; int main() { int t, q, n, p_0, p_1, p_temp, p; ...
70,007,265
70,012,050
Update index variables in threads
I have objects like balls. These objects are dynamically created and stacked into a vector. For each of these balls, a separate stream is created that updates its coordinates. Each of these streams has a reference to a vector with balls and knows the sequence number of its ball. Then, let's say I need to delete several...
Rather than each thread having an index into the vector, why not pass a reference to the object being worked on? Note that this may still be problematic if your vector is vector<Ball>, as I'm not sure what happens to references to objects that are moved. That sounds like a problem. But you could store vector<std::share...
70,007,518
70,007,936
Trying to understand initialization of array C++
I am working with C++ to construct an array, which is then passed into Python (similar to: Embed python / numpy in C++). I am new to C++ and I am confused with some of the details of the code. I'm hoping I can get an understanding of how this code works, because I need to change it. So my question is: what is this meth...
double(*c_arr)[SIZE]{ new double[SIZE][SIZE] }; The above is/can be read as: c_arr is a pointer to an array of size SIZE. Next, new double[SIZE][SIZE] creates a 2D array and also returns a pointer to its first element(which is also an array of double). Next, the pointer c_arr is initialized with the pointer returned ...
70,008,513
70,012,180
Why would the MPI_Status of a successful communication would report "-1" as source
Please look at the following MWE, which shows how what appears to me as a successful communication done using MPI_Irecv and MPI_ANY_SOURCE reports as its source the integer value "-1". The example includes command-line output, which is as follows. Affter this lines, it SigFaults as the "-1" index is later on used as th...
Your problem is that you use MPI_Request_get_status: MPI_Wait(&R2[i], &status); MPI_Request_get_status(R2[i], &flag, &status); Do you see that you have two calls that both have the status as output? That's suspicious. Your MPI_Wait already clears the request object (that's why it's passed by reference), so MPI_Request...
70,008,747
70,009,011
How to define a private member function only in cpp
So consider I have a class with a private member variable and a private function which I do not want to define in the header file, because I want to "hide" it from the user. How can I make this? I can not access the private variable without the declaration of the function in the header. So what works is something like...
Normally one achieves this through the PIMPL (Pointer to IMPLementation) idiom. In your header file you have: class MainClass { public: void public_function(); private: class Impl; Impl* impl; }; Note that the header file does not contain the definition of the Impl class, only its declaration. You then def...
70,009,341
70,009,404
Why do I get an Undefined reference error when trying to compile?
Just had a little problem that I haven't been able to figure out yet. I was using a similar program structure for a different project, but the problem boils down to this. I have two cpp files, which are: Trading_dte.cpp : #include <iostream> using namespace std; class Dte { public: int addition(int a, int b) ...
your cpp file need to be written differently #include "Trading_dte.hpp" #include <iostream> int Dte::addition(int a, int b) { return a + b; }
70,009,655
70,010,601
CLion does not see wxwidgets partially but compiles project
I use Artix linux on OpenRC, I have installed wxwidgets with wxgtk3-dev package (version 3.1.5) from AUR and I wanted to work with that library in CLion. CLion sees it and I'm able to include anything from wx/ dir. I have copied a hello world example from wxwidgets website and pasted it into my cpp source file and then...
OK I solved my problem. As you can see in my CMakeLists.txt it uses C++14. It seems that CLion can not properly handle some code from example with C++14 although it's not a problem for cmake and make to build it. I just switched to C++11: set(CMAKE_CXX_STANDARD 11) and now everything works!
70,010,434
70,010,537
Expression evaluation from infix to postfix
#include <iostream> #include <string> #include <stack> using namespace std; float postix_evalute(string expr) { stack<float> stk; float val; for (int x = 0; x < expr.length(); x++) { if (isdigit(expr[x])) { stk.push((expr[x] - '0')); } else { ...
if (isdigit(expr[x])) { stk.push((expr[x] - '0')); } You're pushing individual digits one at a time. If you run postfix_evaluate("32"), this loop will push 3 onto the stack first, and then 2. Are you sure you don't want the single value 32 on the stack instead? You can, and should, ...
70,010,938
70,011,943
Should I ever store the result of set/map find() as reference?
Please consider the following example: #include <set> int main () { std::set<int> s; const auto it = s.find(1); const auto& it2 = s.find(1); return 0; } One could assume that it2 would be cheaper, but if I understand the generated assembly code correctly, it actually uses two more instructions: //co...
Set::find() doesn't return a reference: const_iterator find (const value_type& val) const; iterator find (const value_type& val); I'm surprised the compiler let you assign the value to a reference. As some of the commenters have suggested, it creates a temporary for your reference to point to. C++ is really quit...
70,011,468
70,807,481
GEOS (​JTS Topology Suite) BufferOp / Offset Curve producing additional points
I am using GEOS (the C port of the JTS Topology suite) to produce an offset curve of a linestring. I have successfully produced the offset curve however for some cases (namely where the start and end lines are both horizontal and end at the same x position / or vertical and end at the same y position), an additional po...
Latest release of Geos resolves this now. See here: Issue
70,011,477
70,011,747
C++ compiler error: use of deleted function std::variant()
I am continually getting the following error message telling me that I am using a deleted function, which I think is the std::variant default constructor. In file included from main.cpp:2: Document.hpp: In instantiation of ‘Document<StateVariant, EventVariant, Transitions>::Document(StateVariant&&) [with StateVariant =...
While you do need to work on a minimal example, the core problem is your DraftState default constructor is ambiguous with your string constructor with a default argument. See https://godbolt.org/z/hTnsjoWaW To be default constructible, std::variant requires the first type argument to be default constructible. The amb...
70,011,500
70,011,627
How to replace quotation marks with angle brackets between two patterns recursively for all file in a directory with sed?
The repository I am working on has multiple source files in a non-flat directory structure, e.g. project │ main.cpp │ └───moduleA │ A.cpp All these source files have code something like #include "A.h" WINDOWS_DISABLE_WARNING #include "externalA.h" #include "externalB.h" WINDOWS_ENABLE_WARNING // more code H...
Read about addressing lines in sed find ... -exec sed -i '/WINDOWS_DISABLE_WARNING/,/WINDOWS_ENABLE_WARNING/ { s/"/</; s/"/>/ }' '{}' + Make sure to back your files up (sed -i.bak) (or omit the -i option) before experimenting with -i