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
70,350,288
70,351,312
Returned Eigen Matrix from templated function changes value
I came around some weird behavior concerning the eigen library and templated functions. Maybe someone can explain to me, why the first version is not working, while the other 3 do. My guess would be the first case freeing up some local variable, but hopefully someone can enlighten me. Thanks in advance. Here is the cod...
In the first version, auto ret = y_n + h * f(y_n); due to Eigen's expression templates this gives you an intermediate expression type, as opposed to a Matrix type. You would need to explicitly invoke eval() on it to force the lazy eval to occur (and in such converting the expression to a resulting Matrix type object);...
70,350,554
70,360,432
How can I fix this callback include problem?
I am kind of new to C++ (and StackOverflow). I am trying to get something to work, but I have some #include problems. I want to call a callback I made (from here), but I am struggling to do this. This is my code so far. When I include child.hpp in the someclass.hpp file (because it needs information about Child for Cal...
To solve the mentioned error("expected class-name before '{' token on child.hpp") you should remove the #include "someclass.hpp" from base.hpp and replace it with a forward declaration for class SomeClass as shown below. base.hpp #ifndef BASE_H #define BASE_H //NO NEED TO INCLUDE someclass.hpp #include <memory> class S...
70,350,675
70,351,468
Understanding more about type_traits
Setup I asked a question yesterday about template method overloading and resolving issues using type traits. I received some excellent answers, and they led me to a solution. And that solution led me to more reading. I landed on a page at Fluent CPP -- https://www.fluentcpp.com/2018/05/18/make-sfinae-pretty-2-hidden-be...
Vocabulary // template-head template<typename T = T{}> // ^^^^^^^^^^ ^^^- default template-argument // \ type template-parameter // template-head template<int i = 0> // ^^^^^ ^- default template-argument // \ non-type template-parameter Default template arguments are not part of ...
70,351,737
70,351,862
what does '#' mean in cpp code? here's a code for reference . I stuck at " char top = st.empty() ? '#' : st.top(); "
bool isValid(string s) { stack<char> st; for(int i=0;i<s.length();i++) { char top = st.empty() ? '#' : st.top(); The code is the solution for 'Valid Parenthesis' on LeetCode.
When you wrote: char top = st.empty() ? '#' : st.top(); The above checks if st is empty. If st is empty then top is initialized with the character literal '#'. Otherwise, top is initialized with the character returned from st.top(). Also, '#' is a character literal.
70,352,016
70,353,927
A complex read text file
I have a text file, which emulates the input to my script. Example of the file: 4 15 30 .... .... .... .... 1 1 2 3 1 2 2 1 2 2 The first line contains some constants, let's say n, a, and b. Next n rows contain some map nXn. Then there is a line with m - number of new coordinates and then m rows of these coordinates. ...
Based on your description, your input problem seems to consist of 4 stages: read one line which specifies n, a and b read n lines which represents the "map" read one line which specifies m read m lines which represents "new coordinates" Although it is possible to solve the problem using only a single loop and using a...
70,352,308
70,356,913
How to use untwister?
https://github.com/altf4/untwister I wanted to use the above program to predict some PRNG. I have read the 'usage' part, I though I should use it in cmd.exe by entering the path of the untwister. I entered the path of main.cpp, only MSVC pops up. Also, MSVC doesn't allow me to debug/compile the file, so I cannot run it...
OK, based on @drescherjm comment's, I've successfully build it. I installed msys2 and use mingw to build it. But the .exe file has error "_zst28__throw_bad_array_new_lengthv" I searched the error message on google, and discover that the problem may caused by gcc version. I downloaded an old version (10.3.0) of gcc a...
70,352,772
70,352,915
Why is 2 not > 0 ?? It is instead <= 0, but not < 0, nor == 0
I was messing around a bit in C++ when I came across an issue that made absolutely no sense to me. For some reason with a variable equal to 2, 2 > 0 returns false, but 2 <= 0 and 2 >= 0 return true, while also somehow 2 < 0 and 2 == 0 return false. However, if I use just a static 2, everything works as intended. Here's...
The compiler assumes that n is a zero when evaluating the conditionals. It's allowed to do that since while (n > 0); is undefined for positive n, and a compiler is allowed to assume there is no undefined behaviour. This is plausible since conditionals can cause branch prediction failures whereas outputting n (which is ...
70,352,776
70,353,051
Function To Count occurrence of given string
#include<iostream> using namespace std; void check_exist_get_count(string str,char ch) { int counter=0; for(int x=0;x<str.length();x++) { if(str[x]==ch) counter++; } cout<<ch<<" : "<<counter; } int main () { string str; cin>>str; for(int x=0;x<str.length();x++) { ...
You're just iterating over the string once in your main function, and for every character in that string, again go over the whole string and count how many characters like that are in there. What you don't do is track which characters you already have counted, that's why you count them multiple times. Don't nest loops ...
70,352,803
70,354,846
Microsoft speech NuGet package doesn't work in C++ project
I'm trying to use the Azure cognitive services speech api in a C++ project and followed the instructions to install the NuGet package (Microsoft.CognitiveServices.Speech) via this page. After that, I followed one of the basic tutorials, but my C++ project doesn't recognise the Microsoft namespaces, like No references ...
I see you only #include <iostream>. Indeed, the iostream header does not contain any Microsoft namespaces. As is described in Get started with speech translation, you need to #include <speechapi_cxx.h>. There seems to be an omission in the Get started with speech-to-text documentation: it doesn't contain the Import dep...
70,352,884
70,353,734
C++ Boost Priority Queue Behavior
I tried to find out exactly how the boost priority queue is implemented and I am confused. Header file (main.hpp): #ifndef MAIN_HPP #define MAIN_HPP #include <cstddef> #include <cstdint> #include <iostream> #include <boost/heap/priority_queue.hpp> typedef std::int32_t int32_t; typedef struct st { int32_t num; ...
You aren't accounting for the copy-constructor that will automatically be created for your class. In your case you wouldn't automatically get a move-constructor, but it's still nice to see where the compiler could do a move instead of a copy. If you change your st to e.g.: struct st { int32_t num; int32_t f; ...
70,352,966
70,354,840
Qt c++ Issue receiving data weighing scale Ohaus aviator 7000
I am trying to establisch a serial port connection to my Aviator 7000 weighing scale using Qt c++. The expected result would be a succesfull communication through the use of a byte command. Sadly I don't receive any bytes back from the scale. below you can find what I tried so far: const int Max_attempts = 5; c...
According to this manual you are supposed to send a byte 0x05 but you are sending 0x35 (the character "5"). Use bytes.append('\X05');
70,353,162
70,353,294
VS Code on Mac Using C++ Debugger Not Working Properly
I am having an odd issue. I am working in C++ and I have coderunner installed and the basic C/C++ extension from Microsoft, but I am having an issue with my debugger. #include <iostream> #include <vector> using namespace std; int main() { vector<int> numbers{10,20,30,40,50}; for(int i = 0; i < numbers.size(); ...
If the compiler supports C++11 standards then vector<int> numbers{1, 2, 3}; can be used. You should not get this error when you try the following usage: std::vector<int> numbers; numbers.push_back(10); numbers.push_back(20); numbers.push_back(30); numbers.push_back(40); numbers.push_back(50); If you are using Clang c...
70,353,631
70,353,803
Rabin Karp Algorithm Negative Hash
I have this Rabin Karp implementation. Now the only thing I'm doing for rolling hash is subtract power*source[i] from the sourceHash. power is 31^target.size()-1 % mod But I can't understand why we're adding mod to sourceHash when it becomes negative. I have tried adding other values but it doesn't work and it only wor...
When using modulo arithmetics (mod n) we have just n distinct numbers: 0, 1, 2, ..., n - 1. All the other numbers which out of 0 .. n - 1 are equal to some number in 0 .. n - 1: -n ~ 0 -n + 1 ~ 1 -n + 2 ~ 2 ... -2 ~ n - 2 -1 ~ n - 1 or n ~ 0 n + 1 ~ 1 n + 2 ~ 2 ... 2 * n ~ 0 2 * n + 1 ~ ...
70,353,963
70,365,820
CMake - Copy specific files in custom target
i want to copy specific files for code coverage from sub directories, which are generated during the build process via custom target. Is there a possibility, to do a recursive copy via add_custom_target and COMMAND, e.g.: add_custom_target(copyFiles COMMAND ${CMAKE_COMMAND} -E copy **/*.gcda ./ DEPENDS ${TARGET_NAM...
Your custom target may run a CMake script (e.g., ${CMAKE_COMMAND} -P find_and_copy.cmake) which is going to perform file(GLOB_RECURSE...) and then do file(COPY...) on found files.
70,354,413
70,355,580
Automatic template parameter deduction in unique_ptr and make_unique
Why do I get automatic template parameter deduction if I call class constructor directly but I do not get it in std::unique_ptr and std::make_unique? Here is an example: #include <memory> template <class T> class C { public: C(const T * const t_) : t(t_) {} ~C(void) { delete t; } private: const T * const t; }; Exam...
This is one way to solve it: template <class T> auto MakeUnique(T t) { return std::unique_ptr<std::remove_reference_t<decltype(*t)>>(t); } int main(void) { const int * const t = new int; auto * const c = new C(t); auto p = MakeUnique(c); return 0; }
70,354,647
70,354,906
What is meant by the statement that std::declval cannot be called?
On the cppreference-page for std::declval it says the following: Return value Cannot be called and thus never returns a value. What does this mean? Surely we call it when we use it? struct Foo { int func(){} }; decltype(std::declval<Foo>().func()) integer; /* ^ | ...
The program is ill-formed if std::declval<T> is odr-used. However, cppreference tries to phrase this in a way that most users will find easier to understand. A call to a function, or taking the address of the function, will normally odr-use that function. However, this is only the case if the call/address is actually e...
70,355,069
70,355,738
synchronization primitives: Equal latencies between atomics and mutex lock
I'm trying to improve my understanding of synchronization primitives in C++. I've measured latencies of various concurrent operations, such as: For a raw std::mutex, the time between .unlock() and the return of .lock() For a std::condition_variable, the time between .notify_one() and the return of .wait() For a std::b...
In an uncontended state an SRWLock is just an atomic int. So it's unsurprising that it performs the same as an atomic. You should see very different timings once you introduce some contention in your tests. An SRWLock is essentially a Windows version of a futex - a synchronization primitive that remains fully in user-s...
70,355,294
70,355,423
Seg Fault with Binary Heap Class when running on Linux, Insert Heap problems
I have implemented a binary heap class in C++ for school. I am having trouble with the program running on the school Linux server. My code outputs 100% correctly on my Mac. It appears to SegFault after the first line of code is printed from the main.cpp. I have tried using GDB and haven't been able to pin point the iss...
When inserting your first element you change cap from 0 to cap * 2, this is still 0 causing the subsequent heap[size] = k to have undefined behaviour. You should also presumably at this point also update cap to the new size of your array. Your next bug is that you do: size = size + 1; // update size heap[size] = k; // ...
70,355,767
70,355,897
Binding a class method to a method of another class
I have two classes where one is logic and one is the model. After initializing both, I would like to bind a b.funB()to a.funA() where A a; B b;. class A{ public: bool funA() { doStuff(); } } class B{ public: bool funB(); Template<class T> void bindBtoA((bool (B::*fun2)(), bool (T::*fun...
You can achieve this via the magic of std::function, which would be hidden inside class B and type-erases the function to be called, thereby giving you the generality you seek. Here's a fully-worked example: #include <iostream> #include <functional> class A { public: bool funA () { std::cout << "funA\n"; return tr...
70,355,938
70,356,755
Thread pools not working with large number of tasks
I am trying to create a thread pool with native C++ and I am using the code listings from the book "C++ Concurrency in Action". The problem I have is that when I submit more work items than the number of threads, not all the work items get done. In the simple example below, I am trying to submit the runMe() function 20...
When pool is destroyed at the end of main, your destructor sets done, making your worker threads exit. You should make the destructor (or possibly main, if you want to make this optional) wait for the queue to drain before setting the flag.
70,355,988
70,356,036
Is there a more idiomatic way to "insert or accumulate" into an unordered_map representing item counts?
Consider code like the following: #include <iostream> #include <unordered_map> std::unordered_map<char, int> get_letter_frequencies(const std::string& str) { std::unordered_map<char, int> freqs; for (char ch : str) { auto iter = freqs.find(ch); if (iter == freqs.end()) { freqs[ch] =...
Just do: for (char ch : str) { ++freqs[ch]; } Just accessing freqs[ch] will create the key-value pairing if it's missing, using the default constructor (for int, that makes 0), and returns a reference to the value (new or existing), so ++freqs[ch] will increment existing values, and both create and increment missi...
70,356,077
70,356,403
Overriding multiplication operator for different datatypes
I created the following class template<typename T, typename S> class Polar{ private: T rad; S phi; public: Polar(T r, S p) : rad{r}, phi{p} {} template<typename A, typename B> friend std::ostream& operator<<(std::ostream&, const Polar<A,B>&); And i want to override the multiplication function for differen...
Using std::common_type_t> may serve here. It gives you "the common type among all types T..., that is the type all T... can be implicitly converted to." [Demo] #include <iostream> // cout #include <ostream> #include <type_traits> // common_type_t template<typename T, typename S> class Polar { public: Polar(T r, ...
70,356,526
70,357,088
asio: how to pass object from one io context to another
I'm trying to understand a bit better how async asio works. I have the following code, where I'm calling async_read on a socket to read the next 10 bytes of data. struct SocketReader { void do_read_body() { asio::async_read(socket_, asio::buffer(msg_, 10), [this](asio::error_code...
I should be able to call from the socket completion handler, something like: asio::post(worker_io_context, [this]() {worker.queue.push_back(msg_)}); Sure. That way, I'm at least sure that the worker queue is not used concurently. But I'm not sure if I'm allowed to post from one io_context to the other, io_context...
70,357,080
70,357,357
Why template function with 'const' from left of parameter type is misbehaving against the rule of type deduction for pointer argument?
Consider this pseudo code for a type deduction case: template<typename T> void f(ParamType param); Call to function will be:f(expr); According to type deduction case where ParamType is not a reference, pointer, nor a universal reference (see S. Meyers "Effective Modern C++", p.14), but passed by value, to determine ty...
(Referencing the C++14 Standard) Your f_non_template_* functions aren't entirely correct. Since T is a template parameter, it'll behave as if it is a unique type: 14.5.6.2 Partial ordering of function templates (3) To produce the transformed template, for each type, non-type, or template template parameter (including ...
70,358,185
70,358,201
C++: use string& and unique_ptr<SomeClass>& for map<string, unique_ptr<SomeClass>>
I have following string& and unique_ptr& const FilePath& path; // given as parameter auto key = path.BaseName().value(); auto value = make_unique<SomeClass>(); I would like to use these in the following map map<string, unique_ptr<SomeClass>> myMap; When I do the following, myMap.emplace(key, value); I get this erro...
std::unique_ptr can't be copied, but only moved. You can use std::move to convert value to rvalue: myMap.emplace(key, std::move(value));
70,358,592
70,359,022
How to embed a DLL into a DLL?
I managed to create a program in C++ / Visual Studio 2010, 2017. And now I have to embed a DLL (B.dll) inside of another DLL (A.dll). I succeed in executing another program (C.exe) that uses A.dll. But I don't know how to embed a DLL into a DLL. Is it possible ? If it is possible, what should I do? I have solutions for...
If you truly want to embed B.dll inside of A.dll, you can define B.dll as a resource of A.dll via an .rc script in A.dll's project. Then you can use B.dll at runtime by first using (Find|Load|Lock)Resource() to access the bytes for B.dll's resource and writing them to a tempory file using (Create|Write)File() before t...
70,358,909
70,358,961
a C++ template question: choose the unexpect function
I am writing my list like the std::list so I have functions like this: template <typename _Tp> class list { public: // ... iterator insert(iterator __pos, const _Tp &__val) { // ... } template <typename _InputIter> iterator insert(iterator __pos, _InputIter __begin, _InputIter __end) { ...
Because the 2nd insert wins in overload resolution; given mylist.insert(it, 2, 20); the template parameter _InputIter could be deduced as int and then it's an exact match. On the other hand, the 3rd insert requires an implicit conversion from int to size_t. You can use std::input_iterator (since C++20) to specify that ...
70,359,086
70,363,014
Boost read_json is not working with wptree from std::wstring
I have a simple code which is not working and I don't really know why... here it's: std::wstring CDbFilterSerializer::DeserializeFromString(const std::wstring& jsonStr) { std::wistringstream ss{ jsonStr }; boost::property_tree::read_json(ss, m_root); return m_root.data(); } The problem here is that after c...
Yes. The assumptions are wrong. .data() returns the value at the root node, which is empty (since it's an object). You can print the entire m_tree to see: Live On Coliru #include <boost/property_tree/json_parser.hpp> #include <iostream> struct CDbFilterSerializer { std::wstring DeserializeFromString(const std::wst...
70,360,319
70,363,779
Measure time for function-runtime in tests with compiler optimization in c++
I want to measure the time a function I programmed takes when executed. While there are many threads on SO on how to measure time in c++, I did not find any that explains how to prevent the compiler optimization to clear away my function-call. So right now I do something like: bool testFunctionSpeed() { auto input ...
To prevent compiler from optimizing away function calls just make input and output of that function a volatile variable. Result is guaranteed to be computed and stored in volatile output variable on each loop run. While volatile input will prevent optimizer from precomputing value of your function in advance, if you do...
70,360,621
70,360,765
returning pointer to a function inline without typedef
I'm running into syntax errors with C++ where I have to return a pointer to a function inline. struct Note{} Observer.hpp class Observer { protected: void (*notify)(Note *note); // should this be *(*notify...)? public: void (*(*getNoteMethod)())(Note *note); }; Observer.cpp void (*Observer::ge...
The problem is the declaration syntax for the member function (which returns function pointer). Declare it as: class Observer { protected: void (*notify)(Note *note); public: void (*getNoteMethod())(Note *note); }; Better to declare the function pointer type in advance via using or typedef, whi...
70,360,837
70,361,032
Build incremental std::string
I try to build an std::string in the form of "start:Pdc1;Pdc2;Pdc3;" With following code I can build the repeated "Pdc" and the incremental string "123" but I'm unable to combine the two strings. #include <string> #include <algorithm> #include <iostream> #include <sstream> #include <iterator> #include <numeric> int ma...
std::strings can be concatenated via their operator+ (or +=) and integers can be converted via std::to_string: std::string res("start:"); for (int i=0;i<3;++i){ res += "Pdc" + std::to_string(i+1) + ";"; } std::cout << res << "\n"; If you like you can use an algorithm instead of the handwritten loop, but it will s...
70,361,181
70,361,392
Check if a string is a number without regex or try catch
I want to implement a simple is_number function that checks if it's an integer, float or an unsigned long int using this method: bool isNumber(const std::string& str) { size_t idx = 0; //Check if it's an integer std::stoi(str,&idx); if (idx == str.size()) return true; //Check if it's a flo...
std::stoi throws when it fails. Instead of using C i/o you can use C++ streams, try to read from the stream and check if there is something left in the stream: #include <string> #include <sstream> #include <iostream> enum Number {Float,Signed,Unsigned,NotANumber}; template <typename T> bool is_only_a(const std::stri...
70,361,272
70,365,618
Spiral matrix, i am getting extra elements while printing spiral matrix order. Don't know why?
// printing in spiral order matrix #include<iostream> using namespace std; int main(){ int n,m; cin>>n>>m; int arr[n][m]; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cin>>arr[i][j]; } } // print for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ ...
Suppose you have a below matrix. Let's dry run your code on below example. 1 2 3 4 5 6 7 8 9 10 11 12 Dry Run 1st for loop: prints 1 2 3 4 row_start=1,row_end=2,col_start=0,col_end=3 2nd for loop: prints 8 12 row_start=1,row_end=2,col_start=0,col_end=2 3rd for loop: prints 11 10 9 row_start=1,row_end=1,c...
70,361,687
70,361,948
Having Trouble with Inheritance in C++
I'm having a little trouble with inheritance. Main.cpp #include <iostream> #include "Shapeclass.h" using namespace std; int main() { int shapecount, shapetype[200],i,height[200], width[200]; string name; cout << "AREA CALULATOR"; cout << "Enter Your Name "; cin >> name; cout << "Enter the amo...
The Shape::calculate() method is declared as pure virtual: void virtual calculate() = 0; So, it must be overloaded in derived classes to have them considered by the compiler as concrete ones you'd able to call. In your case, the overloaded method would be responsible to determine the area of each shape according to it...
70,362,057
70,362,153
Allocation of incomplete type error in QT c++
I am trying to implement my very first project of a mediaplayer using QT c ++ , currently i have this issue where it says "error: allocation of incomplete type 'Ui::About_display'" .h #ifndef PLAYERFRAME_H #define PLAYERFRAME_H #include <QDialog> namespace Ui { class About_display; } class About_display : public QDi...
You are declaring class Ui::About_display; but defining class About_display. Make sure the class definition is in the Ui namespace: #ifndef PLAYERFRAME_H #define PLAYERFRAME_H #include <QDialog> namespace Ui { class About_display : public QDialog { Q_OBJECT public: explicit About_display(QWidget *parent = n...
70,362,195
70,376,503
GetAsyncKeyState() returns wrong value for VK_LCONTROL parameter when right alt is held down
I wonder if I did something incorrectly, or if this is a Windows bug. Here is my code: #include <iostream> #include <Windows.h> using namespace std; int main() { bool quit = false; while (!quit) { bool rightAltMod = GetAsyncKeyState(VK_RMENU); bool leftControlMod = GetAsyncKeyState...
I have found what causes the behavior - it is related to keyboard layout. The bug occurrs on Polish-programmers layout, after switching to EN-US layout it works fine. Well, still I'll need to solve the problem, but for that I'll create a separate question.
70,362,365
70,376,691
How to fix memory leak when passing object from C# COM library to a C++ application
I have a C++ MFC application which consumes C# COM wrapper. The issue is whenever I invoke a function inside wrapper, I am experiencing memory leak. Can anyone explain how to clean up the allocations that are made within the C# COM wrapper. Below code blocks mimic what I was trying to do, can anyone provide me the refe...
You should release memory if it's allocated and no-one else frees it, obviously. Here, the allocated memory is the .NET's string[] and uint[] which are represented as SAFEARRAY* in the native world. But, long story short: you can't really use structs as return type for COM methods. It's causes not only copy semantics i...
70,362,661
70,364,008
The program doesn't give any output on VS Code if I use 'const int ' and assign it a big value like 1e6
#include <bits/stdc++.h> using namespace std ; int main () { int n ; cin >> n ; int a [n] ; for ( int i = 0 ; i < n ; i++ ) { cin >> a [i] ; } const int N = 1e6 + 2 ; // This is where the problem is... bool check [N] ; for ( int i = 0 ; i < N ; i++ ) { check [i] == 0 ...
First, stop using VLA because it is NOT supported in c++ standard. Use vector or new instead. int *a = new int[n]; bool *check = new bool[N]; And use them just like a normal array. As for your problem, it is clearly caused by VLA with big size, and it will run perfectly once you switch to new or vector. Edit: However,...
70,362,713
70,362,794
map.erase(it) causes double free when it comes from map.find in template
I am trying to run the following: #include <algorithm> #include <iostream> #include <map> template <class T> auto first(T t){ return t.find(0); } void f(bool b){ std::map<int, int> map; map.insert({0, 0}); auto it = b ? first(map) : map.find(0); std::cout << "About to erase" << std::endl; map.erase(it); /...
template <class T> auto first(T t){ return t.find(0); } The first function is pass by value, so when t.find(0) is returned, the local variable t will be destroyed, and it will be initialized by a dangling iterator that points to the destroyed container. You should pass by reference: template <class T> auto first(T& ...
70,362,802
70,363,298
Using type in template class of derived template class
Try to implement the CRTP pattern. Therefore I created two template classes. With the first draft of only one template class PDerived everything is fine. But for my purpose in a bigger project I need two template classes. Which results in an error: All types of the PDerivced class are not found. But I have no idear why...
If you want to refer to some templated stuff of your base class, you have to give the compiler a hint how to find it. Change your line: myType myVariable; to TBase< TDerived<Derived> >::myType myVariable; The underlying problem is, that unqualified names are not resolved during this stage until the template is fully ...
70,362,895
70,363,394
Make a function that autodetects when unique
I need to have a function in c++ that gets an element from a vector of strings as soon as the input is unique. For example, my vector contains {"DELETE", "HELP", "GO FORWARD", "GO BACKWARDS"}. If my input is then "H", the function should output "HELP" If the input is "H 55", it should ignore the 55 and still output "HE...
Make a function that autodetects when unique One possible way of doing this is as shown below: #include <iostream> #include <vector> #include <string> std::string checkUnique(const std::string& searchString, const std::vector<std::string>& inputVector) { int count = 0; std::string foundString; for(const s...
70,362,925
70,363,616
Downcasting pointer to pointer
I'm learning polymorphism in C++ and I can't downcast a pointer to a pointer. I have a class Base and a class Derived that extends Base. And I want to do a pool of Derived objects using a function Base **derivedFactory(size_t size). I tried doing Base** array = new Derived*[size]; but the compiler says that it can't co...
There are multiple fundamental problems with the shown code. Base* array = new Derived[size]; This creates an array of Derived objects. This kind of an array in C++ is represented by a pointer to the first value in array. In this case this would be a Derived *, which is what you get from new. It is valid in C++ to ...
70,363,432
70,377,641
Unresolved external when trying to link openSSL in a VMWare shared folder
I have built openSSL and put the static libraries under version control (shared objects are not an option). When I try to build the project while it resides on a shared folder of a vmware Ubuntu VM, it throws me all kinds of unresolved externals, which seemingly stem from 'being unable to find libcrypto.a'. Strangely e...
I have not found the reason behind the original issue, but I have found a way around it. Using the GNU Buildtools, you can combine the two openSSL libraries into one static library and link that instead. For this purpose, I used this link for the basic instructions. My openSSL build script (in Python) therefor now has ...
70,363,508
70,363,962
How to iterate through a directory_iterator in parallel?
std::filesystem::directory_iterator is a LegacyInputIterator and apparently it can't be used in a parallel std::for_each I can iterate through the directory_iterator, get the items, place them in a vector and use that vector for parallel iteration. Can the above step be omitted? Is there a way to iterate through a dire...
directory_iterator is an input iterator, which means it generates values during the traversal. Furthermore, multiple traversals over the same directory may produce different sequences of values (both in terms of order and values themselves), which means the traversal is not restartable. For parallel algorithms this mea...
70,363,513
70,406,269
Multiple prerequisites in partially ordered mock calls in googletest
I was reading partially ordered calls for googletest here and I understoond how their example works. So we can use: using ::testing::Sequence; ... Sequence s1, s2; EXPECT_CALL(foo, A()) .InSequence(s1, s2); EXPECT_CALL(bar, B()) .InSequence(s1); EXPECT_CALL(bar, C()) .InSequence(s2); EXPECT...
You can use After method to expect some call after certain other call(s). https://google.github.io/googletest/reference/mocking.html#EXPECT_CALL.After So in your case it will be like this: Mocked mock; Sequence s1, s2; EXPECT_CALL(mock, A).InSequence(s1, s2); Expectation exp_b = EXPECT_CALL(mock, B).InSequence(s1); EXP...
70,363,669
70,365,845
CMake fatal error: CMakeFiles/<path>.dir/main.cpp.d: No such file or directory
I am trying to compile a simple C++ program with CMake on Ubuntu 18.04, but all of my CMake projects fails when I run the make command. Below is a minimum working example. The directory structure looks like this: - project directory |-build |-main.cpp |-CMakeLists.txt main.cpp int main(void) { return 0; } CMakeLi...
Despite the error message about absent .d file seems to be internal to CMake (such files are used for collect header dependencies generated by the compiler), its usual reason is specifying some output-controlling compiler options in the CMakeLists.txt. In your case it is -o option which damages the command line generat...
70,363,847
70,365,877
Why doesn't std::ranges::upper_bound accept heterogenous comparing?
This code works and returns an iterator to foo{5} from the vector: struct foo { int value; }; auto main() -> int { auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}}; std::ranges::sort(ints, {}, &foo::value); auto it = std::upper_bound( ints.begin(), ints.end(), ...
I suspect it may be intentional since the "standard" way would be to use the projection like so: This is basically the motivation for projections. From N4128: The Adobe Source Libraries (ASL)[1] pioneered the use of “projections” to make the algorithms more powerful and expressive by increasing interface symmetry. S...
70,363,885
70,364,183
How to declare manually uint512_t in boost?
i wanna declare this: uint512_t qwe = 0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E; but c++ don't think so(vscode hints too): integer constant is too large for its type and its print like: x: 0x514c0ce9dae23b7e can you help me please?
You can use user-defined literals to initialize Boost.Multiprecision numbers, for example: uint512_t qwe = 0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E_cppui512; Alternatively, you could use a constructor from string, but this is less efficient as it will require run time parsing. It can be ...
70,364,283
70,364,802
Fast way of copying multidimensional array in C++
I have multidimensional array of Struct in C++. #define TOTALSTREAMS 5 #define SEQUENCEHISTORY 20 #define PROCESSINGSIZE 5 #define OVERLAPPINGSIZE 1 #define X_GRID 100//X_GRID and Y_GRID represents the whole building in CM #define Y_GRID 70 typedef struct { uint64_t localid; uint64_t globalid; int posture...
The code you have posted does not copy the arrays content properly. The assignment Processed_Array[i][j][k][m].people.push_back(History_host[i][j][k][m].people.back()); will not copy the arrays content, but only add the last element of the source array several times. You should use the index n to access the appropriat...
70,364,332
70,365,535
lock of openmp seems not to work when dong summation
I am new to openMP and mutli-threading. I need to do some summation work and I know that when writing to the shared variable, it need to use lock like omp_lock_t. But when I do so, the result still goes wrong. The code is: #include <omp.h> #include <cstdio> struct simu { public: simu() : data{ nullptr } { ...
A lock protects the actual data item from simultaneous writes. Your lock is in the object that points at the item, so this is pointless. You need to let you data point to an object that contains a lock.
70,364,855
70,365,075
operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer typeC/C++
In a lambda function, instead of this, I was trying to use weak_ptr to access all member function and variable, but I'm getting this error: operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer type
std::weak_ptr<T> by design safely refers to an object which may or may not still exist. It does not offer operator-> or operator* since you have to make sure the object still exists before you can try to access it. To access an object referred to by a std::weak_ptr you first call lock() which returns a std::shared_ptr....
70,364,977
70,367,541
Understanding the reasoning between copy/move constructors and operators
I am trying to get the grasp of rvalue references and move semantics with a simple self-made example but I can't understand a specific part. I have created the following class: class A { public: A(int a) { cout << "Def constructor" << endl; } A(const A& var) { cout << "Copy constructor" << ...
Congratulations, you found a core issue of C++! There are still a lot of discussions around the behavior you see with your example code. There are suggestions like: A&& helper_alt(A a) { std::cout << ".." << std::endl; return std::move(a); } This will do what you want, simply use the move assignment but emits ...
70,365,084
70,365,145
How to Ensure proper initialization of Non Static Data Members within a Class Template in C++
I am working with templates in C++ and want to know how can we properly(value) initialize the non static data members in a class template. For example, consider the following snippet: template<typename T> class MyVector { T x; // x has undefined value for a built in type }; Now i know that the data member x has ga...
There are different way to do what you want depending upon which C++ version you're using. This is explained in more detail below: C++11 template<typename T> class MyVector { T x{}; }; Pre C++11 template<typename T> class MyVector { T x; MyVector(): x() { } }; C++11 From C++11 and onwards, you ca...
70,365,696
70,365,734
How do i set x to be a negative value if x is positive, and if x is positive how do i set it to be negative. c++
I am making an AI/algorithm to find a checker pattern in a 2x2 square. I need them to be negative for hidden_1 and hidden_3, but positive for the other 2. #include <iostream> #include <math.h> #include <string.h> using namespace std; int main (){ int x; int y; int a; int b; int x1 = -x; ...
You initialised x1, y1, a1, b1 with negatives of variables that weren't read. Try declare them after you read x, y, a, b. #include <iostream> #include <math.h> #include <string.h> using namespace std; int main () { int x; int y; int a; int b; cout << "Is there a square in the top left?\n1 for Yes/-1 for ...
70,365,812
70,366,629
returning a std::string from a variant which can hold std::string or double
I have the following code: #include <variant> #include <string> #include <iostream> using Variant = std::variant<double, std::string>; // helper type for the visitor template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; // explicit deduction guide (not needed as of C++20) template<class... Ts>...
You can return a proxy object. (this is like your unique_ptr method) struct view_as_string{ view_as_string(const std::variant<double, std::string>& v){ auto s = std::get_if<std::string>(&v); if(s) ref = s; else temp = std::to_string(std::get<double>(v)); } const std::string& data(){r...
70,365,959
70,375,654
Using CMake, how to rebuild Swig wrapper when header file changes
I have a C++ library (called myfibo) and I want to make a python binding modue (called myfibopy) using CMake and Swig. The first build works perfectly. But if I rename an exposed C++ function, the python module doesn't build anymore because the Swig wrapper (PYTHON_wrap.cxx) is not regenerated. I have already tried usi...
Did you try: USE_SWIG_DEPENDENCIES New in version 3.20. If set to TRUE, implicit dependencies are generated by the swig tool itself. This property is only meaningful for Makefile, Ninja, Xcode, and Visual Studio (Visual Studio 11 2012 and above) generators. Default value is FALSE. New in version 3.21: Added the suppor...
70,366,126
70,385,516
inline function with empty parameter
I'm studying on Boost library. Can someone help me understand below code. /*! \fn ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest) \brief Equivalent of <code>std::uninitialized_copy</code> but with explicit specification of value type. */ template<class InputIter...
The short answer is: this function puts values in memory that has already been allocated, but not yet initialized. That's also why this particular allocator_construct implementation does not use the allocator parameter, but others probably do. For an explanation of why this is useful, consider std::vector, which has bo...
70,366,415
70,366,870
How does Visual studio know which library to link if both static and dynamic libraries exist?
When linking with external libraries, if both static and dynamic libraries exist in the same folder, which library will Visual Studio link? As an example, for the boost filesystem library, the x64 static library file is libboost_filesystem-vc142-mt-x64-1_77.lib and the x64 dynamic library files are boost_filesystem-vc1...
TLDR: Yes, in case of boost choise is based on selected runtime in the project options (/MT or /ST). Long version: =) Boost library has an autolinking feature. This mechanism is defined in the header file config/auto_link.hpp. There boost is trying to determine full lib name basing on selected build architecture, tools...
70,366,648
70,366,769
How to recursively split a linked list after k nodes in C++?
I have an ordinary linked list with: struct node{ int info; node* next; }; I need to write a recursive function that splits in 2 a given linked list passed by reference after k elements, leaving the first k nodes in this list and returning the second list with the rest of the nodes. My iterative solutions looks li...
You currently have node* split(node*&L, int k){ node* M; node* head = L; while(k>1){ head=head->next; k--; } M = head->next; head->next = NULL; return M; } You want something like node* split(node*&L, int k){ node* M; node* head = splitPoint(L, k); M = head->next; head->nex...
70,366,716
70,366,878
How can I call a function from an array of functions via its index?
A beginner's question I couldn't find answered online, likely because I don't know the terminology. I want to call one of a list of procedures based on a computed index value. That is, given a '1', invoke firstProc(), '2' invokes secondProc() and so on. All the procedures are void functions with no arguments. I can imp...
There are two equivalent ways to do what you want. The explanation is given as comments in the code snippets. Method 1 #include <iostream> void foo() { std::cout << "Hello"; } void foo2() { std::cout << " wolrd!"; } int main() { void (*a)() = foo;// a is a pointer to a function that takes n...
70,366,907
70,369,699
I'm trying to sum up the numbers in a given array, using recursion , tried this code but it isn't working. Why?
#include <iostream> using namespace std; int sumByRecursion( int arr[]) { int sum = 0; int n = sizeof(arr)/sizeof(arr[0]); //n is the size of the array if (n == 0) { return sum; } else { n -= 1; for (int i=0;i=n;++i){ ar...
A (sadly) common mistake: int sumByRecursion( int arr[] ) { // What do you think ^^^^^ this is? int n = sizeof(arr)/sizeof(arr[0]); // ^^^^^^^^^^^ Sorry, too late. // ... } As already noted in the comment section Inside the function the parameter arr has decayed to type int* and knows nothing abou...
70,367,073
70,367,606
How to define a single copy constructor for template classes?
#include <iostream> template <typename T> class Matrix { public: Matrix() = default; template <typename U> Matrix(const Matrix<U>& matrix) { std::cout << "Copying internal data..." << std::endl; } // Matrix(const Matrix<T>& matrix) { // std::cout << "Copying internal data..." << s...
But even if I don't have a copy constructor, I have a constructor that accepts a matrix of any type. Why is it looking specifically for the copy constructor? In overload resolution it is not find the best usable function. Instead, it is find the best function and try to use it. If it can't because of access restricti...
70,367,406
70,367,506
Generically return a optional<T> / nullopt
I am trying to implement a generic find_if_opt method which is virtually identical to std::ranges::find_if (however it return an Optional) So far this is my implementation. template <typename X, typename Z> inline auto find_if_opt(const X& ds, const Z& fn) { const auto it = ranges::find_if(ds, fn); ...
You can use ranges::range_value_t to get value_type of X template <typename X, typename Z> inline std::optional<std::ranges::range_value_t<X>> find_if_opt(const X& ds, const Z& fn) { const auto it = std::ranges::find_if(ds, fn); if (it != end(ds)) { return *it; } return {}; } Or using std::ite...
70,367,965
70,368,833
how to know if a http request is partial and how to fully parse it before generating a response c++
I am working on a C++ project where i listen on sockets and generate HTTP responses based on the requests i get from my clients on my fds, in short i use my browser to send a request, i end up getting the raw request, i parse it and generate the corresponding http response. However in the case of large POST requests, u...
how can i figure out just from this whether or not am getting a partial request or just a faulty request (I need to generate a 400 error in the case of a request that says it has X content-length but the body size is different) The body size is, by definition, the size of the Content-Length field. Any bytes that you ...
70,368,012
70,368,097
Deduced type with 'auto &&' as function return type
In the following snippet, the function B::f() is a "wrapper" around the function A::f(). But I assume that A::f() return type is an "opaque" type which I don't know if it has a value or reference semantics. So I cannot use auto or const auto & as return type for B::f(). I thought that auto && would do the trick, but it...
Pretty sure what you are looking for is decltype(auto). This will return by value if the expression in the return statement returns by value, and it will return by reference if the expression in the return statement returns by reference. That would give you decltype(auto) f() const { return a.f(); }
70,368,103
70,370,811
How to Rotate a Quad
I'm trying to make a quad rotate around its center. I am using glm::rotate() and setting the quad to rotate on the z axis. However when I do this it gives this weird effect. The quad stretches and warps. It almost looks 3d but since I am rotating it around the z axis that shouldn't happen right? Here's relevant code fo...
Without you showing the graphical output it is hard to say. Your first issue is, you are not rotating around the center, to rotate by the center you must, offset the quad so that its center is at 0,0. then rotate, then offset back to the original position, but you have this line: gl_Position = model * vec4(aPos.x + xMo...
70,369,048
70,369,111
Where are the functions inside of structs stored in memory?
Let's say I have a struct like this: struct 64BitStruct { uint64_t value; void SomeFunction(bool enable); bool SomeOtherFunction(); }; sizeof(64BitStruct) returns 8 bytes, which is 64 bits. I assume those 64bits are the value variable in the struct, but then where are the functions stored?
Member functions are common functions of all objects of the structure type. So they are stored separately from objects. The size of the structure in your example is in fact the size of its data member. If a structure has virtual functions then it implicitly includes a pointer to the table of virtual function pointers a...
70,369,264
70,369,524
Thread 1: Breakpoint 1.1(1)
I'm trying to do a small project and I came over a breakpoint issue. I had it previously on char dirname[256] when I had a char holding it. However, after I removed the char it changed the breakpoint to the cout, which I never had before. I fairly new in c++ somewhat in-depth explanations would be nice. Thank you. Code...
I think your problem is related to using XCode editor rather than coding. I recommend reading this article.
70,369,847
70,371,171
Is there a way to programmatically find the current used GPU (C, C++)?
In the case of CPUs, the (linux specific) sys calls getcpu() or sched_getcpu() can be used inside a program to obtain the ID of the core executing them. For example, in the case of a 4 processors system, the logical index returned by the mentionned calls makes it possible to deduce which one of the 4 CPUs is being used...
C++ has no concept of a GPU. You got a great comment pointing you to the right direction of getting some GPU info using OpenGL, I'm sure there are other cross platform libraries as well. Take a look at the source code of neofetch which is a command-line system info tool which, among other things, gets your GPU(s). It u...
70,370,506
70,511,481
OpenCV threshold color image (by brightness, not per channel)
openCV seems to be doing per-channel threshold if I use cv::threshold on color image. I use it to get rid of pixels that are not bright enough (cv::THRESH_TOZERO), and then overlay that (cv::add) on other image. Works almost OK, but the problem is that it obviously works per-channel, so the colors get sometimes distort...
As suggested in the comments, the solution is to convert to grayscale, do the threshold which gives you a mask, and then do bitwise_and to only keep the pixels you want. Like this: cv::UMat mask; cv::cvtColor(img, mask, cv::COLOR_BGR2GRAY); cv::threshold(mask, mask, thres...
70,370,782
70,686,551
Can't set keep_alive to socket in asio
I'm trying to create a ServerSocket as a singleton. Here's the code: ServerSocket.h #pragma once #include <asio.hpp> #include <iostream> #include <optional> using asio::ip::tcp; class ServerSocket { public: ServerSocket(ServerSocket& otherSingleton) = delete; void operator= (const ServerSocket& copySingleto...
@Vasile, your problem, as @dewaffed told you, is that you are setting the options before the socket has been opened. I don't know what you are trying to do but I can see that you creating a new socket, which is not open, and setting the properties, that's the problem. The correct way is: Create the Socket Accept the n...
70,370,912
70,370,940
Remove a Chunk of Items from a Vector?
I have a vector full of words and I am trying to erase a chunk of that vector at a specified beginning and end. For example: #include <string> #include <vector> int main() { std::vector<std::string> words = { "The", "Quick", "Brown", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" }; remove_chunk(words, 1, 2); } ...
Use vector::erase: words.erase(words.begin(), words.begin() + 2); Note: Second iterator provided is words.begin() + 2 instead of words.begin() + 1 because STL uses [begin, end).
70,370,922
70,370,993
C++ Using sizeof() to determine size of an Octree
Let's say Octree() is a container with Elements of type double. Can I use sizeof(Octree) to determine how much memory in bytes is taken up by my octree? Sizeof() should change if I change the resolution/depth of my octree - which does not seem to be the case when I test it. Is there a way I could determine the dynamica...
No. sizeof returns the size of the object. Which is the size of the type of the object. Which remains constant through the entire program. sizeof does not return the amount of memory that member functions of the object have allocated dynamically, and it cannot be overloaded to do so. Is there a way I could determine t...
70,371,091
70,371,265
Silencing stdout/stderr
What is a C equivalent to this C++ answer for temporarily silencing output to cout/cerr and then restoring it? How to silence and restore stderr/stdout? (Need this to silence noise from 3rd party library that I am calling, and to restore after the call.)
This is a terrible hack, but should work: #include <stdio.h> #include <unistd.h> int suppress_stdout(void) { fflush(stdout); int fd = dup(STDOUT_FILENO); freopen("/dev/null", "w", stdout); return fd; } void restore_stdout(int fd) { fflush(stdout); dup2(fd, fileno(stdout)); close(fd); } i...
70,371,170
70,371,294
OpenMP parallel for loop exceptions
I'm quite new to using OpenMP and to stackoverflow, so apologies if this is a stupid question! I'm trying to set up a large 2d vector to test my CUDA program. The creation for these large vectors is done by looping through all the values of the given dimensions (stored in their own vectors) and creating a row in a new ...
Your problem is with the line `final2.push_back(temp)'. You have multiple threads pushing back into the same vector. That is not possible. Create the vector before the loop, and then write to explicit locations in it. In general, try to avoid push_back as much as possible because it has performance problems. If you kno...
70,371,484
70,371,629
FAST way to determine if first n bits of byte array are "0"
I have a function that computes the checkLeadingZeroBits as follows: typedef std::array<uint8_t, 32> SHA256Hash; bool checkLeadingZeroBits(SHA256Hash& hash, unsigned int challengeSize) { int bytes = challengeSize / 8; const uint8_t * a = hash.data(); if (bytes == 0) { return a[0]>>(8-challengeSize...
As written, no. A raw byte array can't be scanned at the bit level faster than a byte by byte comparison operation. However, if you're targeting a platform with a count leading zeros instruction or equivalent, you can speed up the process by checking blocks the size of a native processor word (32 bit for x86/ARM, 64 bi...
70,371,915
70,385,570
FLTK: Clearing a graph when drawing another
I wrote a simple FLTK program to draw a circle when clicking on the "Draw Circle" button and to draw a line when clicking on the "Draw Line" button. I supposed to have only one graph. But I got two graphs in the panel. I want only one showing and the other disappearing. The following is the code: #include <FL/Fl.H> #in...
There are several issues that need to be fixed in your program, but first of all using the draw() method as you did is basically correct. However, using fl_overlay_clear(); is useless, you can remove it. My solution: your widget doesn't have a solid background (boxtype), i.e. your draw method draws over the background ...
70,373,555
70,374,564
While template deduction, is it possible to detect if a consteval function could be run
Let's say we have a consteval function or a trivial struct with consteval construnctor, which only accept some of the values: struct A { consteval A(int a) { // compile error if a < 0 if (a < 0) throw "error"; } }; Is there any way to detect if a non-type template parameter of i...
Since a call to a constexpr (or consteval) function that throws is not a constant expression, you can detect this: template<int I> concept accepted_by_A= requires() {typename std::type_identity_t<int[(A(I),1)]>;}; static_assert(accepted_by_A<1>); static_assert(!accepted_by_A<-1>); It's also possible to use SFINAE (...
70,373,615
70,389,342
cmake find_package: why cannot find some components in boost
Find_package command is a nightmare to me. I am trying to include some specified components in boost into my project. Some components could not be found with find_package command for different error. Can anyone help to explain the error reported? case 1: cmake_minimum_required(VERSION 3.15) project(tryBoost) set(CMAKE...
Please use below CMakeList.txt for reference. cmake_minimum_required(VERSION 3.15) project(tryBoost) set(CMAKE_CXX_STANDARD 14) #set(Boost_DEBUG ON) set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_MULTITHREADED ON) set(BOOST_ROOT "/home/yubo/boost_1_78_0") add_executable(tryBoost main.cpp) set(Boost_NO_BOOST_CMAKE FA...
70,373,631
70,373,699
when alignof operator used in struct does it affect sizeof
struct s11 { alignas(16) char s; int i; }; does alignas(n) X x mean it would allocate n bytes to hold a X, when X is actually much smaller than n bytes, the rest memory would be all 0s? when s11.s is in memory 0x0, does that mean s11.i would be at 0x10? However, the following pdiff is 0x4 s11 o; ptrdiff_t ...
No, it means the starting address of the member s must be aligned on a 16-byte boundary. Probably in the case of it being the first member of a struct, this will result in the struct itself adopting that alignment and not affecting the size. No, there is no specified alignment pertaining to the member i, so normal a...
70,373,694
70,375,191
cin: No Operator Found Which Takes A Left-Hand Operand
I'm trying to get two space-separated variables and running into this error, as well as [no operator ">>" matches these operands] and [syntax error: ">>"]. #include <iostream> #include <string> #include <vector> using namespace std; ... void player(char array[][ROWS_AND_COLUMNS], char letter) { bool element_occup...
inputValidate() returns a temporary int, an rvalue, which operator>> can't read into. It expects an lvalue instead (ie, a variable with a name). That is why you are getting errors on the cin >> inputValidate(...) statement. Even if the statement could compile, it simply doesn't make sense to use. inputValidate() does i...
70,374,120
70,374,240
Getting subscript out of range after vector resize
I have a 2D vector of string. It has some data in it already - generally speaking all rows (should) have the same number of columns. I am looking to resize the matrix by increasing the number of columns by 1. std::vector<std::vector<std::string>> completeMatrix; matrixRowNum = completeMatrix.size(); matrixColumnNum = c...
Your resize call only affects new rows. All existing rows are unaffected. But you're not even adding rows! You called resize and passed the same value as the current size. So nothing will happen. It seems you have a misunderstanding of how much magic and mind-reading happens inside this call. You will need to itera...
70,375,007
70,375,126
What is "using namespace::std" in C++
I am reading some code snippets from others and I find a line: using namespace::std; I suspect its purpose is using namespace std;, with some typos. But to my surprise the compiler accepts this code without any complaint. I build with: $ g++ --version g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0 $ /usr/bin/g++ ${SRC} -std...
using namespace::std is the same as using namespace std; The :: symbol is the scope resolution operator. When used without a scope name before it , it refers to the global namespace. This means that std is a top level namespace, and is not enclosed in another. The spaces before and after the :: are optional in this cas...
70,375,087
70,375,700
did const int& pass a reference or a copy
For example, void func(const int& a); int main() { int b=1; func(b*2); } If the const int& will pass a reference, how can b*2 be a reference? So it means it only pass a copy of b*2 to func()? But if so, did func(b) really pass a reference of b? Am I right?
It's simple: int b = 1; Here, b is an lvalue. so when you write func( b ) then you are passing an lvalue to the func. And it works since func can take an lvalue by reference. But: func( b*2 ); Here, b*2 is a prvalue (which is under the rvalue category) and when you write func( b*2 ); then you are passing an rvalue to...
70,375,285
70,395,973
Condition Variable wait_until timeout_time in the past?
If I call std::condition_variable::wait_until and pass a timeout_time that is in the past, is it guaranteed to return std::cv_status::timeout? Or is there a short window in which a notification could be delivered that results in the condition variable being unblocked the "normal" way with std::cv_status::no_timeout? Co...
TL;DR: (i) the return value of std::condition_variable::wait_until() does not appear to be guaranteed by C++ under the conditions specified, though the analogous pthreads function does guarantee that a timeout will be signaled under those conditions; (ii) even in the case where the timeout time is already past, the met...
70,375,360
70,375,564
Explicit instantiantion of template member in cpp file doesn't generate symbol (i.e. link error)
Take the following example: // A.h class A { public: int v = 2; template <typename T> int f(T t); }; // A.cpp #include "A.h" template <typename T> int A::f(T t) { return v + t; } template <> int A::f<int>(int t); // main.cpp #include <stdio.h> #include "A.h" int main() { A a; printf("%d\n...
I think @JaMiT got the answer. template <> int A::f<int>(int t) { // full specialization of templated thing } Is a full specialization. template <> int A::f<int>(int t); Is a declaration that such a specialization exists, but doesn't provide the definition. The form you want is template int A::f<int>(int t); Wh...
70,376,693
70,376,967
C++ Interface, What's the best way to not duplicate code
I have this problem: I have an Event Manager that call the event function do() Event *p; //p takes it values from an Event Queue p->do() Some Events have two attributes Object a and b class EventX : public Event { public : EventX(); void do(){actionX(a, b)} private : Object a; Obj...
You can have extra layer with another interface struct EventAB : Event { void do() final { if (bothSide) action(b, a); action(a, b); } virtual void action(Object&, Object&) = 0; /*...*/ private: Object a; Object b; bool bothSide = false; }; And then class EventX : public EventAB { public: voi...
70,376,909
70,376,951
Getting an unusual output for a simple constructor program in C++
I am a novice at C++ and have encountered an unusual error while trying to learn about constructors. Here I am trying to make x = 5 and y = 6, then have the program print them out to the screen. This is my program -> #include <iostream> using namespace std; class class1 { public: int x; int y; ...
This : class1(int x, int y) { x = x; y = y; } is called shadowing. A variable shadows another one of same name. x = x just assigns the value of the parameter x to itself and the members are left uninitialized. The compiler has no way to know that you want one x to be the member and the other be ...
70,377,208
70,377,711
Different amount of template variables
I have to implement a class depending on std::multiset. The idea is that when two multisets get into the same "view", my class needs to sort them, make operators and iterators, etc., but I'm stuck on basically the first step. The problem is that I'd need to create the same class, just with different amount of template ...
A pretty simple way to solve the issue would be providing a default argument for the comparator: template <typename T, typename C = std::less<T>> class multisets_merge_view { /* ... */ }; Since C++17 you can rely on class template argument deduction, which can simplify usage of your template class pretty much – you do...
70,377,521
70,377,998
Default template parameter cannot be used inside another template parameter?
I have a class template with a default value for the template parameter: template<typename T = int> class DefaultType : private std::array<T, 5> { }; and since c++17 this can be instantiated like a normal class DefaultType obj; // equivalent to `DefaultType<>` The same thing cannot be done if I use this type as an ar...
This: DefaultType obj; uses CTAD (class template argument deduction) which is available since C++17 and only in certain contexts: any declaration that specifies initialization of a variable and variable template new-expressions function-style cast expressions the type of a non-type template parameter: To instanti...
70,378,204
70,428,990
How to catch `abi::__forced_unwind` while keeping UBSan happy?
Like libstdc++, we're checking in some places for abi::__forced_unwind, and just re-throw it instead of taking some other action. Like libstdc++, we catch it by reference: try { /* ... */ } catch (abi::__forced_unwind&) { throw; } catch (...) { /* ... */ } But if we actually pthread_cancel to exercise the...
This is a bug in the forced unwinding implementation, which has been filed in the GCC Bugzilla as ticket #100415. (Arguably it should be fixed in GCC itself, as you’re not creating an actual reference binding, only matching on the exception type.) While it is being fixed, you can decorate the function containing the c...
70,378,431
70,384,089
Reducing duplicate code for function implementation
Unfortunately, I get stuck with a problem with duplicated source code. Here is a small example to illustrate my problem: class cPlayer { public: struct Properties { std::vector<cStreet*> Streets; std::vector<cHouse*> Houses; std::vector<cComputer*> Computers; std::vector...
One possible way of doing this is using templates and std::map. In particular, by making the buy member function to be a member function template as shown below: Method 1 Step 1 Creating a std::map std::map<std::type_index, void*> myMap{{typeid(cStreet*), &m_Properties.Streets}, ...
70,378,650
70,378,897
Does forward declaration fully remove the need for any #including for pointer types?
Let's assume that we have a source file A.cpp where we forward declare a type ClassB, and then we keep using pointers to ClassB without ever #including file B.cpp (where ClassB is defined); And in B.cpp we forward declare ClassA and use a pointer to it without ever #including A.cpp (where ClassA is defined), then is th...
This questions is really too general to answer properly, but here's my 2 cents. In general, as long as you only refer to a class as a pointer to it, compilation will work. eg this example compiles fine: class B; int main() { B * tst; return 0; } However, as soon as you try to actually instantiate a the pointe...
70,379,103
70,379,163
char pointer and static_cast in c++ code related to virtualalloc
I was searching for some code related to VirtualAlloc and came across this piece of code: #include<windows.h> #include<iostream> using namespace std; int main() { size_t in_num_of_bytes,i; cout<<"Please enter the number of bytes you want to allocate:"; cin>>in_num_of_bytes; LP...
Simpler example: void* allocate_some_stuff(){ return new char[42]; } int main() { void* ptr = allocate_some_stuff(); char* cptr = ptr; } Because C++ does not allow implicit conversion from void* to char* it causes the error: <source>:9:18: error: invalid conversion from 'void*' to 'char*' [-fpermissive] ...
70,379,337
70,380,745
Template function ignores members from inherited class
I am trying to write a program that compares some Shapes by their area, Shape being the base class. The program has 2 other classes that are derived from the Shape class. This is how I defined them: class Shape { protected: string color; public: Shape(); Shape(string); virtual double Perimeter(); vi...
You are trying to use polymorphism here. Unfortunately polymorphism in C++ works well with pointers or references but not with plain objects because of slicing (thank to @Jarod42 for that reference). And as references cannot be assigned to (you instead assign to the ref-ed object) you cannot use them in containers nor ...
70,379,799
70,379,938
How to make a notched matrix?
I have a little problem, I don't quite understand how to make a toothed (a notched?) matrix in C++. The matrix should be like this (with 4 columns and 6 rows): But I keep getting a matrix in the form of a triangle, i.e. no repeating rows are displayed. How can I fix it? I'm attaching a piece of code, but I don't think...
I'm assuming that the first row has 1 column, second has 2 columns, etc., up to a maximum of M columns. In which case, the below will work. size_t N = 6; size_t M = 4; double **matrix = new double*[N]; for (size_t i = 0; i < N; i++) { size_t cols = std::min( i + 1, M ); // determine the correct number of cols for ...
70,380,645
70,380,944
boost asio, post() to main thread?
I am using boost::asio as a general async backend. I have multiple threads runing one io_context But I encounter certain operations that are binded to specific thread. For example, imshow of opencv must be called from main thread. What is the best way to post to main thread, or any specific thread in general? (without ...
You can't do it through asio. You can use message queue you read in main thread (like Windows messages) or other specific thread.
70,381,179
70,381,331
How to Add Element into a std::vector using std::any
I am working on a C++17 project and there i am using std::any. A minimal reproducible example is given below for reference explaining what i want to achieve. #include <any> #include <vector> #include <iostream> int main() { std::vector<int> vec{1,2,3}; std::any anything = vec; // anything.push_back...
we are using push_back on an rvalue No, that's not the problem. any stores a copy of what it is given. It doesn't reference some other object. It creates an object from what it is given. So even if you get a reference to the object in the any, it wouldn't be a reference to vec itself. If you want to store a reference...
70,381,528
70,381,728
How To complete string from another string
#include<iostream> #include<string> using namespace std; int main () { string str; string str2; int count; cin>>count; while(count!=0) { cin>>str; cin>>str2; int l=str2.length()-1; cout<<str[0]; if(str.length()==str2.length()) { for(int x=1...
A straightforward approach can look the following way std::string::size_type i = 0; for ( auto n = std::min( str.size(), str2.size() ); i < n; i++ ) { std::cout << str[i] << str2[i]; } while ( i < str.size() ) { std::cout << str[i++]; } while ( i < str2.size() ) { std::cout << str2[i++]; } Here is a...
70,382,001
70,384,139
How to marshal through py::dict in C++ passing from pybind11
I try to pass a dictionary (unordered_map) structure from python to C++ through pybind11. On the python side I am trying to do: v1 = { 1:3.0, 2:4.0} v2 = { 7:13.0, 8:14.0, 15:22.0} data={'ab':v1, 'bz':v2} cpp_run(data) On the C++ side, I have #include <iostream> #include <pybind11/pybind11.h> #include <pybind11/numpy...
I sort of solve this by using py::cast on the C++ side: void cpp_run(const py::dict& results) { for (auto it : results) { const std::string& name = py::cast<const std::string>(it.first); std::unordered_map<int, double>& a_map = py::cast <std::unordered_map<int, double> >(it.second); for (au...