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
65,269,741
65,270,514
Simpler syntax to invoke a template functor
I have a functor that looks like this: struct Functor { template<typename T, typename... Args> static void func( Args&&... args ); }; I need to pass it as a template parameter to a function and this function invokes it: template<typename F> void fn() { F::template func<int>(1, 2, 3); } fn<Functor>(); Having to wr...
Another alternative is to let all template deducible, something like: template <typename> struct tag{}; struct Functor { template<typename T, typename... Args> static void func(tag<T>, Args&&... args ); }; And so, usage is similar to: template<typename F> void fn() { F::func(tag<int>{}, 1, 2, 3); } fn<Functor>()...
65,269,753
65,269,824
How to read data from binary files properly in C++ till the last data?
I recently learnt that to read properly from a text file we use while(file>>var1>>var2){ //do stuff with data } instead of while(file){ file>>var1>>var2; //do stuff with data } because the latter performs one extra read even after last data item is read and on the next read it is able to read the eof, so if ...
It's the same as your text example, the test on the file must be after the read not before. for (;;) { obj1.read_binary(file); if (!file) // did the previous read fail? break; // if so quit the loop records.push_back(obj1); }
65,269,809
65,270,487
Acess and modify a C++ vector containing objects with different variable types
Im just starting to learn C++ and i would like to acess and modify a vector of objects that have different variable types. I have only been able to create the vector, but cant do anything with it. How can i acess and modify it? This is the code i have created so far: class Person { private: string name; int id; public:...
To access objects stored in the vector you have different operators and methods such as at() or operator[] For more details check https://www.cplusplus.com/reference/vector/vector/ Since you want to learn C++, I assume you do not know what exactly to ask, so let me help you Your code example lacks further things, besid...
65,269,828
65,270,559
Split string C++ by '\'
I'm trying to split a path from Windows by '' , but when I'm running my program crashes. Here's a small example: char*s = "C:\\windows\\system32\\calc.exe"; char*pch; pch = strtok(s,"\\"); while(pch!=NULL){ printf("%s\n",pch); pch = strtok(NULL,"\\"); } I can make a search manually, but I think it's easier way than ...
You need a mutable string. A string literal is immutable. Trying to change a string literal will result in undefined behavior. Instead of char *s = "C:\\windows\\system32\\calc.exe"; (pointer to string literal) you can simply use a array of chars char s[] = "C:\\windows\\system32\\calc.exe";. This will copy the string ...
65,269,914
65,269,983
Copy constructor on return in C++
I'm trying to understand the following #include <iostream> class Number { int _value; public: Number(int number) : _value(number) { std::cout<<"constructed!\n"; } Number(const Number& other) : _value(other._value) { std::cout<<"copied!\n"; } ~Number() { std::cout<<"destructed!\n"; } }; Number create_number(in...
That's copy elision. Without getting too much into the C++ standard's obscure language, in most cases the compiler may elide (optimize away) the copy, but isn't required to. This is treated like any other optimization. Interestingly, this is a rare exception to the as-if rule, where the side-effects of an optimization ...
65,269,952
65,270,813
Compile time efficient remove duplicates from a boost::hana tuple
I use the boost::hana to_map function to remove duplicates from boost::hana tuple of types. See it at the compiler explorer. The code works very well but compiles very long (~10s). I wonder if there exist a faster solution that is compatible with boost::hana tuple. #include <boost/hana/map.hpp> #include <boost/hana/pai...
I haven't run any benchmarks, but your example does not appear to take 10 seconds on Compiler Explorer. However, I can explain why it is a relatively slow solution, and suggest an alternative that assumes you are only interested getting a unique list of types and not retaining any run-time information in your result. C...
65,270,016
65,270,045
How to use a string variable in an if statements condition C++?
I'm writing my final project in C++ for my computer class. We have to make a text adventure game so a little basics on mine: I made it so that the user has to pick from 3 subjects of learning: math, English, and science. Once that happens they go to a function for the subject choice. They have to solve 5 questions for ...
This is because you're creating a variable inside the statement. std::string is a type notation (you only need it once). When you declare it. Try if (your_choice == "math") {
65,270,182
65,270,905
Boost 1.74 serializing boost::posix_time::ptime getting error: ‘split_free’ was not declared in this scope
After updating to Boost 1.74 I am getting too many warning messages along with a compilation error. /usr/include/boost/date_time/posix_time/time_serialize.hpp:48:1: error: ‘split_free’ was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissiv...
That's minor deficiency in the Boost Datetime library. The serialization header does not include all required headers. This reproduces for Boost 1.74.0 on GCC 10: #include <boost/date_time.hpp> using boost::posix_time::ptime; #include <boost/date_time/posix_time/time_serialize.hpp> #include <boost/archive/xml_oarchive...
65,270,312
65,270,494
C++ accepting function as template and returning vector of function's return type
I was just experimenting with C++ templates when my friend asked me about NumPy's vectorize function, so I tried to implement my own version of it in C++. However, I decided to make it instantly calling original function with vector, and not returning vectorized function, so I came up with this code: #include <iostream...
Change typename Return = typename std::invoke_result_t<Func(Arg)>> to typename Return = typename std::invoke_result_t<Func,Arg>> And you should be good to go! You can see it working online at: https://rextester.com/QMI86655
65,270,373
65,270,550
Finding matching letters in a string at same spots
I need a code to compare two strings: word and ptw. Both strings only have one word, and are of equal length and same case. The code needs to check the first character of both words and see if they are same and it will do this untill the end of the word. Then it will output the amount of matching letters (I don't need ...
Assuming the two words have the same length and since you don't care which letters match you can simply iterate and count matching characters unsigned matchingletters(const std::string& word, const std::string& ptw) { assert(word.size() == ptw.size()); unsigned count{0}; for (size_t i = 0; i < word.size();...
65,270,450
65,270,711
Why is the recursion depth non-deterministic (C++)?
Repeated runs of the following C++ program give a different maximum number of recursion calls (varying by approximately 100 function calls) before a segmentation fault. #include <iostream> void recursion(int i) { std::cout << "iteration: " << ++i << std::endl; recursion(i); } int main() { recursion(0); }...
What happens when you blow the stack is not a guaranteed crash. Depending on the system, you could just be trashing memory in a relatively random bit of your memory space. What is in that memory might depend on what memory allocations occurred, how much contiguous memory the OS handed to you when you asked for some, A...
65,270,453
65,271,029
C++ XDevAPI multiple .values
I am using Xcode, MySQL and XDevAPI. I have the following table on the database create table TABLE(ID INT, VALUE_01 INT, VALUE_02 INT, VALUE_03 INT); I have the following values on code the code: Table table(session, "TABLE"); int id; set<int> numbers; id = 2395; numbers.insert(1); numbers.insert(2); numbers.insert(3...
You have two problems here. First, you're invoking values twice instead of once, and both times you're doing it with the wrong [number of] arguments. You're supposed to provide values() once per row, each time providing a value for each field in that row (ref). Second, a std::set<int> is ordered, meaning that for diffe...
65,270,695
65,307,839
Pivot table data structure
What type of data structure (or data structures?) could be used to store a pivot table of two dimensions where the data can be accessed? For example, let's take the following, copied from Excel: If the data was all in a one-dimensional hierarchy -- that is, it went Group > Product > Year > Value, we could do something...
In python hierarchical indexing is used to implement pivot tables. For example in python pandas pivot tables are multi-index dataframes. The implementation of a dataframe is in https://github.com/pandas-dev/pandas/blob/v0.22.0/pandas/core/frame.py#L236-L6142. MultiIndex is implemented in pandas.core.indexes.multi.py (h...
65,270,788
65,271,014
Concatenate float with string and round to 2 decimal places
So I have a function below formatted as polymorphic void display(string& outStr). The output from this function should basically be formatted into one large string, which will be saved to the outStr parameter and returned to the calling function. I have successfully formatted my large string into multiple lines but I w...
There is no need to do any crazy conversions. Since the function is called display, my guess is that it's actually supposed to display the value instead of just save it to a string. The following code demonstrates how that can be accomplished by just formatting your printing. #include <cstdio> #include <iomanip> #inclu...
65,270,963
65,271,077
C++ vector initialize with value
As a C++ beginner, I know that we can initialize a vector of vectors using: vector<vector<int>> vec(10, vector<int>(15, 0)); which is quite efficient, but when I want to do the same thing with a struct I wrote, The code won't compile: vector<TreeNode> vec(10, TreeNode("abc")); the struct looks like this: struct TreeN...
A string literal like "abc" isn't a std::string. But that's okay! A std::string, such as the one that's a parameter in your TreeNode constructor, can be constructed from one automatically. However, that string will be a temporary, and temporaries don't bind to non-const references (except with a Visual Studio extension...
65,271,297
65,271,421
Adding elements inside a typedef while taking care of the overall size of the struct?
I have a typedef'ed struct which currently looks like this: typedef struct Sys_Inject { uint16_t num; uint16_t alternative; uint8_t delay; uint8_t thresh; uint8_t reserved[2]; BOOL32 state; options_select_t sel; uint32_t per; } Sys_Inject_t; I want to get rid of the elements BOOL32 state; ...
The most reliable way is to just use the compiler's information: typedef struct Sys_Inject { uint16_t num; uint16_t alternative; uint8_t delay; uint8_t thresh; uint8_t reserved[2 + sizeof(BOOL32) + sizeof(options_select_t)]; uint32_t per; } Sys_Inject_t; Here's a program that statically checks ...
65,271,477
65,271,770
Defining uninitilized reference c++
I have a template T template<typename T>undefined_behavior(void) { throw; return T{}; } template<typename T> struct UBHandler { const bool valid; T value; (operator T)() {if(valid)return value;return undefined_behavior<T>();} }; This works when using rvalues but breaks when using rvalue referen...
Seems trivial to overload the type for references and write: #include <stdexcept> template<typename T> struct UBHandler { const bool valid; T value; operator T() { if (valid) return value; throw std::runtime_error(""); } }; template<typename T> struct UBHandler<T&> { T *const value...
65,271,707
65,276,691
How to use automake/autoconf with subdirectories properly?
I am looking to use automake for a project with a lot of subdirectories. What I want to achieve is compiling all of the source code in all of the subdirectories into one executable on linux. Right now I am using subdir-objects where I have to manually specify the paths of each of the source code files for the entire he...
Right now I am using subdir-objects where I have to manually specify the paths of each of the source code files for the entire heirarchy. You have to specify each source file individually, somewhere, in any case. I had tried using LTLIBRARIES approach using Makefile.am for each of the subdirectories, but for some re...
65,271,723
65,271,829
lvalue and rvalue reference can combine in one?
I found the below link which said "lvalue and rvalue reference interface can combine in one". Pass lvalue to rvalue but when I take it for example. compile error appeared cannot bind ‘std::string {aka std::basic_string}’ lvalue to ‘std::string&& {aka std::basic_string&&}’. Below is my implementation. #include <iostream...
To combine an r-value reference and l-value reference into a single reference, you need to use a so called universal reference. These are defined in C++ via auto && or a template with a && reference. See for example What is move semantics? , though, quite exceptionally, I guess you'll find more approachable explanation...
65,271,743
65,275,499
Difference between add_compile_options and add_link_options also flags each option supports
I've been using a .bat file to build my applications for years. Recently, switched to CMake for it's elegancy and I ran into a situation where I had to guess the flags that I should put into CMake's add_link_options and add_compile_options Example flags that I've used in my BAT file, -s WASM=1 --bind -s MODULARIZE=1 A...
I am not sure what your problem is, but here is a full working sample from a Wasm project that sets project-wide strict mode and disabling of exception support: if (EMSCRIPTEN) add_compile_options(-fno-exceptions "SHELL:-s STRICT=1") add_link_options("SHELL:-s STRICT=1") endif() Note in particular that, as it ...
65,271,783
65,271,822
Exception Safety: Strong Guarantee vs Basic Guarantee
I'm trying to learn C++ right now and have gotten on the topic of exception safety. I'm pretty sure I understand the meaning of the four different levels of exception safety. However what are some concrete examples of when a strong guarantee would be inappropriate but a basic guarantee would be appropriate?
The strong exception guarantee is of course nice to have, and in the absence of any other consideration should be provided. However, there are cases where providing the strong exception guarantee is too expensive, too complicated, or even impossible. Here are some examples: Sorting. If a sort predicate fails, do you...
65,271,920
65,272,237
Pass data via template argument, C++
I am thinking about having color spaces structs in my program. Now as you can see each color space has its limitations for each of its component. So consider a struct like this. template<typename T> struct SomeColorSpace{ T component1,component2,.....; // or std::array<T,N> components, N is compile-time const }; ...
Support for literal classes as non-type template parameter is already in clang trunk. See it live on godbolt: template<typename T> struct Range { T min, max; }; template<typename T, Range<T> R> struct SomeColorSpace { static constexpr Range<T> r = R; T component1, component2; }; using Rgb = SomeColorSpac...
65,271,977
65,271,999
how to count how many times a loop was executed?
I am writing a program that prints products of a number, (for example, 2 can be 1 * 4 , 2 * 2 , 4 * 1 and counter shows (3) numbers), I need to have a counter that counts how many numbers were printed. I can't use (i) as a counter as it counts everything. for(i=1; i<=number; i++) { if(number%i==0) cout<<i<<"*"<...
Just add another variable and expand the body of the if-statement right? int count = 0; for(i=1; i<=number; i++) { if(number%i==0) { cout<<i<<"*"<<number/i<<"="<<number<<endl; count++; } } cout << "Printed " << count << " times" << endl; return 0;
65,271,979
65,277,474
In c++, is there a way to pass a value to a constructor without a move or copy happening?
I'm writing a game engine in C++ for the first time and I need a state manager / machine. I want it to have ownership of all states. When I started digging into how functions usually work, I found out they normally copy or move a value into the function. That seems unnecessary to me. What I want is to create the value ...
Move is generally cheap, so avoiding it at all cost is not really needed. You can provide interface to avoid move/copy by constructing in-place class StateManager { public: template <typename ... Ts> StateManager(in_place_t, Ts&&... args) : state(std::forward<Ts>(args)...){} private: State state; }; int m...
65,272,001
65,274,324
std::initializer_list as constructor argument in template class
I'm trying to use std::initializer_list in a constructor to accept variable number of arguments. With non-template class it works fine, but with template class it gives compiling errors. Could anyone possiblly point me to the right direction? My g++ is capable of C++17. #include <iostream> #include <vector> #include <t...
Template cls1({vec, vec+2, vec+3, vec+4}) has no ways to deduce T. You might use Template<double, double*> cls1({vec, vec+2, vec+3, vec+4}); or provide custom deduction guide: template <typename It> Template(std::initializer_list<It>) -> Template<typename std::iterator_traits<It>::value_type, It>; Or simplify your cla...
65,272,198
65,272,522
C++ Looping through an Array to display contents
I'm writing a loop to go through a 3d array and display the contents of [0][0][0] through [0][2][4]. It displays and acts normal from [0][0][0] through [0][0][4], but after that it jumps to [0][2][0] instead of to [0][1][0]. I can't figure out why that is myself if anyone could correct my mistake. a, b, c, d, and e are...
You need to reset the value of b each time the for loop is executed
65,272,519
65,273,111
how to move unique_ptr object between two STL containers
#include <utility> #include<unordered_map> #include<queue> using namespace std; struct Task { char t; int cnt; Task(char ch, int cnt):t(ch), cnt(cnt){}; }; struct CompTask { bool operator() (const unique_ptr<Task>& a, const unique_ptr<Task>& b) { return a->cnt < b->cnt; } }; class Schedule...
There seems to be lack of move functionality out of std::priority_queue<>. You can go around it using const_cast, though in rare cases it might cause undefined behavior (when stored element type is const). int schedule() { unordered_map<unique_ptr<Task>, int> sleep_q; priority_queue<unique_ptr<Task>...
65,272,863
65,273,000
How do you add certain values in map based off of user input?
I'm trying to make a Gematria calculator in c++ and want to get the same results i am getting in java. How would I get so in C++ it could print the sum of the values from what the user inputs and get the same ultimate result as I would in Java? Please note I'm a beginner at C++ so please forgive me for any ignorance in...
if I understand your problem the key type of the map should be char and not string. The same should apply to the java version. see Why is using namespace std; considered bad practice? we don't use std::double_t. Honestly I've never even heard of this until now. Use double. by default prefer std::unordered_map over ...
65,272,986
65,273,172
How to make function thread safe
This is the code where i would be inserting values in a unordererd map and would also query those values at regular intervals. class MemoryMap { private: std::unordered_map<std::string, std::string> maps_; std::mutex mutex_; public: void AddMap(std::string key, std::string value); std::string Get...
It is sufficient. The mutex lock guarantees at most one thread get call get or set at the same time. However, your code might be not optimized if you want to achieve concurrent reads. In C++, unordered_map is a container, which has thread safety like this: https://en.cppreference.com/w/cpp/container#Thread_safety Two ...
65,273,006
65,273,342
Iterable Designated Initializer Alternative in C++
In C99, a struct array can be initialized static struct {char* tag; char* msg;} help_info[] = {[0]={"tag0","msg0"}, [1]={"tag1", "msg1"}}; This is not valid in C++. What is a possible alternative to replicate this behavior for an iterable object containing defined information?
C++20 added designated initializers to C++. There are some restrictions compared to C, in a couple of different directions. In your case, the main difference of note is that C++ has tightened up a bit of the type system so you can no longer initialize a char * from a string literal. In C, you can initialize a char * fr...
65,273,582
65,273,648
What is the difference between const string &s and string &s?
This is the code from c++ primer: string::size_type findChar(const string &s, char c, string::size_type & occurs){ auto ret = s.size(); occurs = 0; for (decltype(ret) i = 0; i != s.size(); ++i){ if (s[i] == c){ if (ret == s.size()) ret = i; occurs++; }...
A string literal like "hello, world!" is not a std::string. So to call your function the compiler has to create a std::string for you. Such an object is called a temporary. So in the first case the compiler uses "hello, world!" to create a std::string and then binds that temporary string to reference parameter s. Howev...
65,273,770
65,275,521
Bind a valid class object pointer to boost::function<>fn. What may happen if invoking the `fn` after the object has been destoryed?
Bind a class member function and a valid class object pointer to boost::function<>fn. What may happen if invoking the fn after the object which the pointer pointed to has been destroyed? Are there some potential problems that I should be aware of? Domo code snappet: class CTest { public: int demo(void){}...
You need to ensure that the target object's lifetime exceeds the function object's lifetime. This is easier to express in an obvious way with a lambda function instead of bind. The lambda can explicitely capture the object 'by-value': std::function<int(void)> fn; { CTest tes; fn = [tes] { tes.demo(); }; } fn();...
65,273,837
65,315,930
Android native file read from assets folder by tflite BuildFromFile()
I have Android native code (C++ shared object), that want to read model file kept in the assets folder while creating APK. Tensorflow Lite has two APIs: FromFile and FromBuffer static std::unique_ptr<FlatBufferModel> BuildFromFile(const char* filename, ErrorReporter* error_reporter); static std::unique_ptr<FlatBufferM...
I don't think you can use BuildFromFile without copying the asset file to a local file (which is equivalent to what you've done above, and then BuildFromBuffer is more convenient in this case). If you want to avoid memory copy, here is what you can do: (Java) Load the model through memory mapping. AssetFileDescri...
65,274,005
65,293,464
error: JNINativeMethod nfptr throwing invalid conversion from jobjectarray* to void*
I hava following simple jni application: jobjectArray ListItems(JNIEnv *env, jobject self, jstring library) { jclass c = env->FindClass("java/lang/String"); jobjectArray a = env->NewObjectArray(2, c, 0); env->SetObjectArrayElement(a, 0, env->NewStringUTF("text1")); env->SetObjectArrayElement(a, 1, env->NewS...
as @Michael said, just need a void* casting: int main() { ... ...*load and initialize Java VM and JNI interface* ... JNINativeMethod m[1]; m[0].fnPtr =(void*) ListItems; m[0].name = "listItems"; m[0].signature = "(Ljava/lang/String;)[Ljava/lang/String;"; env->Registe...
65,274,405
65,275,300
create a function to add a doubly linked list to itself at the end
#include <iostream> #include <string> using namespace std; class Node{ public: double data; Node* next; Node* prev; }; void insert(Node**,int); void display(Node*); void finaloutput(Node*,Node**); int main() { Node* head=NULL; Node** second=NULL; insert(&head,1); insert(&head,2); insert(&head,3); ...
If the assignment is create a function to add a doubly linked list to itself at the end then the expected by you output 5 4 3 2 1 4 5 4 3 2 1 is incorrect because before doubling the list it has the following values 5 4 3 2 1 So the output of the doubled list will be 5 4 3 2 1 5 4 3 2 1 You need to add new nodes t...
65,274,887
65,276,555
Partial specialisation of member function with non-type parameter of a class with non-type parameter
I have a matrix class with a toString() method: template <typename T, int rowCount, int columnCount> class Matrix { //... public: std::string toString() const { // ... } }; Now I want to specialize toString() for the case, that T is Matrix so that it returns a string in a different format in the ca...
You can use if constexpr to achieve this. template <typename, int, int> class Matrix; template <typename> struct IsMatrix : std::false_type { }; template <typename T, int N, int M> struct IsMatrix<Matrix<T, N, M>> : std::true_type { }; template <typename T, int rowCount, int columnCount> class Matrix { //... pub...
65,274,994
65,275,158
How do I take input from the user of their full name, and then output their first name and last name seperately? (C++)
I only so far made the outline, and I just don't know how to continue onwards with it, I am stumped. Example output should be: enter your full name xfdgchkv loyloyloy your name is xfdgchkv and surname is loyloyloy #include <iostream> #include <string> using namespace std; int main() { string fullName; ...
cin ignore space/new-line, so you can use this: cin >> firstname >> lastname;
65,275,492
65,278,096
Vector of iterators to unordered map - compilation error
Hey fellow programmers I want to create a vector of iterators to unordered map for elements which fulfill some criterion. I've written a function for that, but it doesn't compile, and I don't understand what's wrong with the code: class Cache { public: Cache() {} template<typename Functor> std::vector<...
getSpecificOrders is declared const; therefore transactions within that function is a const object; therefore transactions.begin() returns Transaction::TransactionsContainer::const_iterator. You are trying to add that to the vector of Transaction::TransactionsContainer::iterator, but the former is not convertible to th...
65,275,712
65,293,167
Rationale behind deleting lambda assignment operator?
I just learned that a (even mutable) lambda in C++ is not assignable unless it has empty captures (c.f. ClosureType::operator=). Example: auto x = 0; auto l0 = [copy = x]() mutable {}; auto l1 = []() mutable {}; static_assert(not std::is_copy_assignable_v<decltype(l0)>); static_assert(std::is_copy_assignable_v<decltyp...
I suspect it was not proposed. Lambdas entered the language much weaker than the function objects they are sugar for and slowly are gaining back functionality. With respect to the special member functions, P0624 proposed adding assignability and default-constructibility for captureless lambdas. Only default-constructib...
65,275,778
65,291,032
Undefined reference with xtensa-lx106-elf-gcc?
I'm using Arduino IDE and planning on later moving to a VSCode/Makefile solution. I have a project that compiles and runs fine if all the code belongs in the main sketch. Once I separate the code, the linkage step fails. I've boiled it down to a simple demonstration: What works Sketch file #ifdef __cplusplus extern "C"...
Arduino's Github According to https://github.com/esp8266/Arduino/issues/1283, where Links2004 states: random is a API function from Arduino not working on C the answer seems to be to replace calls to replace calls to random to calls to rand. Testing demonstrates that both in that demonstration source and the real sou...
65,275,939
65,276,055
Are .cpp files useful?
I can understand that headers are used to include classes and functions into another file, but .cpp just seem a bit useless to me. .h files are used to declare functions that can be exported/imported, however, template functions and classes must be defined in the same .h file and not only declared. I have only used .cp...
Here's an example of how to organize your code. Define headers for any classes you're using, like: // example.h #pragma once // Avoid duplicate imports, if supported by your compiler #include <string> class Example { public: Example(); Example(const char* name); ~Example(); protected: std::string name; }; The...
65,276,102
65,277,351
Compilation errors with M1 MacBook Pro and cmake
I have just got my new M1 MacBook Pro and am trying to compile a code base required for my university work. Here are the steps I have taken: I set Terminal to always open using Rosetta. Installed homebrew using /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" Installed c...
Have you reopen Terminal after xcode installed? It's needed to set the environment variable SDKROOT. Close and run again Terminal or open a new tab in Terminal. Or run the following command in the current Terminal export SDKROOT=$(xcrun --sdk macosx --show-sdk-path) Also be sure the proper xcode toolchain is selected ...
65,276,282
65,393,101
How to solve C++ linking error in shared library linked to a static library
I'm struggling with a linking error. I have 3 modules: static library A which defines function ole::compound_document::find_storage(const std::string&); shared library B which is linked to A and uses the function; executable C which is linked to B and uses functions from B (but does not call directly functions of libr...
As mentioned by n. 'pronouns' m.The problem was in inconsistent use of -D_GLIBCXX_USE_CXX11_ABI flag. I used c++14 standard, but some projects were compiled with the flag -D_GLIBCXX_USE_CXX11_ABI=1. It was not easy to find out, because I use a lot of 3rd party libraries with conan package manager.
65,276,795
65,276,830
Does the operator [] accepts types other than ints in C++?
I'm trying to recreate the Dictionary from python into C++, for the sake of learning. I want to be able to use the subscript operator [] with a keyType (which is the data type of the keys in the dictionary, might be an int, string... etc), I tried this approach (i'm using linked lists): // keyFind is the value to b...
Does the operator [] accepts types other than ints in C++? Operator overloads are just functions, and they can accept any parameter types just as other functions can. So, yes. The C++ standard library already provides std::unordered_map and std::map which are for most purposes analogous to Python dictionaries.
65,276,937
65,277,225
How to check the prime numbers from a vector in c++?
I have written a piece of code below, that asks for a user to input the number of a vector's elements and the elements of it. I want to use a function for checking prime numbers from the vector. For example, I have a vector with 2,6,3,7 as elements and the function have to check how many prime numbers are there, but th...
There was an error in the logic flow of your algorithm to find prime numbers. I have fixed it down below, and also made your methods void as they don't return anything. Variables declared and not used where also eliminated. #include <iostream> using namespace std; void input_vector(int a,int t[20]); void output_vecto...
65,277,255
65,277,420
String to unsigned long append the ascii value in binary. C++
I'm looking for a way to simply append the ASCII value of text[i] to an unsigned long. For an example: string something = "abc"; The ASCII values are 97, 98, 99. I'm NOT trying to get a sum of 97, 98, 99 making it 294 it should be 6 382 179. EDIT For clarification: Meaning that the value that is appended it's the 8 bit...
You need the left shift operator to move the existing bits before you add the new bits unsigned long temp = 0; for (int i = 0; i != text.size(); i++) { temp <<= 8; temp += text[i]; } return temp;
65,278,016
65,278,085
C++ char array declaration in Class
I'm creating a game where I want to save the screen data in 1D array of data type char. Screen data has to be a global variable in the class. The size of array will be determined after initialization. In constructor there will be declared some constant values, that are used the calculate the exact size of array. class ...
Array sizes must be compile time constants. Use a vector instead. #include <vector> class Screen { public: Screen(uint16_t width, uint16_t height); private: uint16_t WIDTH; uint16_t HEIGHT; std::vector<char> field; }; Screen::Screen(uint16_t width, uint16_t height) : WIDTH(width), HEIGHT(height), ...
65,278,774
65,279,533
In c++ code, set.erase(it) is halting execution, where it=set.begin() for a set of pairs, why is this happening?
Sorry for any inconvenience I am a beginner at C++ and was stuck with an empty set... Thank you for the helpful comments that helped me figure out what the problem was I wrote a C++ code for a question in which I need to use Dijkstra's shortest path algorithm in n*log(n) time and so I am using set of pairs to obtain th...
The problem as told by user4581301 in the comments was that the iterator was pointing to the end() of the set, which means the set was empty as it was initialized to point to begin() of the set. Thus an undereferencable iterator was dereferenced resulting in undefined behavior, (this means it may not necessarily give a...
65,278,781
65,278,885
How to find out the size of a dynamic Eigen vector in bytes?
I'm going to calculate the size of the vector. If I write this code: Eigen::Matrix<float, 6, 1, Eigen::ColMajor> staticVector; std::cout << "sizeInBytes: " << sizeof (staticVector) << std::endl; the output is: sizeInBytes: 24 But if I write: Eigen::Matrix<float, Eigen::Dynamic, 1, Eigen::ColMajor> dynamic...
If Eigen::Matrix's array is all in the stack, then sizeof should return the right value. This would be great for small Matrices, but could become dangerous for largest, as it could cause stack overflow. If data are stored in the heap then you need to make a method that adds stack and heap memory and returns it. This wo...
65,279,075
65,279,222
Is it safe to pass nullptr to C function?
I have some library written in pure C. Now I'm creating some unit tests but the testing library is written in C++ rather than C. When I pass NULL to API function under test CLion gives me a hint to pass nullptr instead of NULL. Is it safe to pass nullptr to pure C function in this case?
Is it safe to pass nullptr to pure C function in this case? I think it is. From the C++11 standard (4.10 Pointer conversions): A null pointer constant is an integral constant expression ([expr.const]) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be c...
65,279,138
65,279,205
C++ console closes immediately, possibly crashing (cin, system("pause"), etc. have no effect)
I've got the bare shell of a program with a "BasicObject" class and a randum number generator class implemented. When I run the program, the console closes immediately, and cin functions, system("pause"), etc. have no effect. I suspect a crash, but can't find what the source might be. Any help? BaseObject.cpp: #include...
It's crashing, because here obj->get_id() obj is not initializated yet. Just a pointer to memory with some random garbage. You need something like BaseObject* obj = new BaseObject() Before you can use obj
65,279,345
65,280,014
Segmentation fault with cout in merge sort
I've read many posts but I can't figure out where is my error so I go with it. My program throws the segfault at the cout<<endl. When I erase it, the program doesn't even print anything. It just prints the segfault. Aparently the program never reach to sort the vector. #include <iostream> #include <vector> using namesa...
You have problems in your code with vector indices assuming value -1 inside a couple of loops. I have corrected these mistakes below, a working version of your code: #include <iostream> #include <vector> using namespace std; void inserctionSort(vector<double> &v, int i, int j) { int v_size = v.size(); double ...
65,279,621
65,280,849
MPI_File_write_at : Writing the same struct twice results in slightly different data blocks in binary file
I have the following simple MPI code: #include <iostream> #include <mpi.h> int main() { struct test { int rank = 1; double begin = 0.5; double end = 0.5; }; MPI_Init(NULL, NULL); int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); int world_size; MPI_C...
Instead of: MPI_Aint disp[3] = {0, 4, 12}; do the following: disp[0] = offsetof(test, rank); disp[1] = offsetof(test, begin); disp[2] = offsetof(test, end); do not forget to include "#include <stddef.h>", and to adapt the offset (i.e., offset = sizeof(test) * world_rank;) Do not try to manually hardcode the offsets, ...
65,279,650
65,279,672
Segmentation fault while trying to access empty vector
So I made a 2D array of chars but Every time I try to access it I get a segmentation fault and I cannot figure out why. std::vector<std::vector<char>> matrix_; //Filling it with space ' ' characters std::vector<char> aRow; matrix_.resize(height_, aRow); for (std::vector<char> row : matrix_) { row.resize(width_, ' ...
Use auto&& row : matrix_ (note the reference added), in the for to get the reference to each row you are looking for. As you have it, it creates a copy, resizes it and discards the result. Without being too pessimistic about it, you could also look to resize each column with the right sized row. The for loop is not nee...
65,279,760
65,287,689
How to pass dynamic Eigen vector to GPU using Cuda?
I am going to learn how to transfer a dynamic Eigen vector to a GPU and get it back. For these purposes, I wrote a test code: using Vector = Eigen::Matrix<float, Eigen::Dynamic, 1, Eigen::ColMajor>; Vector vector; uint64_t size = 6; vector.resize(size); for (uint64_t i = 0; i < size; ++i) v...
The easiest way to fix this is to turn this into a float* pointer using the Eigen data() function, which returns a raw pointer to the data in your matrix. You can transfer the data to the GPU, work on it there, then copy that data back and store it in a nice Eigen Matrix again. #include <iostream> #include <cuda_runtim...
65,280,059
68,037,896
Is there any way to compile C++ code by pressing f5 or any other key in VScode?
Is there any shortcut key in vscode to compile C++ code , like vim or atom has f5 ? Press the key and you have a black dialog window . I use vscode for competitive programming and I compile code using "g++" syntax on command prompt . Any method faster than this will work .
You need to install the extension called "Code Runner". To do that : Click on the four squares with one square not align icon on the left. Type "Code Runner", find the extension and install it. Also install the "C/C++" extension. When both extensions are installed, to compile and run, press Ctrl + Alt + n. Small tip ...
65,280,184
65,280,506
Define `static constexpr` function on source file
I have a class on a header file, which has its members defined inside a pimpl class. The idea is that I use this method (basically std::aligned_storage_t and a pointer, but the size and alignment of the class have to be specified when declaring the object) to allocate the pimpl class on the stack. I want to make the co...
There are a couple issues with your code that strike me as odd. The point of the "PImpl" idiom is to decouple an interface from its implementation, typically in order to allow easier compilation when the implementation changes. However, by defining your struct impl inside your interface class and by using it in a templ...
65,280,272
65,280,406
Trying to implement an extremely simple toy version of std::vector and hitting an EXC_BAD_ACCESS which I don't understand
I just started learning C++, and was trying to implement a simple version of std::vector when I hit the bug I mention in the title. The following code sometimes triggers a EXC_BAD_ACCESS on a line which I mark with a comment on the code snippet below, and I am not sure why. Anyone have any suggestions? I thought that n...
There are several issues with your code. The first and foremost is this one: size_t new_size = size * 2; T* newStore = new T[size]; // <------ Error You failed to use new_size when you used new[]. The code should be: size_t new_size = size * 2; T* newStore = new T[new_size]; The second issue is that you should u...
65,280,539
65,280,721
Passing a reference array to template pointer array
I have this class: template<typename T> class array_eraser { T* array; int size_array; public: array_eraser(T &a[], int s) { size_array = s; array = new T[s]; array = a; } } I call the class with this line in main: std::string langs[] = { "C++", "Haskell", "Ada", "Python", ...
You are nicely demonstrating why not to use raw arrays. T &a[] is not a reference to an array of Ts but an array a of references to T. Maybe you wanted T (&a)[] - a reference to an array. But that will not fly either. Because in this case you disable the decay mechanics and you have to specify the size. This can be do...
65,281,046
65,281,161
In C++, is there a way I can make a mutable const member variable? Like with the "final" keyword in java?
I'm creating a game engine class which will have a "logger" member. Like this: class Engine { public: const Logger logger; Engine(); ~Engine(); void init(); void start(); }; My question is whether it's possible to make "logger" so I can't override the variable, but still modify the object itself?
C++ has no concept of "replacing" variables in the first place, so what you're asking for doesn't make a ton of sense. It would be better to forget Java when writing C++; they are different languages with different paradigms and concepts. If you want to prevent users of your class from being able to logically "replace"...
65,281,085
65,281,370
c++ pointer manipulation problem with linked list insert at head for a graph
I have a Graph class that stores an array of linked list. I want to insert at head of linked list and set the "next" of the new item to previous head. However, when I set the new head's "next" as previous head, it ends up setting the new head as its own next causing an infinite loop because the next also points to itse...
The problem is here: EdgeNode edges[MAX_VERTICES]; You have an array of objects. When you overwrite an element in the list the object no longer exists, as a result you can not create a chain. // This creaters a local object. // When this function exits this object will no longer exist. // Which is fine for...
65,281,372
65,283,059
Detect Mouse Hover Over Button?
I have an owner-drawn button that I would like to highlight, when the mouse hovers over it. Here is the simplified code, that doesn't seem to work: case WM_DRAWITEM: LPDRAWITEMSTRUCT pDraw = (LPDRAWITEMSTRUCT)lParam; if(pDraw->itemState == ODS_HOTLIGHT) DrawButton(pDraw->hDC, HIcolor); else ...
ODS_HOTLIGHT may not be used by the button. See What states are possible in a DRAWITEMSTRUCT structure?. You can use subclassing, and then use TrackMouseEvent to get the event in SUBCLASSPROC. LRESULT CALLBACK Subclassproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) { ...
65,281,609
65,281,806
Strange overflow assigning 2 * 1024 * 1024 * 1024
void main() { long long ll = 2 * 1024 * 1024 * 1024; unsigned long long ull = (2 * 1024 * 1024 * 1024); std::cout << ll << "\n" << ull; } My output with Visual Studio 2019 is -2147483648 18446744071562067968 I have no idea why overflow is happening here, please help
In both cases the calculation is done using integers because all the values on the right are integer literals. 2 * 1024 * 1024 * 1024 is 2,147,483,648 which 1 larger than the max 32 bit int so this part of the calculation is overflowing. To fix do the first calculation as long long using long long ll = 2LL * 1024 * 102...
65,281,689
65,281,784
How to shift elements to end of the array
I have this array: std::string langs[] = { "C++", "Ada", "Haskell", "Python", "Ada" }; I would like to write a function to shift K elements to the end for instance: k="Ada"; { "C++", "Haskell", "Python", "Ada", "Ada" }; I wrote this but its not working: void moved(T e) { istd::vector<int> indexes; for...
If the order doesn't matter you can use std::partition: int main() { std::string langs[] = { "C++", "Ada", "Haskell", "Python", "Ada" }; std::partition(std::begin(langs), std::end(langs), [](auto& lang) { return lang != "Ada"; }); for (auto& str : langs) { std::cout << str << std::endl...
65,282,134
65,286,920
Different behavior between clang++ and g++ (using c++17)
I was trying to use some modern c++ dark magic, in order to test if a class has a member function called funcA. And... it backfired... It worked perfectly using "g++ -std=c++17 main.cpp". But when I compiled the same code with "clang++ -std=c++17 main.cpp", it returned false even that the class had this function! Can...
@Igor Tandetnik answer solved the problem. I removed the word template from this line struct HasFuncA<T, S, std::void_t<decltype(std::declval<T>().template funcA(std::declval<S>()))>> : std::true_type {}; ==> struct HasFuncA<T, S, std::void_t<decltype(std::declval<T>(). funcA(std::declval<S>()))>> : std::true_type {};...
65,282,288
65,293,976
Time complexity of the travelling salesman problem (Recursive formulation)
According to this recursion formula for dynamic programming (Held–Karp algorithm), the minimum cost can be found. I entered this code in C ++ and this was achieved (neighbor vector is the same set and v is cost matrix): recursion formula : C(i,S) = min { d(i,j) + C(j,S-{j}) } my code : #include <iostream> #include <ve...
Your algorithm time complexity is O(n!). It's easy to understand that your code is guessing the next node of the path. And there're exactly n! different paths. Your code actually counts the same value several times. For example if you run TSP({1, 2, 3, 4}, 0) and it tries order {1, 2, 3} and {2, 1, 3}. It is clear that...
65,282,509
65,282,588
Is the initialization order of the vector elements guaranteed by the standard?
To fill a std::vector<struct_name> from std::cin, I usually write as following code: struct point{ int x, y; }; int main() { std::size_t n; std::cin>>n; std::vector<point> vec(n); for (auto& p:vec) std::cin>>p.x>>p.y; //... } But today I found out another way to do it with default constr...
It is not guaranteed that the elements are initialized in the order of their indices. In C++11, see [vector.cons]/3: Effects: Constructs a vector with n value-initialized elements. This says nothing about the ordering, so nothing can be assumed. The wording changes in later editions of the standard, but no ordering e...
65,282,778
65,283,004
Is an identity conversion of pointer type be considered as qualification conversion when ranking
void fun(int*); // #1 void fun(int const*); //#2 int main(){ int* ptr = nullptr; fun(ptr); } Consider the above example, the overload resolution shall select the best viable function in #1 and #2. This is a branch of this question, namely, the vague between [over.ics.rank#3.2.1] and [over.ics.rank#3.2.5]. The r...
The standard conversion sequence from int* to int* does not contain a qualification conversion. This is made explicit by [over.ics.best.general]/8: If no conversions are required to match an argument to a parameter type, the implicit conversion sequence is the standard conversion sequence consisting of the identity co...
65,282,926
65,283,170
ifstream reading extra characters (CR 13 LF 10) at end of lines
I am currently reading a text file that has newlines occupying 2 bytes, since it writes newline as CRLF instead of only LF. std::fstream fileReader = std::fstream(_filename, std::ios::in); // READ THE SIZE OF THE FILE: fileReader.seekg(0, fileReader.end); // set reader position to the end std::streamsize fileSize = fi...
This is normal behavior: ifstream::read expects "the amount of characters that will be extracted" as a parameter, not the file size. Since this amount is impossible to predict, and the function does not provide it either, using ifstream::read without the ios::binary flag is completely useless, unless the file is KNOWN ...
65,283,146
65,283,946
why copy constructor called but not move constructor in c++11?
This is the C++ test I do. I thought move constructor would be called, but it's not. neither the two cases will call move constructure. class MyTest { public: MyTest() {} ~MyTest() {} MyTest(const MyTest& lv) {} // be called actually MyTest(MyTest&& rv) {} // not be called actually, but i ...
Your copy assignment operator void operator=(const MyTest& lv) { MyTest(std::move(lr)); } have three problems: The argument is named lv but you use lr inside the function; The argument lv is a reference to a constant MyTest object, it can't be "moved" from; And the statement MyTest(std::move(lv)); // Corrected...
65,283,381
65,283,493
Why can't I define a count variable outside of my loop in this function (C++)
This is a very basic question, I know, but I was solving the following simple exercise: my2Darray is a two-dimensional array of doubles with nRows rows and nCols columns. Write a function that sums all the elements in each column and returns them in an array called totalsByColumn. Write a second function that sums all...
Because after the first iteration rowCount will be equal to nRows. And for the 2nd iteration of the outerloop it doesn't re-initialize to 0 therefore the code inside this for ( ; rowcount < nRows; rowcount++) loop doesn't work. You have to reset the value of rowCount to 0 after the iteration of the inner loop. If you r...
65,283,473
65,289,633
C++ My first time trying to use a Makefile. It won't work
I am trying to create a Makefile for a simple project that has 3 files and Makefile. When I compile, console displaysL: make: Nothing to be done for 'all'. And nothing happens Code: math: main.o function.o g++ main.o function.o -o math main.o: main.cpp g++ -c main.cpp function.o: function.cpp g++ -c funct...
My IDE is Eclipse FYI This is a key detail. You did yourself and others a disservice by burying it in a semi-parenthetical comment at the end of the question. When I compile, console displaysL: make: Nothing to be done for 'all'. Your IDE has some specific expectations for makefile conventions, and your makefile d...
65,283,516
65,283,563
Getting a number when added char. Why?
I am trying to concatenate the characters of a string but getting numerical value(s) instead. Why's that so? C# using System; namespace std { class Program { static void Main(string[] args) { string n = "helloWorld!"; Console.WriteLine(n[0] + n[1] + n[2] + n[3] + n[4] + n[5]); ...
All x[i] are chars. A Char stores a numerical value that represents a character depending on the encoding you're using. When you do x[i] + x[j], you're not concatenating them, you're simply adding their numerical values.
65,283,517
65,283,614
size of class name vs size of an instance of the class
class test { public: int a; }; int main(){ test t; // return ; } In the above example, is it correct to say sizeof(test) is always equal to sizeof(t)?
From the reference for sizeof, the two ways this operator can be used are: sizeof ( type ) Yields the size in bytes of the object representation of type. sizeof expression Yields the size in bytes of the object representation of the type of expression, if that expression is evaluated. In your example with sizeof(...
65,283,787
69,891,694
Variadic template tensor class
I'm trying to make a variadic template tensor class with as template parameters a type and a set of dimensions. For example creating an array of 13 floats would use Tensor<float, 13> a; and creating a 3rd order 3 by 4 by 5 tensor of doubles would use Tensor<double, 3, 4, 5> b;. This is for a HPC application. Ultimately...
std::array<Tensor<T, n>, m> a; should be std::array<Tensor<T, n...>, m> a; and the class should be redefined so that e.g. Tensor<float, 3> is legal.
65,283,848
65,284,264
An issue about the example after [conv.lval#2.2]
The example is: struct S { int n; }; auto f() { S x { 1 }; constexpr S y { 2 }; return [&](bool b) { return (b ? y : x).n; }; } auto g = f(); int m = g(false); // undefined behavior: access of x.n outside its lifetime int n = g(true); // OK, does not access y.n The relevant rule is: When an lvalue-to-rvalue conv...
The issue with your reasoning is that [conv.lval]/3.2 doesn't ask for n to be not-odr-used. The expression in question is E = (b ? y : x).n. The set of potential results is {x, y}. The evaluation of E, when b = true, would eventually result in the evaluation of y. Therefore, we can set Ex = y, and we now find that "the...
65,283,897
65,285,601
How both the function act different from each other not in the matter of time complexity
For the below question where does the both function differ. I have tried stress testing both the function returns the same result. I am trying to submit the product function in the competitive programming site it return wrong answer for some test cases, while all the test cases passes for the max_dot_product function. ...
The max_dot_product() function calculates the products of elements of a and b by converting them to long long and then doing the multiplication. This happens due to the usage of std::multiplies<long long>() which creates a functor with an operator() that accepts two long long arguments, and returns their product as ...
65,284,762
65,285,004
Optional type in recursively defined class
I'm making a tensor class that can make tensors of any order. For example a third order 3 by 2 by 4 float tensor is made using Tensor<float, 3, 2, 4> a. The elements are recursively stored as arrays of lower order tensors, until the 1st order, at which point they're stored as an array of the given type. template <typen...
Instantiating std::conditional<sizeof...(n) == 0, T, Tensor<T, n...>> instantiates Tensor<T, n...> even when the condition is true, meaning you give the template one argument instead of the 2+ it requires. Lazy arguments don't exist in C++ for general use (including standard library templates). You need to delay the in...
65,285,050
65,285,331
Memory access violation
My program is reading, the memory that I don't have the access, I have tried multiple debug statements, but could not find what I am doing wrong. The code is not complete yet as I am finding the access violation. // Program to find the length of the longest repeating sequence in a string. #include <iostream> #include <...
You have map m from string_view to integers. string_view doesn't own memory. It only refers to one. So m[""+s[i]] =... will create a string and then m will have a string view pointing to a destroyed string leading to UB. You also most certainly use substr incorrectly. Second parameter is size and not location. I believ...
65,285,404
65,285,447
Can i store a pointer to forward declared classes/structs?
#include <stdio.h> struct B; struct A { B* b; int num = 4; A() { b = new B(this); } }; struct A; struct B { A* a; int num = 21; B(A* a) { this->a = a; } // function that does stuff with both A and B nums int add() { return num + a->num; ...
It's possible but you're going to have to move some code around because many expressions cannot be compiled until the type is fully known. For instance new B(this) cannot be compiled until B is fully known. So the A constructor needs to be compiled after B is defined, like this struct B; struct A { B* b; int n...
65,285,453
65,285,535
C++ functions with pointers
What is the error? How to solve it? This code is to find the area of the circle using pointers and functions. The error I am facing is that the &answer cannot be converted into float. #include <iostream> using namespace std; void area(float, float); int main() { float radius, answer = 0.0; cout << "Enter a r...
You can do one of the 2 things: Change the prototype to void area(float*, float*); Remove the prototype and move the function: void area(float *value, float *result) // This is the function to calculate the area. { *result = 3.142 * (*value) * (*value); } above the main() function. Either of these will work.
65,285,534
65,285,727
Unable to mark a second subscript operator overload as const
So in my Matrix class I've used some weird syntax in this post in order to use the class as a 2D array. However marking the second overload as const just tells me it expected a ';'. #pragma once #include <iostream> using std::ostream; struct Matrix { public: Matrix(float identity = 0.0f) { for (int ...
The correct syntax is const float (&operator[](unsigned int index) const) [Columns] You could get this by starting with operator[](unsigned int index) const, and then adding the result type around it, if you're into that sort of thing. But why make life difficult? Use a type alias. using Row = float[Columns]; Row& op...
65,285,921
65,286,198
"Identifier" Undeclared Identifier
Right now i try to change character set on my code from multibyte to unicode but when i compile this code i got an error, this is my error error C2065: 'LtszCommConfigFile' : undeclared identifier I dont know why this happen ?, i already declare LtszCommConfigFile identifier but still i got that error this is my compl...
_T is for string literals only (e.g. "hello world"). You cannot use it on variables. _T and TEXT and TCHAR and LPCTSTR etc is ancient history, used in the 1990s when people wanted to write code that worked on both Windows 95 and Windows XP. There is no reason at all to use them in modern code. Instead use char and rela...
65,286,678
65,287,030
make_unique cannot access private constructor in static member
My class has the following structure: class S { public: S() {} }; class T { private: std::unique_ptr<S> a; T(S); public: static std::unique_ptr<T> make_item() { std::unique_ptr<S> s_instance = std::make_unique<S>(); return std::make_unique<T>(std::move(s_instance)); } }; How...
As proposed by yksisarvinen in the comments, a way to solve this is to just replace make_unique<T> by std::unique_ptr<T>(new T(S)). class S { public: S() {} }; class T { private: std::unique_ptr<S> a; T(S); public: static std::unique_ptr<T> make_item() { // Create S std::unique_pt...
65,286,811
65,286,973
C++ : I have two array where the first and last element have the same memory adress
I have a problem issue with adress memory of an array. I have an array A[4], and an array B[4]. I notice that when I print &A[0] and &B[4], these two have the same adress memory. I don't know why and how to fix it. This is my code in c++ #include < iostream> int main() { int a[4]; int b[4]; for (int i=0;...
This is because a,b are local variables and pushed to stack sequentially i.e b is pushed after a. So when you print address of b[4] (just out of boundary of array b, as b[3] is the last item of b) it actually pointing to the address of starts of array a, i.e. a[0].
65,286,874
65,287,090
non-standard syntax; use '&' to create a pointer to member C++
I have a problem running my small piece of code. I have a vector who reads in temperature from User Input. I want to process the data a bit. Giving out which kind of day it was (hot day, summer day, etc...) and which day was the hottest. But everytime I want to get the maximum temperature with the function maxNumber I ...
First of all begin() and end() are method, so you're getting that error because you're trying to reference a function so it should require an address operator. Second is begin() and end() return an iterator and not an index, and you're clearing trying to access like index. Third thing is you're always returning after t...
65,286,930
65,287,010
How can I fix this [Error] cannot convert 'float [6]' to float in assignment
This is my code below, I'm having an error. ([Error] cannot convert 'float [6]' to float in assignment.) I don't know what to do or what to put in profit... My goal is to put the highest expenses, highest profit, and lowest profit below. but I'm having this kind of error. #include <iostream> #include <string> using na...
highExp = expenses; in this line highExp is a float, and expenses is a float[6], hence you are trying to assign a float array to a float which is invalid. Additionally for (int i=0; i <=6; i++ ) { will cause errors as sales[6] is not within sales, as the start of sales is sales[0] and ends at sales[5], same with expens...
65,286,957
65,290,535
How should I compute the null space of a rectangular sparse matrix over GF(2) in C/C++?
UPDATE: I ended up not using Eigen and implementing my own GF(2) matrix representation where each row is an array of integers, and each bit of the integer represents a single entry. I then use a modified Gaussian Elimination with bit operations to obtain the desired vectors I currently have a (large) rectangular sparse...
Let's call the matrix in question M. Then (please correct me if I'm wrong): GF(2) implies that M is a equivalent to a matrix of bits - each element can have one of two values. Arithmetic on GF(2) is just like integer arithmetic on non-negative numbers, but done modulo 2, so addition is a bitwise XOR, and multiplicati...
65,287,135
65,287,317
Return typename using function, template metaprogramming or any other solution
I am writing a caching library as a node-addon to be used as a universal cache across node clusters, and am using boost::message_queue to pass data from one process to another, but I want to support transfer of types, so I have managed to serialize and get typenames of the data being transferred using std::is_same so n...
You can't determine a compile-time type at runtime, and a template parameter must be known at compile-time. (Note that the example you found does not involve any runtime information.) The best you can get is pretty much the reverse of the serialization, dispatching to an explicitly instantiated function template for re...
65,287,323
65,288,242
Strange default empty constructor on a virtual inheritance behaviour on GCC
I have the following situation of a Derived class with virtual inheritance to a Base class in my code: class Base { int x; public: Base(int x): x{x} {} virtual void f() = 0; }; class Derived : public virtual Base { public: Derived() = default; }; class Concrete: public Derived { public: Concret...
Standard says (latest draft): [class.default.ctor] A defaulted default constructor for class X is defined as deleted if: X is a union that ... [[does not apply]] X is a non-union class that has a variant member M with ... [[does not apply]] any non-static data member with no default member initializer ([class.mem]) i...
65,287,737
65,287,800
unlock of unowned mutex windows debug build
I am trying to port my existing Windows code to common code that works for both Windows and Linux. Replaced CRITICAL_SECTION with std::mutex. The code fails with the error: "unlock of unowned mutex". This happens only with debug build and not with Release build. Here is sample code where the behavior is observed: #incl...
The point of std::unique_lock is to lock a mutex when constructed, and to unlock it when the unique_lock goes out of scope. You can get the unique_lock to unlock the mutex early with unique_lock::unlock(), though this is an uncommon thing to need; otherwise you should let it do the unlocking itself. As your code stands...
65,287,801
65,287,911
How to convert value of std::variant to std::string using std::visit
I want to convert value of std::variant to std::string, but this code doesn't work: using AnyType = std::variant <bool, char, integer, double, std::string, std::vector <AnyType>/*, Object, Extern, InFile*/>; struct AnyGet { AnyGet() {} std::string operator()(std::string& result, const bool& _ctx) { return _ct...
A working example: using AnyType = std::variant<bool, char, int, double, std::string>; struct AnyGet { std::string operator()(bool value) { return value ? "true" : "false"; } std::string operator()(char value) { return std::string(1, value); } std::string operator()(int value) { return std::to_string(value...
65,287,930
65,288,606
how can i call talib macd in c++?
i can use talib MACD function correctly in python, but it failed in c++. talib is easy to use in python, i can use it as: MACD(close, 12, 26,9) # close is a pandas series but when i use it in c++, it confuses me about the params. I have a function which update one close price for one time, so i save the close price se...
endIdx is the last index, not the size. Hence, you need to call it as: TA_MACD(..., close_price.size() - 1, ...);
65,287,981
65,294,796
How to access derived class member function using Base class function?
I am trying to design a parking system (Low-level Design ) Some classes behave like this. class Vehicle { public: int entryTime; int exitTime; virtual void leaveParking(Vehicle*); virtual int getChargePerHr(); //virtual void getChargePerHr() = 0; Vehicle()...
Problem Here: void Vehicle::leaveParking(Vehicle* v) { ... } You're not able to access Car::getChargePerHr() because v is a Vehicle not a Car. Clearly you're attempting to achieve polymorphism since it appears you want derived classes of Vehicle to perform the same actions when they leave parking. Solution Declar...
65,288,044
65,306,815
Generating TFRecord format data from C+
I'm trying to use TFRecord format to record data from C++ and then use it in python to feed TensorFlow model. TLDR; Simply serializing proto messages into a stream doesn't satisfy .tfrecord format requirements of Python TFRecordDataset class. Is there an equivalent of Python TfRecordWriter in C++ (either in TensorFlow ...
It turns out tensorflow::io::RecordWriter class of TensorFlow C++ library does the job. #include <tensorflow/core/lib/io/record_writer.h> #include <tensorflow/core/platform/default/posix_file_system.h> #include <tensorflow/core/example/example.pb.h> // ... // Create WritableFile and instantiate RecordWriter. tensorf...
65,288,624
65,289,221
How to initialize union in struct with C++20 designated initializer
I am trying to initialize struct sigaction (from sigaction.h) using C++20 designated initializers, but there are compiler errors. As this is part of a larger program, I created a short example: #include <stdio.h> #include <unistd.h> #include <signal.h> void onSIGINT(int signal, siginfo_t *siginfo, void *context) { ...
The problem is that sa_sigaction is a macro, defined to __sigaction_handler.sa_sigaction. This means that your code expands to .__sigaction_handler.sa_sigaction = onSIGINT; this is valid C, where a named member initializer is allowed to have a complex structure, but it is not valid in C++20. You can see that by #undefi...
65,288,907
65,295,155
winsock fails to connect to localhost
For my project I am unable to debug the program so i cannot be sure as to why this error occurs. My server, which is hosted on c# is failing to connect to server on localhost. Instead of it sending back a "connection" signal to my server, it never connects, I think the code is written well and I can't see any errors, m...
You are not actually making a connection to the server. You are calling bind() to bind the client socket to a local port 55480, but that does not create a connection. You need to instead call connect() to connect the client socket to the remote port 55480. Also, your SendData() is coded wrong. It is telling send() t...
65,289,167
65,289,257
Returning rvalue references
I've seen other posts regarding this but I'm still quite a bit confused regarding this. const std::string& func(std::string&& ref) { return ref; } int main(void) { const std::string& r=func("E"); std::cout << r << std::endl; } Now this should technically be UB, I'm returning a reference to "E" which should be des...
However, no warning from clang or g++, perhaps I am missing something? Only thing that you're missing is the fact that compilers are not guaranteed nor required to warn about undefined behaviour and generally are not able to do so. Is this not UB after all? The behaviour of the program is undefined. Lack of a warni...
65,289,739
65,294,859
OpenCV "not a member of 'cv'" errors while trying to compile some code
I was trying to compile the following visual odometry library: https://github.com/HKUST-Aerial-Robotics/VINS-Mono but in attempting to do so with OpenCV 4.0, I'm getting several "error: 'x' is not a member of 'cv' errors. There were several of these involving things like RGB2GRAY that I was able to Google and figure ou...
Found my solution after some more Googling: CV_SHAPE_CROSS --> cv::MORPH_CROSS CV_SHAPE_RECT --> cv::MORPH_RECT CV_TERMCRIT_EPS --> cv::TermCriteria::EPS CV_TERMCRIT_ITER --> cv::TermCriteria::MAX_ITER
65,290,019
65,291,230
ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second
Why is this ambiguous? // In class declaration template<typename T> class threadsafe_list { void for_each(std::function<void(T&)> _consumer); void for_each(std::function<void(const T&)> _consumer) const; } // Calling for_each threadsafe_list<bool> list; std::function<void(const bool&)> print = [](const bool& ...
There are two possible overload resolutions for the first call, each involving a conversion: Choose the first overload, convert std::function<void(const bool&)> → std::function<void(bool&)> Choose the second overload, convert threadsafe_list<bool>& → const threadsafe_list<bool>& Neither conversion is better than the ...