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
63,987,208
63,987,752
Move insertion with unordered_map having multiple values
I tried the below code for move and initializer list insertions. The later works but not the move insertion. Can someone help me with the right solution here ? #include <iostream> #include <iostream> #include <string> #include <unordered_map> using namespace std; int main () { std::unordered_map<std::string,std::pa...
This line has a few problems: myrecipe.insert (std::make_pair<std::string,std::make_pair<double,double>>("eggs",(1.0,6.0))); The type you want to insert is a std::pair<std::string, std::pair<double, double>>, but that is not what you are making here. This is how to make it work with make_pair: myrecipe.insert(std::make...
63,987,539
63,988,519
String permutation recursion issue
(--This question was answered down below--) Hey guys so I know this question has been answered in various ways so far on this site but I wanted to see if I could get a hint to my question without getting the blunt answer... sorry if this is redundant! so... so far my code is this (as the function says, this is supposed...
The problem is that you're modifying both strings in the loop, so prefix grows and remainder shrinks. That is, you want the "top-level" call to iterate through A/BCD, B/ACD, C/ABD, and D/ABC, but you're iterating through A/BCD, AB/CD, ABC/D, and ABCD/empty. Don't modify the strings, just pass the values you want to the...
63,988,161
63,988,190
Erase-Insert Idiom in C++?
The following code works perfectly fine: auto it = vec.insert(vec.begin(), vec.begin(), vec.begin()+i); vec.erase(it+i, vec.end()); But this gives a malloc: corrupted top size error: vec.erase(vec.insert(vec.begin(), vec.begin(), vec.begin()+i)+i, vec.end()); Why is this happening and is there any way to fix this err...
vec.end can change due to the insert, after it's been evaluated as argument to erase. C++ does not guarantee that arguments are evaluated left-to-right. There's no simple fix here. You need an iterator range for erase, but the insert changes the iterators of vector.
63,988,501
63,988,629
Problem with order of evaluation in parameter pack expansion
I wrote a template that takes an istream& and a function and is supposed to extract all parameters for this function from the istream, call the function with these parameters and return the result. It all works fine, except for the order of evaluation of function parameters. See code, further details and final question...
For example, we can use an intermediate std::tuple to force the order of evaluation: template<typename TR, typename ... TArgs> TR Bar(std::istream &s, TR f(TArgs...) ) { std::tuple<TArgs...> args{Parse<TArgs>(s)...}; return std::apply(f, std::move(args)); } In contrast to function arguments, the order of evalu...
63,988,620
63,989,318
Deadlock in WPF: How to not block the GUI thread in HwndHost.BuildWindowCore?
We have a large code base for processing and visualizing images in C++ with Qt. Now a user wants to build on that, but their code base is .NET Core 3.1 with WPF. We use PInvoke to interface the native code, and can very successfully join the projects. The few native widgets are embedded with Win32-in-WPF-HwndHost wrapp...
Your WPF pump (Dispatcher) is blocked. Async / await / Yield will not help you since you are not in an async function. You need WPF to keep pumping while it is sat inside BuildWindowCore(). You can do this by calling your native code on a different thread, then have your WPF thread sit and pump messages until the worke...
63,988,862
63,989,101
listen returns without waiting for a connection
When I run my program I get output Listening on port 65004 listen -> 0 Why does listen returns without waiting for a connection? #define PORT 65004 bool listen_on_port(int port) { WSADATA wsadata; int error = WSAStartup(0x0202, &wsadata); if (error) { return false; } if (wsadata.wVersi...
Zero means that the call succeeded. However, I believe that the problem is a misunderstanding in what listen does. The Linux man page has a good explanation, but it works the same way with winsock: listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept inc...
63,988,906
63,989,253
CMake Error: mismatch for the compiler version between your conan profile
I'm on MacOS. This is my error : CMake Error at build/conanbuildinfo.cmake:625 (message): Detected a mismatch for the compiler version between your conan profile settings and CMake: Compiler version specified in your conan profile: 11.0 Compiler version detected in CMake: 12.0 Please check your conan profile settings ...
Apple-clang recently updated to version 12.0, but your default profile, created before, still contains version 11.0. This error is good, it is protecting you from changing compiler version and not realizing binaries will be different. You can update your default profile, go to your userhome ~/.conan/profiles/default an...
63,989,671
63,995,678
Casacore linking error in C++ on Ubuntu 18.04
I installed casacore from source using the GitHub repository on my Ubuntu 18.04. The installation completes without any errors and the respective files are written to the expected directories (the .h files to /usr/local/include & libraries to /usr/local/lib). On trying to compile a basic C++ file using these I'm given ...
When compiling manually with g++ you need to first specify your sources, and then the dependencies (libraries): g++ -o ms ms.cpp -I/usr/local/include -L/usr/local/lib -lcasa_casa -lcasa_tables -lcasa_ms -g -Wall Better just use CMake if you plan to have something more that just one cpp. Related topics: linking files ...
63,989,941
66,407,447
How to visualise ndarray Rust in VSCode?
I am using VSCode to develop my rust application which contains lots of NDArray. When I set breakpoint and watch the NDArray variable, it is only showing pointers. I don't know how to view the content. I tried both cppvsdbg & lldb (vscode-codelldb) and both has same issue? Is there any command I can type in debug conso...
I am now able to visualise it using below natvis, <?xml version="1.0" encoding="utf-8"?> <AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> <Type Name="ndarray::ArrayBase&lt;*,*&gt;"> <DisplayString>{{Modified by Selva}}</DisplayString> <Expand HideRawView="false"> ...
63,990,042
63,990,244
Are "1" and '1' different in Cpp ? if yes then how?
When element of character array is compared to "1" instead of '1' it shows an error #include <bits/stdc++.h> using namespace std; bool sortbysec(const pair<int,int> &a, const pair<int,int> &b) { return (a.second > b.second); } int main() { int t; cin>>t; while(t--) { int N...
Are "1" and '1' different in Cpp ? Yes. if yes then how? First is a null terminated array of chars and the latter is a char. According to error one of them is pointer and other is integer if so then which of them is what and how? Technically, one of the operands is an array as I mentioned. But when an array is us...
63,990,676
63,990,788
Assign object of a different child class to the pointed address [C++]
Im working on a project where I have a few child classes (Profile1, Profile2, Profile3). One of the functions is to edit the Profile which includes changing type from Profile1 to Profile2. My first idea was to simply delete former object and create new one, however this would require some additional changes in the code...
As I said in comments, you cannot change the object type but keep the same address. Different object types require different amounts of memory if Child1 and Child2 derive from the same parent, then you could keep the same pointer, but it will hold a different address. Parent * currentProfile= new Child1(); Child2* newP...
63,990,814
63,991,336
Why is this solution giving TLE on the given test case?
Question link : https://leetcode.com/problems/word-search/ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighbouring. The same letter cell may not be used more than on...
Recursive function dfs receives board by value, i.e. it cannot change it while it apparently tries. Timeout due to huge amount of copies and infinite recursion. Looks like bug.
63,990,937
63,990,963
Is there a std::less/std::greater for the spaceship operator?
All the basic comparisons (<, <=, ==, !=, >=, >) have an associated function object (std::less, std::less_equal, std::equal_to, std::not_equal_to, std::greater_equal, std::greater). Does the spaceship operator <=> have a similar function object? If not, why was it not added to the standard library?
std::compare_three_way is the function object for three-way comparison (aka. spaceship operator).
63,990,994
63,992,007
How to compose generators with STL algorithms
I have an algorithm which generates combinations from entries of a container and I want to find the combination which minimizes a cost function: struct Vec { double x; double y; }; double cost( Vec a, Vec b ) { double dx = a.x - b.x; double dy = a.y - b.y; return dx*dx + dy*dy; } pair<Vec,Vec> get_pair...
There is http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2168r0.pdf who's development I would follow If you are using MSVC, and can use their experimental/generator (not sure if others support it yet), you can use std::experimental::generator<std::size_t> Generate(std::size_t const end){ for(std::size_t i =...
63,991,176
63,991,292
Assign a small number to unsigned long long data-type without casting
I became a little bit confuse about assigning a small number to a big data-type variable, for example in my code (checkout online) : #include <iostream> int main() { unsigned long long num = 5000000000; unsigned long long num2 = static_cast<unsigned long long>(5000000) * static_cast<unsigned long long>(1000); un...
Your line unsigned long long num4 = 5000000 * 1000; consists of three independent parts which are evaluated separately. The right-hand-side is evaluated as int because all the operands are int. The result is not what you expect because of an integer overflow. The left-hand-side makes space for an unsigned long long. ...
63,991,316
63,991,561
C++ finding class in vector using std::find raises errors
I'm trying to find a SnekNode object in an std::vector using auto it = std::find(snek_node_container.begin(), snek_node_container.end(), snek_node); but it raises a compiler error: Error C2676 binary '==': 'SnekNode' does not define this operator or a conversion to a type acceptable to the predefined operator ...
operator== should return bool. Also, you need to compare the members individually. In your code you just call operator== again, causing infinite recursion. What you can do is use the operator== in operator!= to save typing, e.g.: struct SnekNode { bool operator== (const SnekNode& rhs) const { return a == rh...
63,991,414
63,991,524
How to work with Arrays inside of classes c++
I just started to learn C++. Maybe the Question is stupid, but please be nice. I want to write a Class for a linear Congruence Generator. In this Class I wanna write the calculated Values into an Array, but it dosen't work. I would be very thankful, if you can tell me what I'm doing wrong! Here's my program: #include <...
In fact your Array works correctly. However, just think about the content of your Array: Array[0] = x0 = 4 Array[1] = (60 * Array[0] + 0) % 200 = 240 % 200 = 40 Array[2] = (40 * Array[1] + 0) % 200 = 1600 % 200 = 0 Array[3] = (0 + 0) % 200 = 0 ...
63,991,707
63,991,910
Valid way to check that a double has been assigned a value of 0.0
I know there are plenty of pitfalls with using the equal comparator with double's so I'm cautious on how to implement a check for a value equal to exactly 0.0. Basically, I want to know if a value was never assigned or if it was intentionally assigned the value 0.0 with a literal. I do not want to know if it is nearl...
If you need to know if a floating point variable is exactly 0.0 or -0.0 then there is nothing wrong with using val == 0.0. If you need to know if it is exactly 0.0 and not -0.0 then you must verify that you are using ieee-754 floating points and check whether the bit representation is all zero.
63,991,941
63,992,069
Including two headers which are not available at the same time
There is a code repository including these two headers from Boost library at the same time: #include <boost/nowide/cstdio.hpp> // => Not found with Boost 1_72_0 #include <boost/detail/endian.hpp> // => Not found with Boost 1_74_0 or 1_73_0 First I installed Boost 1_74_0 or 1_73_0 and the <boost/detail/endian.hpp> was ...
If you read the <boost/detail/endian.hpp> header file it has a comment: // Use the Predef library for the detection of endianess. Followed by #include <boost/predef/detail/endian_compat.h> It simply seems that the header you used have been obsolete or deprecated for a while, and finally removed. So the solution is t...
63,992,429
63,992,618
CMakeLists include Header File from subdirectories
I am trying to work with CMake for the first time and am struggling to link header files into my main. My cmake directory looks like this: Project | CmakeLists.txt | src || CMakeLists.txt || Main.cpp | Libs || CMakeLists.txt || headers |||obstacle_detection.hpp ||source |||obstacle_detection.cpp |build ||"build files"...
You haven't added any include directories to the obstacle_detection library. By listing the header file in the add_library call, this may allow the header to be displayed in an IDE, but it doesn't do anything for compilation. You should use target_include_directories to add the headers directory as an include directory...
63,993,779
63,999,019
A neat way to release C++ project executable
I am writing a simple program with C++ using CLion, cmake in Ubuntu. The program uses CURL, Qt and OpenCV library, so I installed prebuilt packages using apt. I finished writing my code, uploaded to github, and now I want to define current code as version 1 and make an release. My initial thought was: build the program...
If you want to release executables for Linux, you're potentially taking on a pile of work. Not only do different Linux distributions handle packaging and dependency management differently, there can be inconsistencies even in different releases of the same distribution. It's extremely difficult to support even one dist...
63,994,370
63,994,458
Segmentation fault (core dumped) unable to find the bug
#include<iostream> using namespace std; class Node{ public: int data; Node* next; }; class LinkedLIst{ private: Node* head; public: LinkedLIst(){ head=NULL; } void addNode(int data){ Node* newNode = new Node(); newNode->data = data; newNod...
Node* temp = head; while(temp!=NULL){ temp = temp->next; } This will guarantee that the only way you get out of this loop is if temp is null. And what do you do on the next line? temp->next = newNode;// I think fault is here. Dereference temp! You probably wanted temp to point to the last node after the loop. You...
63,994,751
63,994,832
Call a C++ class method without a class instance?
Long story short, I am trying to build a wrapper to access C++ source code from a C main function (I have to do the conversion because of Embedded systems); however, I am having trouble calling the methods from the class to an external function without creating an instance of that class. I want to pass this *side point...
You can call a static member function of a class without an instance: just add the class name followed by the scope resolution operator (::) before the member function's name (rather than the class member operator, ., as you have tried). Also, in your Cube_C function, you should not dereference the side pointer, as the...
63,994,958
63,996,201
Run libpcap without sudo/root
I am using libpcap to sniff packets and also to create raw packets in C++ in Ubuntu 18.04. These features require admin(sudo) permission. I am checking for a way to remove the dependency. When I run my code without sudo, I get the following error: pcap_open_live(): You don't have permission to capture on that device (s...
I found the answer here. Issue turned out to be my hard disk not mounted with sudo. I built my tool in home folder and with setcap, I am able to sniff packets without sudo now.
63,995,081
63,995,701
Qt: How do I write data immediately to a QProcess?
My QProcess is very simple and goes something like: #include <iostream> #include <string> int main() { std::string a, b; std::cout<<"Enter value of a: "; std::cin>>a; std::cout<<std::endl; std::cout<<"Now, enter value of b: "; std::cin>>b; std::cout<<std::endl; std::cout<<"Value of a is "<<a<<" and value of b is "<<b<...
No need to use ...toStdString().c_str() for such a cases when having QString and QByteArray. Do the following: if ( proc->state() == QProcess::Running) { proc->write(qinput->toPlainText().toUtf8() + "\n"); // as I understand, \n will flush the line } Note that you can also use proc->write("\n"); to simulate "pres...
63,995,368
63,995,741
How can we multiply each elements of an array to each other and store each product values in a array in c++?
example: let's say we have an array of arr1 [1,2,3,4] , the products will be 1x2, 1x3, 1x4, 2x1, 2x3, 2x4, 3x1, 3x2, 3x4, 4x1, 4x, 4x3. so the new array will be like arr2 [2,3,4,2,6,8,3,6,12,4,8,12]. I thought about going with : for( int i=0; i<n; i++){ for(int j=0; j<n; j++){ arr2[i]= arr1[j] * arr1[j+1]; ...
Use an if statement to check that i != j before doing the multiplication. You also need another index variable to hold the index in the output array, you can't use i for this, since it stops at n. You also can't use i*n + j because you're skipping elements (there may be a formula for the desired index, but using anothe...
63,995,518
63,995,823
Fast input/output for Competitive Programming
I see people using this snippet extensively for achieving fast i/o in competitive programming ios_base::sync_with_stdio(false); cin.tie(NULL); Though i understand what it does mostly from here : Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); I want to know why this statement is not included cout.tie(...
As you can see in this example and in the docs, std::cin and std::cerr are both tied to std::cout by default, but the relationship is one-way. There is no need to call cout.tie(NULL) because the tied stream is already nullptr. The statement would have no effect. You would not be able to use an argument of 1; tie take...
63,995,967
63,996,352
Why referenced vector address cannot be dereferenced in cpp?
I am trying to dereference a referenced vector address as follows: #include <bits/stdc++.h> using namespace std; int main() { vector<int> p; p.push_back(1); p.push_back(2); p.push_back(3); p.push_back(4); p.push_back(5); p.push_back(6); cout << (*(&p)) << endl; cout << (*(&p + 3)) <...
std::vector<int> p; is an object that manages consecutive storage of elements of type int. &p would be an address of such an object. What that object contains is unspecified. You can expect a vector object to contain, e.g. the pointer to an array of elements allocated on the heap, the current size and capacity. To get ...
63,996,087
63,996,183
C++ Synchronization Library
I was trying to learn various Thread Synchronization Techniques and understand that they are as mentioned below: Mutex Condition Variable Semaphores Please add if I missed any - however I found that we do not have C++ semaphore APIs available as like in C (semget , sem_wait , sem_init) Am I true in my understating?
There's quite a bunch. std::promise and std::future as mentioned by πάντα ῥεῖ in the comments, but also std::call_once. (These are all C++11, as tagged) C++20 adds the <semaphore> header, and also <latch>.
63,996,135
64,025,595
(BOOST) Filter out the edges of a graph iteratively
I have a connected graph A (level 0) and I want to populate the next level with graphs B,C,D... by iteratively removing one edge at a time in A. Here is how my code begins: struct VertexData { long ID; }; typedef boost::adjacency_list<boost::listS, boost::listS, boost::undirectedS,VertexData, property< edge_index_...
Thanks to the discussion on this question (here), I was able to come up with a solution to my problem. I took the same approach as in the thread and decided to 'blacklist' each edge individually: typedef std::pair <int, int> Edge; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_pro...
63,996,251
63,996,443
Assure that parameters passed to a function are unique
I have a function that looks like this, that calls a function from a third party dll: void f1(const double * const input, double * output){ // this function will modify output[] // I have no knowledge of the implementation of this function, only that it wants // 3 doubles as the input parameters, and it wi...
No, you can't have such a check at compile time. There are other options you have though, which are done at runtime. Make a copy of the input. That way, you won't ever get in a situation where you change the same memory. This is of course not very useful if the array is big, but if the array is only 3 doubles, it's no...
63,996,276
63,998,801
How to do variadic deduction in std::function's parameters?
I try to implement a function f: (std::function -> int) which will pass 1s into input_functor with c++ variadic template. Let input_functor be g. For example: If g is std::function<int(int,int)>, then f return g(1, 1). If g is std::function<int(int,int,int)>, then f return g(1, 1, 1). If g is std::function<int(int,int...
You have 2 issues: definition order: template <typename T> int apply(std::function<int(T)> func) { return func(1); } should be place before the recursive function to allow to be visible and ends recursion. lambda is not a std::function, so deduction don't happen template <typename T, typename... Args> int apply(...
63,996,509
64,006,584
How can I address unique sections of reused global memory for each active thread block?
Note: I am using a GT 740, with 2 SMs and 192 CUDA cores per SM. I have a working CUDA kernel that is executed 4 times: __global__ void foo(float *d_a, int i) { if (i < 1500) { ... ... ... } } int main() { float *d_mem; cudaMalloc(&d_mem, lots_of_bytes); for (int i = 0; i < 1500; i +=...
Simplest way would be foo<<<2, 384>>> or foo<<<2, 192>>> and putting a for loop around the calculations in your kernel. Then you can select the half of memory with blockIdx.x. Even if the two blocks are scheduled on the same SM, it would work. This method also works with more than one block per SM, e.g. (for quarter m...
63,996,603
63,996,688
How to pass array initialization thru custom structure?
Usually array could be initialized like this: int ooo[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; I need to hide it into the custom structure like this: template <typename T, size_t dim1, size_t dim2> struct MyStruct { private: T m_data[dim1][dim2]; }; How to pass the initialization to the arra...
It would work if you can make the member public, and add a set of braces. This is aggregate initialisation: MyStruct<int, 3, 3> s = {{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, }}; I need to hide it into the custom structure ... If you need the member to be private, you cannot rely on aggregate initialisa...
63,997,007
63,997,093
Is there a way to change color without outputting the ANSI escape sequence in C++?
I am on android, using termux and clang. I am trying to do something like the echo command but with colored output (for fun.) I have this code, and the normal outputting works, but I'm confused on how to change color without the ANSI escape sequence being outputted with the text? This is my code: #define RESET "\033[0m...
You will need to use a library that understands how to write to the terminal. You could look at ncurses. Its been a while since I did any of this stuff but if you want to draw (term used loosely) on the terminal this is a simple library that abstracts away particular terminal devices. It is used by people writing OS in...
63,997,031
63,997,049
Does memory leak in a while loop when the same pointer is reinitialized
Does this cause a memory leakage? while(true){ std::string* items = new std::string[size]; if (SOME_CONDITION){ //do something } } delete[] items; The while loop may iterate over hundreds of times but the same pointer is resized so I think it shouldn't cause a memory leakage.
Yes, this will cause a memory leak. If you call new[] twice, you will allocate two chunks of memory. If you call delete[] once, you will only free one of them. I don't know what you mean by "same pointer is resized" exactly. Nothing is resized in this loop, it just allocates a new block of memory each iteration. Here's...
63,997,059
64,010,563
LuaBind c++ error handler when calling a Lua function
I am little newbie in C++ scripting but I know some things. I'm compiling a plugin that use a function to call an Lua callback using the LuaBind, but the client crashes when function doesn't exists on main.lua, also I'm trying to add an error handler to that functions... I don't know what I can do to solve it. Here is ...
Solved. Thanks to my friend habi. luabind::object func = g[name]; if( func ) { if( luabind::type(func) == LUA_TFUNCTION ) luabind::call_function<void>(L,"onServerFrame", elapsedTime);}
63,997,131
63,997,218
Is the function of nanosleep() removed in C++14?
I tried to compile the below code calling nanosleep() using C++14, but it failed with an error: 'nanosleep' was not declared in this scope nanosleep(&ts, NULL); #include <stdio.h> #include <time.h> #include <stdint.h> #include <sys/time.h> #include <sys/resource.h> int main(int argc, char *argv[]) { struct ...
nanosleep is a POSIX function and has nothing to do with the C++ standard. What you want for C++ is sleep_for found in the thread and chrono header. See https://en.cppreference.com/w/cpp/thread/sleep_for
63,997,370
63,998,453
Qt: How to "grey out" options using QComboBox (and make unselectable)
I'm building a GUI using Qt Creator, and I have a dropdown menu using a QComboBox with X many different options. For example, my dropdown has "Apple", "Pear", "Cookie", "Banana". Apple is the first choice (at the top), then pear, and so on. Using QComboBox, how do I "grey out" the last two options, "Cookie" and "Banana...
@pptaszni was correct. Tested the method below, and it works. Using the following, I am able to 'grey-out' options and make un-selectable in a QComboBox. _ui->comboBox_4->setItemData(3, false, Qt::UserRole -1); Inside my mainwindow.cpp - the code is as follows, which allows me to choose the 'row' I wanted greyed out. ...
63,999,002
63,999,090
Having trouble with getting one pattern printed correctly
I have to make figures based off of the input value at the start of the program. It's this section that is giving me a hard time. for (int i = a; i > 0; i--)//Diagonal line up and to the right { for (int j = i; j > 0; j--) { cout << " "; } cout << "*" << endl; } ...
You're just off by 1. Each line should have one less space before the *. So subtract 1 from i in the loop that prints the spaces. for (int i = a; i > 0; i--)//Diagonal line up and to the right { for (int j = i-1; j > 0; j--) { cout << " "; } cout << "*" << endl; }...
63,999,050
63,999,980
In-place string compression problem using C++
Hi I'm attempting to solve this interview question problem: String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string "aabcccccaaa" would become "a2b1c5a3". If the "compressed" string would not become smaller than the original string, yo...
Main problem: wrong use of erase() This is a very nasty issue: string::erase() has several signatures. There's a form with iterator, where you provide the start and end iterator for the region to be erased. You think to use this one. But in reality, you don't work with iterators but with positions. With positions, er...
63,999,142
64,000,219
Is it possible to set a text file to UTF-16?
My code for writing text works for ANSI characters, but when I try to write Japanese characters they do not appear. Do I need to use UTF-16 encoding? If so, how would I do it on code? std::wstring filename; std::wstring text; filename = "path"; wofstream myfile; myfile.open(filename, ios::app); getline(wcin, text); myf...
From the comments it seems your console correctly understands Unicode, and the issue is only with file output. Here's how to write a text file in UTF-16LE. Just tested in MSVC 2019 and it works. #include <string> #include <fstream> #include <iostream> #include <codecvt> #include <locale> int main() { std::wstring ...
63,999,949
64,000,429
Print dereferenced values from list in GDB
I am looking at a core file in gdb. I have a std::list of pointers to objects that are on the heap. Debugging with GDB, printing the list returns a list of addresses. That makes sense. I can print the dereferenced object of the first element in the list easily i.e. 'print *$1.my_list.front()'. I want to see the conten...
gdb has pretty-printers for most of the standard library and thus just print your_list should be enough in most cases. However, since you have a list of pointers and you want to see the referenced objects you have to get one element of the list and then deference it by using p *your_list.front() as you have already don...
63,999,953
64,028,460
std::conditional with unknown type
I'm currently writing a library which makes use of C++20's std::span. Compiler library support for std::span is at this point rather scarce. Therefore, I have a marco which allows to use a 3rd-party implementation instead (in my case tcb::span). The macro looks like this: #ifdef SPAN_BUILTIN # include <span> # defi...
Nice question! Let's answer it step-by-step constexpr const bool span_builtin = // ... Does something like this exist? Would this work? Probably not https://stackoverflow.com/a/45594334/1691072 We could use this but the issue with this is that below C++20, Span would not be defined Also we cannot officially add our ow...
64,000,246
64,000,315
No matching function for call to 'init_pair'
I use termux with clang. I've tried compiling the following code in clang but it outputs an error, mentioned in the title. Here is the code. #include <ncurses.h> #include <string> using namespace std; int main(int argc, char** argv) { initscr(); start_color(); init_pair(1,argv[1],argv[2]); attron(COLOR_PAIR(1)...
The actual error message tells you what the problem is: > clang -c foo.cc foo.cc:8:1: error: no matching function for call to 'init_pair' init_pair(1,argv[1],argv[2]); ^~~~~~~~~ /usr/include/curses.h:648:28: note: candidate function not viable: no known conversion from 'char *' to 'short' for 2nd argument; derefe...
64,000,372
64,000,458
vector of call back functions and function pointer binding
I am new to the std::function and trying to implement a callback function. In the following code "Callback_t" contains a function that holds a vector of function to be called. Class "other" is a nested class inside "SomeClass". An object of "SomeClass" contains an array of nested class object "b". The "other" class co...
other(SomeClass *loc, int id){ this->id = id; this->loc =loc; fptr = std::bind(&other::func,this); } The constructor binds fptr to this, which is the constructed object. Now, pay careful attention: this->b[i] = other(this, i); This ...
64,000,862
64,000,940
Why output does not show initialized value -1?
int main() { cout << "Please enter your first name and age\n"; string first_name = "???"; int age = -1; cin >> first_name >> age; cout << "Hello, " << first_name << " (age " << age << ")\n"; } According to the book Programming Principles and Practice Using C++ 2nd edition (Auth...
The behavior described in your book is correct until C++11. Until then, only the failbit was set if extraction failed. The value itself was left unmodified. However, since C++11, the value is now set to zero, in addition to the failbit being set. See this reference page on std::istream::operator>> for further informati...
64,001,118
64,001,396
Template functions using namespace as parameter?
For performance reasons, I have to make my own classes of vectors, matrixes, tensors, etc, with explicit operations. Since I only work with 2D or 3D dimensions, I defined the classes using namespaces for each dimensions. This is a simple draft of the code: namespace Dim2 { class Vec { public: double...
You can use type traits-like helper structs to reduce the number of arguments used to call doSomething(). namespace Dim2 { class Vec { public: double components[2]; }; class Mat { public: double components[2][2]; }; struct Chooser { using Vec = Vec; ...
64,001,224
64,001,316
c++ how can I ignore the second message in this condition
double const A = 0.80, B = 0.60, C = 0.40, D = 0.20; char code1, code2; int volume, student; double price, totalcost, totalvolume, totalprofit; cout << "Enter the number price for one book :"; cin >> price; cout << "Enter the book in stock :"; cin ...
This snippet of code: if (totalvolume !=0) totalcost = totalvolume * price; cout << " totalcost is :" << totalcost << endl; The third line in this code snippet "totalcost is: " will always print if the outer "if" statement condition is satisfied. If you want it to print only when this if statement is true,...
64,001,674
64,001,705
C++ Template is sending a "false argument" a bad practice?
std::stoi is throwing some errors in specific cases. I don't want to use try/catch block, so I googled a little bit about char convertion and saw that std::from_chars was doing exactly what I wanted, without those try/catch block. Obviously, using std::from_chars directly works pretty well, but I don't like the syntax....
You are not checking the return value of std::from_chars for failure, eg: auto [p, ec] = std::from_chars(str, str + strlen(str), var); if (ec != std::errc()) { ... } That said, another way to deal with the template argument T without using a type-casted input parameter is to simply specify the desired type explici...
64,002,003
64,002,146
how can i implement a function which can passin vector and int *?
I want to write a function which can modify element for all container which space is continueous, like, vector, int*. char* .... here is my code: #include <vector> #include <string> #include <iostream> using namespace std; template <typename T> void test(T* t, size_t size) { for (size_t i = 0; i < size; ++i) { ...
If you want to add 2 to each element of a collection, C++ already provides a way to do that: std::vector<size_t> a = {1,2,3,4}; std::transform(a.begin(), a.end(), a.begin(), [](int i){ return i + 2; }); This has a few obvious advantages over your code: it works with non-contiguous collections (as well as contiguous o...
64,002,283
64,023,520
Copying unique string from one list to another list from text file
I've been asked to make a list of data from a text file of words which is equal to a specific length of letters, the user inputs the length wanted and the function would make a list of all the words that have the same length. I tried making it with a list but changed to a vector but I still couldn't manage to make it w...
int main() { vector<string> wordListA; int wordLength=3; string filename; string line; cin>>filename; ifstream myfile; myfile.open(filename); // opening the filename given in command line if (myfile.is_open()) //testing if the file is opened or not ...
64,002,397
64,013,760
Catch2 - Populating singleton with different mock data for different test files
I am using Catch2 for unit testing in my C++ project. I have a singleton class and it is being used in different test files. For example one file might be testing the singleton itself, and another file testing the interaction between the singleton and another component. As such, I was wondering if there is a way that I...
You probably want a Fixture. Fixture documentation: https://github.com/catchorg/Catch2/blob/master/docs/test-fixtures.md
64,002,799
64,002,952
Is there a way to spawn a std::thread using an object and its non-empty argument list call operator?
I'm new to std::thread and C++11 in general. Trying to toy with the examples from https://en.cppreference.com/w/cpp/thread/thread/thread, I am trying to see if I can spawn a std::thread using a class member function call operator with non-empty argument list as in the code below: // main.cpp #include <iostream> #inclu...
std::thread doesn't let you pass by reference unless you're explicit because it's an easy source of lifetime issues. Use std::ref to be explicit that you're passing i by reference: std::thread t1( f, std::ref(i) ); Alternatively, pass by value. Think hard before you pass something to a thread by reference and make sur...
64,003,065
64,003,090
Printing out an array as an evenly spaced rectangle
Ok so I have this code as part of a project to print an array: #include <iostream> #include <string> #define ROWS 12 #define COLS 10 using namespace std; void image_print(unsigned char image[ROWS][COLS]) { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { ...
#include <iomanip> cout << setw(3) << +image[r][c] << " "; setw is an I/O manipulator which sets the field width for the next item to be output.
64,003,068
64,010,715
comparing against time with chrono c++
I want to pretty much say "as long as we are under a certain time, continue to iterate" the code for this looks like int time = atoi(argv[1]); auto start = std::chrono::high_resolution_clock::now(); while((std::chrono::duration_cast<chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count()) < ti...
int time = atoi(argv[1]); What units is time? seconds? nanoseconds? For this answer I'll assume seconds, but change it to whatever you need: std::chrono::seconds time{atoi(arv[1])}; Next: auto start = std::chrono::high_resolution_clock::now(); high_resolution_clock is going to be a type alias to either system_clo...
64,003,591
64,005,810
Convert from base to derived class at runtime using template logic
I am writing a small Database of sorts and seem to have run into an issue. I have 3 Statement types (each of which correspond to CREATE, INSERT and SELECT. The definitions of these types are: class Statement { }; // Base class, contains common stuff like the table name class CreateStatement : public Statement { /* C...
The way I would do this would be something like this: class Statement { ... virtual void parse(const std::string &stmt) = 0; // A string view will work here too. virtual bool execute() = 0; ... }; class Create : public Statement { ... virtual void parse(const std::string &stmt); // Implement ...
64,004,241
64,004,323
Overloading operators with structures in c++
So I am doing a simple, (or so I thought) exercise to help build my C++ skills. I have this simple struct to keep track of date information. I need to overload an operator to display the results. This is a simple function that I have used before in classes, and never had any problems with. However, in this exercise I a...
Your structure does not implement any method. Instead of calling date.year() simply call date.year
64,004,785
64,004,902
Header files and include for sourcing functions
I am quite new to C++, coming from an interpreted language I am having a bit of difficulty with understanding how header files relate to libraries and dependencies. For example, suppose I have the main body of my project: #include <vector> //----------------------------define some auxiliary function which deals with v...
Just the file that uses the Vector Component needs to include it. You can also include a component when you include another file. For Example: Example.h #include <vector> //----------------------------define some auxiliary function which deals with vectors void A(std::vector<int> &vect) { vect.clear(); } Exam...
64,004,846
64,008,059
are bits in structs guaranteed to be contiguous?
I played with https://gcc.godbolt.org/ and this code seems to always return 1. However I wonder if standard guarantee this. #include <cstdint> struct S{ uint8_t a : 6; uint8_t b : 2; }; int main(){ return sizeof(S); } My real example is following: struct Pair{ uint64_t created; // 8 bytes uin...
Most compilers will give you bit fields that are packed together, although the behaviour is implementation defined. One way to check would be to add a static_assert to compare the size of your struct definitions with and without the bitfields. This way you would get a nice compile time error once the implementation doe...
64,005,029
64,005,855
Segmentation fault C++ Program
I want to write a program to construct a n*n matrix and fill it with 1 to n^2. but I‌ get a segmentation fault( core dumped). I‌ have no clue why this happens. Any help will be appreciated. int array[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { array[i][j] = t; t++; }
Some problems to be solved in your code: The variable length array (VLAs) are not a part of C++ standard. Thus, using syntax like: int n = 10; // non-const value int incorrect_array[n][n]; // invalid The array size must be known to compile time. Since the size of the array provided by you in the question is yet uncl...
64,005,343
64,005,425
How does upper_bound work with custom object type val?
I am currently learning about upper_bound algorithm in c++ and things are quite easy if the third parameter val is of type Integer. However, i came across an exammple with custom type val and things got a little confusing. Sample code. class Pocket { public: int value; Pocket(int value) : value(value) {}; b...
Your program has undefined behaviour. The range you pass to upper bound must be sorted by < (for the three argument overload).
64,006,326
64,012,535
Check if a FlexBuffers buffer is not corrupted in C++
I want to use FlexBuffers as a kind of binary format JSON. But since the buffer and its size may be given from an external user, I want to know if there's any way to check if a FlexBuffers buffer with its size is real and not corrupted in C++.
There is currently no Verifier implemented like for FlatBuffers, and we absolutely should have one. I'd open an issue on GitHub about it.
64,006,854
64,014,886
Can I use std::unique_lock to AttachCurrentThread and DetachCurrentThread from JNI?
class SmartAttachCurrentThread { public: SmartAttachCurrentThread(JavaVM *jvm, JNIEnv *env) : jvm(jvm), env(env) { //TODO: throw if jvm null? jvm->AttachCurrentThread(&env, NULL); } ~SmartAttachCurrentThread() { jvm->DetachCurrentT...
Your class constructor is taking the JNIEnv* parameter by value, that is why the env variable outside of the class is not being updated. You need to pass it by reference instead, eg: class SmartAttachCurrentThread { public: SmartAttachCurrentThread(JavaVM *jvm, JNIEnv* &env) : jvm(jvm) { if (!jvm) ...
64,007,065
64,014,211
How does std::unordered_set allocate bucket to provide O(1) lookup?
The unordered_set should provide O(1) lookup time in case of a good hash function. Each bucket contains items with the same hash value. Let's assume that our hash function is ideal and gives no collisions at all. Hash values can vary from 0 to max(std::size_t). How to organize unordered_set without allocating continu...
Each bucket contains items with the same hash value. Wrong. Each bucket "contains" items with the same value of:        hash(key) % current number of buckets. Let's assume that our hash function is ideal and gives no collisions at all. Not having collisions in pre-mod space isn't necessarily ideal: what matt...
64,007,068
64,007,343
Extending the class definition upon including a file inside its block
I am drafting some modification on a C++ I have been given. In order to separate my contributions for the time being, I would like to extend the class definition in a original header file by including another file. In terms of pseudo code it would be something like this class OldClass : public OldSuperClass { private...
What you have done can work. Just consider that #includes are simply about textual replacement. What you can put in the header is for example: // xy.h int x; So when it is expanded in: struct foo { #include "xy.h" }; The result becomes struct foo { // xy.h int x; }; Your code is invalid after replacing...
64,007,590
64,007,768
C++ cast with additional round brackets
What does the following statement do in C++? (*JImageGetResource)(jimage, location, val, size); This instruction is taken from here.
There's no cast involved. JImageGetResource is a pointer, by adding * in front of it, it will be dereferenced. Typically you will see this with iterators for example. In your case it's a function pointer. So the resulting code would be the same as resultingFunction(jimage, location, val, size). In line 1017: JImageGetR...
64,008,132
64,008,767
How to use add_definititions() variable inside c++ classes?
I have defined a couple of variables in my CMakeLists.txt like so: # the subject of the commit execute_process( COMMAND git log -1 --format=%s WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE GIT_COMMIT_SUBJECT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE ) add_definitions("-DGIT_COMMIT_SUBJECT=${GIT_COMM...
You can define macros as strings when building, but you need to enclose the strings in double-quotes: add_definitions("-DGIT_COMMIT_SUBJECT=\"${GIT_COMMIT_SUBJECT}\"") Now any use of the macro GIT_COMMIT_SUBJECT inside the code will be replace by a literal string.
64,009,202
64,009,251
Find value in vector of pairs
Here is my code (I cannot change the signature of the function): using VectorOfPair = std::vector<std::pair<std::string, std::string>>; bool some_find(VectorOfPair data, const std::string& k, std::string *value) { sort(data.begin(), data.end()); auto element = std::lower_bound(data.begin(), data.end(), ...
std::make_pair(k, "") is not a pair of std::string and std::string but a pair of std::string and const char*. Try std::make_pair(k, std::string("")) instead.
64,009,301
64,024,034
c++ Qt inheriting from QWidget gives linking error re missing vtable
I am on MacOS and I want to inherit QWidget for a class with QObject :: connect but i have a error: Undefined symbols for architecture x86_64: "vtable for Core", referenced from: Core::Core(QWidget*) in Core.cpp.o NOTE: a missing vtable usually means the first non-inline virtual member function has no definition. ld: ...
add the files with Q_OBJECT in the cmake like this for example : set(SOURCES core.cpp ) qt5_wrap_cpp(SOURCES core.hpp) add_executable(babel ${SOURCES} ${BABEL_SRC})
64,010,028
64,010,875
Does recursion in the C preprocessor abuse an inconsistency in the standard?
Consider this code: #define MAP_OUT #define A(x) B MAP_OUT (x) #define B(x) A MAP_OUT (x) A(x) Then A(x) expands to B MAP_OUT (x), then B (x). Now take a look at the standard: After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing to...
Does B (x) belong to "resulting preprocessing token sequence for more macro names to replace"? No, absolutely not. Read again: After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. The resulting preprocessing toke...
64,010,090
64,010,103
Accsess nested class from outside in C++
Hello I want to access a nested class from other class. class OutSideClass { public: class InSideClass { ... }; friend class InSideClass; }; class Other { InSideClass x; // This doesn't work }; The class InSideClass is a public class so I don't understand why can I access it from outside I ...
The class InSideClass is inside OutSideClass, so you have to specify so. class Other { OutSideClass::InSideClass x; // This should work }; In the second case, the declaration is inside OutSideClass, so you should remove OutSideClass<T>:: from the declaration. Also typename seems to be required according to these: ...
64,010,249
64,014,756
Why would my BHO fail to obtain IWebBrowser2 pointer inside IObjectWithSite::SetSite()?
I've seen a number of BHO samples and I try to implement this common scenario: STDMETHODIMP CBhoImpl::SetSite(IUnknown* pSite) { if (NULL != pSite) { CComQIPtr<IWebBrowser2> webBrowser(pSite); // webBrowser should hold a non-null pointer here // but it holds a null pointer instead ...
Try querying the IUnknown parameter for IServiceProvider, and if successful then you can call its QueryService() method to get the IWebBrowser2, eg: STDMETHODIMP CBhoImpl::SetSite(IUnknown* pSite) { if (pSite) { CComPtr<IWebBrowser2> webBrowser; CComQIPtr<IServiceProvider> pServiceProvider(pSit...
64,010,624
64,011,527
c++ hex set of strings to array of bytes not return vector
So basically , I want to create a function that takes this hex pattern: "03 C6 8F E2 18 CA 8C E2 94 FD BC E5 03 C6 8F E2" and returns this array of bytes: BYTE pattern[] = { 0x03, 0xC6, 0x8F, 0xE2, 0x18, 0xCA, 0x8C, 0xE2, 0x94, 0xFD, 0xBC, 0xE5, 0x03, 0xC6, 0x8F, 0xE2 }; My main problem is what i need like each 0x03 ...
You have a number of minor errors. By reusing your converter object it no longer works after the first conversion because it gets into an error state. Try this version that recreates the stringstream each time round the loop (you could also call converter.clear(); at the end of the loop). while (ss >> word) { int t...
64,010,829
64,011,299
Making QGraphicsEllipseItem always on top of all figures
I created small game when player controls the ellipse and while he moves I draw other Rect items on the screen. While I like that they overlay all other existing items, I dont want new items to cover that ellipse. Is there any way to make that ellipse always on top of anything else?
You can use QGraphicsItem::setZValue on your rectangles and ellipse. For example, upon creating an ellipse item you give it value of 2 and upon creating a rectangle item you give it value of 1. This way ellipse will always overlay any given rectangle. If you like the way new rectangles overlay existing ones, you can re...
64,011,696
64,011,838
Severity Code Description Project File Line Suppression State Error C3872 '0x2019': this character is not allowed in an identifier
I'm new to C++ and my code is giving me the following error when I try to build the project: Severity Code Description Project File Line Suppression State Error C3872 '0x2019': this character is not allowed in an identifier I am using Visual Studio 2019 Professional. I am running my code in Release and in my properti...
You cannot use the ’ character (or, indeed, any punctuation marks) in the name of a variable in C++. You can only use Latin letters (upper or lower case), decimal digits ('0' thru '9'), the underscore (_) character and some Unicode characters (as detailed in the reference linked below). The first character in the name ...
64,012,327
64,012,414
Turn off the rightmost set bit
int n; cin>>n; int i=1,m=1; while(n&i==0) { i=i<<1; m++; } //now flip mth set bit from right; int ans=n^(1<<(m-1)); cout<<ans<<endl; What is the mistake in the above code for unsetting the rightmost bit of an integer?
In C++ == operator has higher precedence than & operator, so n&i==0 won't be what you want. Use (n&i)==0 instead of that.
64,012,632
64,012,778
How to count instances of matrices in a vector?
I'm trying to count instances of matrices using the following: // setup some matrices to count instances of std::vector<std::vector<int>> matrix1({{1, 2, 3}, {4, 5, 6}}); std::vector<std::vector<int>> matrix2({{1, 2, 3}, ...
From the cppreference page on reserve(): Increase the capacity of the vector to a value that's greater or equal to new_cap. If new_cap is greater than the current capacity(), new storage is allocated, otherwise the method does nothing. reserve() does not change the size of the vector. (emphasis mine) So your counts_ ...
64,014,782
64,014,891
C++ program crashes when trying to sort a vector of strings
I'm trying to sort an array of strings in C++, but I am getting the following error message: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid The following program causes the previous error. I got the error when v has 17 elements, but everything ...
The comparator you pass to sort must satisfy the named requirement Compare: Establishes strict weak ordering relation with the following properties For all a, comp(a,a)==false If comp(a,b)==true then comp(b,a)==false if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true With your comparator: comp(a,a) == true....
64,014,902
64,014,949
How can I send a PDF file over a socket?
I opened a file in binary format and extracted this file as String. After, I tried to send it as HTTP reply. Finally, it looks like this: ptr->Sendall((char*)"HTTP/1.1 200 OK\r\n"); ptr->Sendall((char*)"Content-Type: pdf/html\r\n"); ptr->Sendall((char*)"Content-Length: 16384\r\n"); ptr->Sendall((char*)"\r\n"); ptr->Se...
Binary files by definition may contain characters that preclude them from being represented as C strings. The first NUL byte you hit will end the string prematurely and those appear frequently in all kinds of files. std::string can represent these just fine. c_str() will return a pointer to the complete data, but you'l...
64,015,235
64,015,359
Using auto vs const auto& to temporary keep result of method call
Assuming I have class Container { public: T getValue() const { return t; } const T& getCRef() const { return t; } private: const T t; }; void f(const T& arg) { ... } What is the preferred way to bind return value temporarily inside a function? E.g. what should I prefer and why? void method(const Conta...
Is that correct? Yes. If so, should I prefer const auto& over auto for such cases all the time? It depends on what you intend to do. If you want a copy, then use an object variable. If you want to refer to an object stored elsewhere, then use a reference variable. Also, should I prefer getCRef() interface over get...
64,015,701
64,016,660
Implement a function that prints an array using pointers
I need to print an array by implementing the use of a function before the main function. So I tried the following function: int* printArr(int* arr) { for (int i = 0; i < 5; i++) { cout << arr[i]; } return arr; } I encountered two problems when implementing this into the whole code. First, this i...
The declaration and implementation of printArr() is all wrong. First, this is printing what I think is the address of the array and not the actual array. The printArr() function itself is printing the contents of the array (well, the first 5 elements anyway), and then returning the address of the array. It is main()...
64,015,744
64,016,302
How do we compile and run a program on the CS50 ide?
So basically I am a starter in programming. I do not understand how do I compile and run the program below on Harvard's CS50 IDE. #include<iostream> using namespace std; int main() { cout<<"HelloCS50"; } enter image description here
Start typing in the terminal. follow each command you type with the enter key. Use the command ls to list all the files in your directory. One of those files should be the code you just wrote and saved. It's not a requirement, but will make it easier to have the filename end in '.cpp'. If your file does not have that, ...
64,016,040
64,017,055
QPainting QPixmap using clipping to gain performance
I'm trying to create a simple Image Viewer in Qt with zooming supported. To display an image file I load it into a QImage and create a QPixmap. class NN: public QWidget{ Q_OBJECT Q_DISABLE_COPY(NN) public: NN(QWidget* parent = nullptr) : QWidget(parent){ } const QPixmap& pixmap() const { ...
When m_pixmap and/or rect() are very large, the bulk of your slowdown is likely coming from here: m_pixmap.scaled(rect().size()) Here you are you are asking Qt to create a new QPixmap object the same size as rect(), which is a potentially very expensive operation; and passing that QPixmap object into the call to drawI...
64,016,051
64,016,400
C++ template that knows its argument's position
I am new in c++ metaprogramming and few days ago I decided to write a template with variadic parameter pack, that knows in which position in parameter pack stands first int. More precisely I want to have a struct with name GetIntPos and with static constexpr int value which indicates the position of int in parameter pa...
My recursive way #include <iostream> #include <type_traits> template <std::size_t, typename ...> struct GIP_helper : public std::integral_constant<std::size_t, 0u> { }; template <std::size_t N, typename T0, typename ... Ts> struct GIP_helper<N, T0, Ts...> : public GIP_helper<N+1u, Ts...> { }; template <std::...
64,016,643
64,021,390
QTimer running in QThread
I need a class with a timer which will do a task every 100msec, this class need to run in a thread, so I would like to combine qtimer with qthread. I have created the following code: class Worker : public QObject { Q_OBJECT public: void setEnabled(bool enable); public slots: void initialize(); ...
No, it's not entirely correct. Worker::setEnabled(bool enable) should be a slot too, as it's invoking the QTimer::start() slot directly. Calling Worker::setEnabled directly from the main thread then results in undefined behavior. You must use a signal-slot connection to invoke setEnabled safely from the main thread. Yo...
64,016,809
64,037,175
How to use QMediaMetaData correctly to define media files parameters?
I need to determine the parameters of the audio file: bitrate, sampling rate, bit depth, audio format. I have tried to use it like that: #include <QtMultimedia/QMediaMetaData> #include <QtMultimedia/QMediaObject> #include "mainwindow.h" #include "ui_mainwindow.h" . . . void MainWindow::on_pushButton_1_clicked() { QM...
You're welcome. Define a player variable: private: QMediaPlayer *m_player; In your code: m_player = new QMediaPlayer(this); connect(m_player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), this, SLOT(onMediaStatusChanged(QMediaPlayer::MediaStatus))); m_player->setMedia(QUrl::fromLocalFile("C:\\...
64,017,043
64,017,718
How to make const variables filled at runtime accessible across all of the program?
What technique should I use to make a list of const variables whose value is known only at runtime accessible across all of the program? Yes, I can make it in a way like that: class some { static const int a; static const int b; ... static const int z; }; int some::a(f1()); int some::b(f2()); ... int s...
I know many won't like this, because Singletons are considered bad design, anti patterns and whatnot. Though Singletons are ubiquituous in many framework and architectural designs. That said, now for the OPs question: But what if there are many such variables? In such a case there must be a lot of corresponding functi...
64,017,554
64,017,621
C++ program compiles in Visual Studio 2010 but not Mingw
The program below compiles in VS 2010, but not in a recent version of Mingw. Mingw gives me the error "conversion from int to non-scalar type 'tempClass(it)' requested". Class "it" is just a simple class to use in the template for the purpose of illustration. #include <iostream> #include <string> using namespace std; ...
MinGW is correct to refuse the code since it relies on two implicit user-defined conversions. One from int to it and one from it to tempClass<it>. Only one user-defined implicit conversion is allowed. The below works since it only requires one implicit conversion: tempClass<it> thisOne = it(5); You can also let the co...
64,017,579
64,026,748
Pass a bidimensional array and store as a class menber
I have an C++ class with a bidimensional array of ints. This member is setted by one method of the class. class MyClass { private: int values[][4]; public: MyClass(); void setValues(int values[][4]); if I do this: MyClass::setValues(int values[][4]) { Serial.println(values[0][0]); } Everything work...
I solved this with Vector.h from ArduinoIDE libiries. But, I don`t use a Vector of Vectors... Frist of all, I created a struct struct MyStruct { int a; int b; int c; unsigned long d; MyStruct(int a, int b, int c, unsigned long d) { this->a = a; this->b = b; this->c = c; this->d = d; } }; ...
64,017,823
64,018,426
How to extract multiple substrings from a string?
My original string looks like this <Information name="Identify" id="IdentifyButton" type="button"/> from this string, how do extract 3 substrings string name_part = Identify, string id_part="IdentifyButton", type_part="button"
Assuming you don't want to use third-party XML parsers, you can simply use std::string's find() for each of your names: int main() { std::string s("<Information name = \"Identify\" id = \"IdentifyButton\" type = \"button\" / >"); std::string names[] = { "name = \"" , "id = \"" , "type = \"" }; std::string::size_t...
64,017,851
64,019,380
Is there a clean and fast way to find the min and max of an array
Is there a clean and fast way to find the min and max of an array int array1[] = {2,6,10,22,12}; results are min = 2 / max = 22 // Function void min_max(set<int> my_set) { for (auto i : my_set); } // Function to find the maximum element int findMax(set<int> my_set) { // Get the maximum element i...
You can find the min, max and sum in one pass: int array1[] = {2,6,10,22,12}; const int quantity = sizeof(array1) / sizeof(array1[0]); int max = array1[0]; int min = array1[0]; int sum = 0; for (int i = 1; i < quantity; ++i) { const int value = array1[i]; if (value > max) max = value; if (value < min) min = ...
64,018,265
64,057,106
Writing USB Disk Sectors Results in Permission Error 5
The code below is required by my app to write disk sectors of external USB drives. It works on most Win10 PCs, but it's returning error 5 for permission denied on a couple PCs. I have exclusions created for both Windows Defender and Malwarebytes. There's nothing in the event viewer related to the failure. The read func...
I found the answer where I wasn't expecting. I thought this had to be something related to how the file handles were being opened. Instead, turning off Real-time protection in the Virus threat protection settings for Windows 10 caused the error 5s to go away. To resolve without disabling real-time protection, you need ...
64,018,377
64,034,208
Avoiding data race condition between two ROS subscriber callback funtions
Let's suppose we've two ROS subscriber callback functions where the callback is called every time a new message is extracted from the queue and we want to use the value of a callback in another callback and vice versa. I've implemented this in a class with two member variables that store my data. I suspect a possible r...
You simply can make use of a Lock Guard using the same mutex instance in each of your callbacks like: std::mutex mutex_; void <class_name>::callback_function_1(<msg_type> &msg_holder) { const std::lock_guard<std::mutex> lock(mutex_); //Locked code here //The mutex is automatically released when lock goes o...
64,018,567
64,018,619
How to define a variable whose type depends on whether the size of a pointer equals a specific value
I know that C/C++ preprocessor doesn't know sizeof, but I'd like to define a variable in some way similar to this: #if sizeof(char*) == 8 uint64_t a; #else uint32_t a; #endif Is it possible?
You can use std::conditional_t like this: std::conditional_t<sizeof(char*) == 8, uint64_t, uint32_t> a;
64,018,651
64,019,073
How to find the position of the first 1 in a double value?
How to by a given value like 0.00...001 find the position of 1? I have a sample code like this: constexpr int PrecisionFromDouble(double val) { int d = 1.0 / val; int log = 0; while (true) { d = d / 10; if (d == 0) break; ++log; } return log; } It works with...
I think you can use log10 #include <math.h> constexpr int PrecisionFromDouble(double val) { return -(int)log10(val); }
64,018,731
64,018,888
Data get lost when written to binary file - C++
I have an array including 4994 vectors. I want to save the array in a file in binary format. Since I'm not used to doing that, I did a test to see if the array is successfully copied to the file. So, I first save the array in a file and then load the array from that file. Comparing the data, I find that they are differ...
Operations on files using the C++ Standard Library are buffered. The reason is that writing exactly as many bytes as the programmer asks can be very inefficient. For example, a spinning hard drive or an SSD drive cannot write single bytes, but only blocks of say 4096 bytes. So if you wanted to write a single byte, you'...
64,018,790
64,019,274
Specifying unsigned char storage for integer numerals
In terms of modern C++, is it possible to specify storage of a integer numeral to a char? I am looking to write auto var = 255; to initialize var as unsigned char type It is possible to specify other types of storage: auto var_ulong = 255ul; auto var_float = 255.f; However, not short or char? Surely I am missing somet...
There is no standard integer literal to do what you want, but you can add your own user- defined literal if you plan to do this a lot: namespace foo { // constexpr pre C++20 // | // V consteval unsigned char operator"" _uchar(unsigned long long x) { return static_cast<unsigned char>(x); } } using namespace fo...
64,019,166
64,118,693
gcc, segfault, and the mystery of the changing address of a static variable (across stack frames)
I get a segfault in my application and have been poking at it for multiple hours now. I was analysing the backtrace using gdb and noticed the following: (gdb) frame 3 (gdb) info address C_STATIC_STRING Symbol "C_STATIC_STRING" is static storage at address 0x66a660. (gdb) frame 2 (gdb) info address C_STATIC_STRING Symbo...
I would like to summarize the things I learned from the helpful comments above: It is inevitable for static variables to have different addresses in different Translation Units. Due to the phenomenon known as Static Initialization Fiasco, using the static variables in the way that I did, relies on "good luck" for the ...
64,019,743
64,020,738
Does std::thread make any guarantee about what's happened when its constructor returns?
If you call one of the nonempty std::thread constructors, is there any guarantee about the state of the thread when the constructor returns (assume the thread start-routine has a long lifespan)? Do you know whether the thread has actually started (i.e. its start-routine has been entered)?
From cppreference.com: The completion of the invocation of the constructor synchronizes-with (as defined in std::memory_order) the beginning of the invocation of the copy of f on the new thread of execution. So the constructor will finish before the supplied function starts, but otherwise there are no guarantees. In ...