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
64,596,004
64,596,217
What is the type of the following?
typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, TestStringAllocator<wchar_t> > TestString; So is it a "basic_string" or is it a "wchar_t" Please let me understand, I need to do conversions and don't know what the type of TestString is. Thanks.
In this case TestString is just std::wstring with custom allocator defined TestStringAllocator. Most probably this is used to inspect how allocator works and how std::basic_string is using that. Some time ago I used something similar to investigate if std::string_stream is optimized (is not). Since you didn't provided ...
64,596,090
64,596,146
Strange output after cast removing constness in C++
After encountering some cast and const issues, I have simplified my problem in a very small code snippet: #include <iostream> using namespace std; int main() { const int a = 2; const int* p = &a; int* p_bis = (int*)p; *p_bis = 42; printf("\na = %d", a); printf("\n&a = %p\...
While it is perfectly valid to cast a const pointer to a non-const one, and it also is valid to modify data through that pointer if the data was not originally defined as const, it is invalid to do so if the data was originally defined as const (which is your case). Changing the value of a variable that was defined as ...
64,596,117
64,599,569
Android Studio is bundling stubbed library into the APK
I am using Android Studio to build a native C++ project. There is a dependency library (let's call it lib.so) which is required to be linked with the JNI library to resolve few of its symbols. However, I do not want this library to be bundled into the APK as this is a stubbed library and to be used only for the linking...
Try to use find_library for that. Put your prebuilt lib.so (bad name at least liba.so) to some path and add it to CMAKE_FIND_ROOT_PATH: list(APPEND CMAKE_FIND_ROOT_PATH ${PREBUILT_LIBS_DIR}/${ANDROID_PLATFORM}/${ANDROID_ABI}/a) example how it could look: ~/my-proj/prebuilt-libs/android-28/x86/a/lib/liba.so Then find ...
64,596,126
64,596,313
std::function to C-style function pointer
I'm using a library written in C. This library accepts callbacks like this: int(*)(int arg, void* user_param) Is it possible to create a std::function<int(int, void*)> and pass it to this library as a callback? I know that std::function has a target method which returns the address of the stored function, but as far a...
You can use lambda functions with C-style function pointers, just not using std::function. Lambdas that don't have any capture are convertible to a functions pointer: using callback_t = int(*)(int arg, void* user_param); void set_c_callback(callback_t, void* user_param); // ... void foo() { set_c_callback([](int ...
64,596,249
64,596,264
Power using recursion c++
I wrote this code for calculating power of a number using recursion and it works with integers but when i pass a float, it doesn't give me an error it returns the wrong value. #include<iostream> using namespace std; int powerRec(float num, int power) { if(power<=0) return 1; return num*powerRec(num, --...
The return type of powerRec is int, so the returned value will be truncated. Use return type float to do calculation properly.
64,596,548
64,597,311
How do I create a helper function that can access a private member and operatore += sign?
My question is at the bottom. I am creating a module for a Mark to encapsulate between 0 and 100. I have a few operator and conversion overload functions so far: class Mark { int mark; public: Mark(); //constructor ~Mark(); //deconstructor Mark(int value); // mark is created using int va...
Your implicit casting is weakening your type. It is so weak, that it has now become ambiguous. Since you allow a Mark to be automatically converted into an int, you may as well just use an int and create stand-alone functions that manipulate ints instead of Marks. If you insist to manipulate Marks, you should create a ...
64,596,606
64,599,255
gcov not working with pthreads, WSL-2, Clion
Background: This seems to work fine if I don't use any threads or just spawn 1 thread, which makes this all the more confusing. Clion Project here Problem: I set up a basic example project that starts 2 threads and does some printing to the console from main thread, thread 2, and thread 3. #include <iostream> #include ...
Needed to do threadObj.join() and threadObj2.join(). So code looks like: int main() { std::cout << "Hello, World!" << std::endl; std::thread threadObj(thread1); std::thread threadObj2(thread2); for(int i = 0; i < 10000; i++) { std::cout<<"MainThread"<<std::endl; } threadObj.join(); ...
64,596,748
64,597,396
Can you define a class static constant at namespace scope with auto?
In c++, it's possible to define const static data members from within the class definition without defining it at namespace-scope. Doing so is valid so long as the constant is not ODR-used; this practice effectively does not provide a storage-backing in the translation-unit. For example: #include <cstddef> // std::size...
despite the fact that decltype(my_string::npos) is already known by this point Well.. so just use it! #include <cstddef> // std::size_t class my_string { public: static const auto npos = static_cast<std::size_t>(-1); }; const decltype(my_string::npos) my_string::npos; // all fine!
64,597,203
64,598,360
Why does QGraphicsRectItem object stay at coordinate (0,0) regardless of the coordinates provided explicitly?
I'm new to Qt5 and tried all the solutions provided online but most of them are from 2011. Am I missing something? It reluctantly stays at (0,0). File Name: sll.cpp sll::sll(QWidget *parent) : QWidget(parent), ui(new Ui::sll) { ui->setupUi(this); scene = new QGraphicsScene(t...
Cause QGraphicsView aligns the scene by default in the middle. A graphics scene has dimensions, e.g. 1000x800 px. QGraphicsView::setSceneRect or QGraphicsScene::setSceneRect, which is equivalent, sets these dimensions. When one of those methods is not used explicitly, Qt determines the dimensions automatically, based...
64,597,499
64,599,007
P0847 deducing this - can it allow a generic clone without a need for CRTP?
P0847 proposes the possibility of using explicit this parameter for member functions. Among other great goodies that this proposal brings, there is also the great new possibility for CRTP without C, R and even T. A common practice for implementing a generic clone in C++ is based on CRTP, see for example this SO post. G...
template deduction only uses static type, whereas Clone need dynamic type, and so virtual. P0847 mostly allows to transform template <typename T> T* Foo(const T& obj); // With Obj base of T into template <typename Self> Self* Obj::Foo(this const Self& obj); What you could do though is simplify the covariance with sma...
64,597,759
64,597,941
Passing Derived Objects as Argument
I have a Constructor for a class Student like this: Student(ISubject subject, IStudy study); With ISubject and IStudy being abstract classes. I then created classes that inherited from the abstract class. (E.g Maths : ISubject and Calculus : IStudy) When I want to pass in an object of the derived class into the contru...
If your classes ISubject and IStudy are abstract classes, you cannot create objects of these types according to the rules of the language. But when you write (ISubject subject, IStudy study) it tells that you want pass objects of these types as function arguments, but it isn't possible since these objects cannot exis...
64,597,796
64,597,923
Moving a range-based iterator forward from within the loop
I'm iterating over a multidimensional vector<vector<float> > using a range-based for loop. So, something like this: for(vector<float> &row : myVector){ // Do some stuff } I'd like to be able to move forward some fixed number n rows based on conditionals within the loop. I could, of course, do something like: for...
There is some context missing, so I'll just blindy trust what you write: You know how to do your special increment with an iterator based loop along the line of: for(int i = 0, j = 0; i < rows && j < columns; ++i, ++j){ // Do stuff } But also you have a range based loop: for(vector<float> &row : myVector){ // ...
64,598,056
64,598,135
A lot of : "error: no match for 'operator>>' (operand types are 'std::basic_ostream<char>' and '<unresolved overloaded function types>')
This is the code : #include <iostream> using namespace std; int main() { cout << " SSSSSSSSSSSSSSS" >> endl; cout << " SS:::::::::::::::S" >> endl; cout << "S:::::SSSSSS::::::S" >> endl; cout << "S:::::S SSSSSSS" >> endl; cout << "S:::::S" >> endl; cout << "S:::::S" >> endl; cout << "...
When writing using the extraction or insertion operator (e.g >> or << respectively) you need to basically point it where you want the flow to go, and not change the flow for that whole statement, to put it in simple terms, in your case you want both insertion/extraction operators that you use to be facing like so << an...
64,598,253
64,598,328
++ pre-fix operator overload is not working with <<
Bit of a new C++ dev here. I have a class Rational used to represent rational numbers and allow the user to perform arithmetic and relational operations on them. I overloaded all the operators and they're all working properly except when I try to combine the ++/-- pre-fix operators (e.g., --Rational) or the +/- unary o...
The second argument of your operator<< binds to an l-value reference: ostream& operator <<(ostream &outs, Rational & num) // ^ But all your operators return r-values. So for example, when you do: cout << -num; you are trying to bind an l-value reference to an r-value, which i...
64,598,366
64,598,526
Pass a sentence to a char array in c++
How do i take a sentence, with spaces and upper and lowercase letters, as an input to a char array, e.g char arr[]. Is there any way to do this without using the cstring library? #include <iostream> using namespace std; int palindrome(char arrC[], int indexS, int indexE) { if(indexS>=indexE) return ...
Simple way to do this, is to use std::cin.getline(), use it as follows: First argument to it should be the c style string array you want to store the input in. Second argument passed in should be the maximum number of characters to write to 'your first argument' (including the terminating null character). Here is an ...
64,598,755
64,602,123
Template class type alias failing substitution in member declaration
Assume you have a templated class like this: template <typename type> class Object { using length_t = unsigned int; template <length_t length> void put(type (&)[length]); }; and you declared a put(...) method in it like so. How do you go about declaring that put(...) method outside the class? Here's one appr...
I think it's a compiler bug, or further more, a defect in standard. your code actually has NO problem, and is accepted by MSVC. and if you put the definition inside the class, no compiler will think it's ill-formed. I have posted a question that is similar to this. and I get the result that, CWG2, the ancient issue tha...
64,598,823
64,609,531
How do I fix these encodings?
I'm making a program that captures all the keys the user enters & saves them to a file. There's one problem I'm really confused with. Sometimes when I open the text file it seems like it's ALL in Unicode. I typed the Russian characters and they're correct. However, sometimes the file is in a normal form. This convert...
When you use the writeScannedKey function, the following codes all write two bytes to the file WriteFile(file, text, wcslen(text) * sizeof(wchar_t), NULL, NULL); But when you use the writeLog4 function, you only write one byte at a time: WriteFile(file, (LPCVOID)text, sizeof(text) / sizeof(char) * sizeof(char), NULL,...
64,599,154
64,599,206
How can I forward declare an array inside a namespace in c++
I've been trying to find out how I can use namespaces properly. I want to use a namespace, but not have to define it in the header file. I am not sure how I can do this with an array inside the namespace. I either get an "already defined symbol" error, or I get told that the namespace has not been declared. I have trie...
Same way as in global namespace: // .h namespace foo { extern int array[5]; } // .cpp namespace foo { int array[5] = {1, 2, 3, 4, 5}; }
64,599,451
64,599,471
How to pass arguments to bash script from a cpp program
I've forked a child process which then calls a bash script using execv, the way i'm passing command line arguments to the script, It does not print first argument on doing echo $1 inside the script. std::string s = std::to_string(c_no); char *args[] = {(char *)s.c_str(), NULL}; pid_t pid = fork(); if(pid == 0){ ...
First argument passed to a program is its name so currently your number ends up in $0. args should be: char *args[] = {"./ckpnt.sh", (char *)s.c_str(), NULL};
64,599,845
64,600,058
std::vector<T>::insert and std::move_iterator<T> how they work together?
I am not exactly sure about this, so please explain me how does it work. Let's consider following code. std::vector<std::string> vec {}; void add (std::vector<std::string>&& v) { using iter = std::vector<std::string>::iterator; vec.insert (vec.end (), std::move_iterator<iter> (v.begin ()), ...
[Does] the implementation of std::vector<T>::insert() distinguish between "normal" and "move" iterators? No. The "magic" happens in move_iterator::operator*(): it returns an rvalue reference. Therefore, when insert() fills in a newly allocated element, it prefers the move-constructor, and for this reason moves the va...
64,600,160
64,601,397
How to have QTreeWidgetItems of different heights in a QTreeWidget utilizing QStyledItemDelegate?
NOTE: it turned out that the problem was not due to the implementation of QStyledItemDelegate, but it was the fact that in the constructor of MyTreeWidget I was calling setUniformRowHeights(true). The code below and the solution posted by @scopchanov are valid and working QTreeWidget has a protected method called itemF...
Solution I would approach this problem in a different (simpler) manner: Define an enumeration for the different item sizes, e.g.: enum ItemType : int { IT_ItemWithRegularPadding, IT_ItemWithBigPadding }; When creating an item, set the desired size in its user data, depending on its type, e.g.: switch (t...
64,600,448
64,600,670
Check if two types can be aliased
I have a public API function (in a library header) that accepts a struct foo &, and that function's internal implementation calls a third-party dependency's function that requires a struct bar *. I do not want to pull in the third party dependency into the public header as the library will be distributed in binary form...
reinterpret_cast<bar*>(&f) is always UB because of strict-aliasing. Without strict-aliasing, you could use c++20's std::is_layout_compatible, but there isn't any compiler support for that. You could use a hack like this: template<typename T, typename U> constexpr bool is_same_member_type(T foo::*, U bar::*) { retur...
64,601,055
64,601,096
Please help me with a simple c++ std::time_t question
I am trying to get the current time and subtract a set amount of seconds to find a time in the past. See my code example below... #include <ctime> #include <stdio.h> void main() { uint32_t sec = 100; std::time_t t = std::time(NULL); std::time_t mt = t - (std::time_t)sec; struct std::tm* currTime = std::loc...
This is explained in the manual page for localtime(3): The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. Your localtime always returns a pointer to the same internal object, and each time it gets called it overwrites its...
64,601,065
64,601,132
How can I use header for C that has typedef enum, when converting code to c++?
I need to use some C code in a C++ project but I'm getting build errors for one of the c original's .h files. The error has to do with some typedef enum parts, which I undestand that c and c++ handles differently. (or c++ doesn't do) Here is a minimal version of that c style .h: (there's several more similar entries in...
One trick you can do is defining an overloaded operator | for enum types that are intended to be used as bitmasks like this: ILCLIENT_CREATE_FLAGS_T operator|(ILCLIENT_CREATE_FLAGS_T a, ILCLIENT_CREATE_FLAGS_T b) { return static_cast<ILCLIENT_CREATE_FLAGS_T>(static_cast<int>(a) | static_cast<int>(b)); } This will ...
64,601,394
64,601,724
Head pointer doesn't contain child nodes in Binary Tree
I'm copying a binary tree and I'm having an issue where my root pointer of the new tree ends up only containing the 1st node that is to be copied, and no others. I believe the issue has something to do with the fact that when I pass in the pointers in the recursion in the helper function, for some reason they are not b...
You have a couple of problems here. First, ref and first_time are serious flaws and you should avoid writing code with such global state. It is not reentrant, and not thread-safe. Second, you're trying to write to the t2 pointer and change the caller's pointer to that value. However, you're passing in a copy of t2 so...
64,601,546
64,601,905
Are gltf animations of type vec4 ever not quaternions?
I am trying to make my own gltf loader, and I am dealing with animations. I have the first basic triangle example that makes it rotate. One thing I noticed is that these are the defined types for a gltf file: #define TINYGLTF_TYPE_VEC2 (2) #define TINYGLTF_TYPE_VEC3 (3) #define TINYGLTF_TYPE_VEC4 (4) #define TINYGLTF_...
A glTF file does specify which properties are affected by each animation channel, but you would need to look it up in the reverse order. In pseudocode: for anim of gltf.animations for channel of anim.channels sampler = anim.samplers[channel.sampler] print "Accessor #" + sampler.output + " modifies " + channel...
64,602,475
64,617,337
how to print value returned by template member function in gdb/lldb debugging
There is a template member function named at in class cv::Mat of OpenCV: //definition of at template<typename _Tp> inline const _Tp& Mat::at(int i0, int i1) const{ // ... } //my codes cv::Mat eyePts_left; // ... if(std::max(eyePts_left.at<float>(0,0),eyePts_left.at<float>(16,0)) > eyePts_left.at<float>(61,0)){ /...
The current debug information for template functions, and templated entities in general is awkward because it only describes instantiations, and not templates as abstract entities, so templated functions just show up in the debug info just as functions with angle brackets somewhere in the names. That makes it tricky t...
64,602,809
64,602,928
Checking if a string contains more than just keywords C++
Thank you for clicking on my question. After countless hours of searching, I have not come across a solution and its quite difficult to search for something you don't know how to properly phrase in a search. Please help me out, I would appreciate it. The data of the string would be like: std::string keyword 1 "Hello"; ...
You can remove all instances of these keywords from your data and see what's left. It's not terribly efficient but shouldn't matter for reasonably sized inputs. bool contains_more_than(std::vector<std::string> const& keywords, std::string sample) { for (std::string const& keyword: keywords) { size_t pos; whil...
64,603,583
64,603,645
How to "whitelist" template specializations?
I am trying to create a type safe abstraction for registers. Shortly explained a register can contain a field of bits which have some special meaning and the bits in question can usually be either set to a range of valid values (specified by an enum) or to any integer value (if so specified). The fields in a single reg...
How about setting the template argument to auto in both allowed_type and set? template<auto value> struct allowed_type; template<> struct allowed_type<Definitions::kField0> { using type = Field0Values; }; template<auto maskValue> constexpr void set(typename allowed_type<maskValue>::type) {} Alternatively, if you...
64,603,674
64,605,074
Parsing the string and populate the map
Consider this: command1 -keep -path { {path1} } { {./input.doc} } I wanted to parse the above line and collect the information into a map where value would be contents of -path option and key would be everything else. The format of the string would be fixed that after -path there would be two opening and two closes b...
With regex, you might do: std::string s1 = "command1 -keep -path { {path1} } { {./input.doc} }"; std::regex pattern{R"((.*)-path \{ \{([^}]*)\} \}(.*))"}; std::smatch obj; if (std::regex_match(s1, obj, pattern)) { std::string key = obj[1].str() + obj[3].str(); std::string value = obj[2].str(); // ... } ...
64,603,707
64,605,060
How to remove protruding part of a square shape in an image?
]2 I would like to get a square shape from the right image above. But when I try to get it, it also includes other protruding parts because they have similar color. Are there any solutions to get the result like below? (The square lines are not 100 % straight. They are little distorted.) This is the code I wrote. cv::...
For this specific image my pipeline would be very simple: Binary threshold the image with a fixed threshold. The rectangle is quite dark compared to the rest of the image. Morphological opening with a large rectangular kernel to get rid of the "noise". To get a perfect rectangle, determine the bounding rectangle of th...
64,604,121
64,604,602
Varadic and template template parameters and partial specification for tree node class
As the new standard gains popular, programmers are able to use template template parameter along with varadic template to define a class template that looks like: /* C++ code */ template <template <class...> class container = std::unordered_multimap, typename... args> class basic_node { public: container<args.....
If your concern is about the "recursion" with struct S : C<S /*, ..*/>, it is fine. it is the idiom Curiously_recurring_template_pattern (CRTP).
64,604,383
64,604,868
How can I create a square 2d array of size NxN where N is supplied by the user and populated with random numbers at a certain range?
My goal is for the user to input a number from the range 3 to 8 and it will a create matrices based on that size and then fill it with random numbers from the range of -12 to 8. for example if the user enters 3 it should display : 9 1 -4 4 2 -6 -11 5 8 I think I've got the concept right but the variable length array c...
You probably should use a vector of vector of ints, using std::vector. #include<iostream> #include <random> #include<time.h> #include<iomanip> #include <vector> #include <map> using namespace std; // generate the array with random numbers void array_gen(vector<vector<int>> & array, size_t arraysize) { array.r...
64,604,656
64,607,855
How could pass an object function by reference to another library funcion that needs a funcion with the same args and the same returns
I have an example of my real problem. I use a C library that have a function that needs a pointer fucntions to be called laters. But I need that call would be an object function, but I cant to do this: class MyClass{ static int numberObjects; //... public: MyClass(int num){ numberObjects++; //... } v...
To call a member function an object is required, but your C function allows you to pass an int, rather than void* which you could use to pass the pointer to the object. Hence, you need to use that int as an index into a global array of pointers to your objects to locate the object: MyClass* objects[2]; void callback(i...
64,604,693
64,609,016
C++20: Automatically generated operators are unreferencable in derived classes?
I noticed something rather strange while writing C++20 related to spaceship operators. As I understand, since C++20, comparison operators are automatically generated by the compiler. However, I have encountered an interesting problem with this automatic generation of operators. In the code below, I am trying to define ...
As I understand, since C++20, comparison operators are automatically generated by the compiler. However, I have encountered an interesting problem with this automatic generation of operators. This is not correct. The comparison operators are not generated. Comparison expressions are rewritten. That is, given: struct ...
64,604,915
65,017,359
Hyperscan scanning in too much time
I am using a database that has a ten million lines signature to match PCAP packages. I finished the code with c++. It cost 100 seconds in matching one 200m PCAP package. Well, as I know, someone finished the project , and that cost only several seconds in matching one 200m PCAP package. This is my steps: all my patt...
I figured out the problem, the cause of the slow is because I mixed too many different patterns of flags in my database. So I split the pattern by different flags, and it works amazingly. Thank u guys.
64,605,810
64,614,388
Code doesn't run when instancing multiple objects from the same class, but does work when instancing objects from a duplicate class with the same code
Solved! The issue a similar name in my bootscript my main source file. Look at the answer for more details. I've had this mind-boggling error for weeks now. I am compiling for the GD32V chip. What happens is, I have the following class, which abstracts the gpio pin output for the chip: class pin_out : public hwlib::pi...
I finally solved it! The one thing I didn't expect to be the issue, was the issue. Basically I had the linkerscript calling the bootscript. I grabbed these two files from a blogpost. However, the linkerscript called the bootscript's function, which was named 'main'. As my own function in my source file was also called ...
64,606,020
64,606,087
Using template type with default type without angle brackets
I was playing with this example code from https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution: #include <random> #include <iostream> int main() { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engin...
What is this feature (being able to omit angle brackets) called and in what version of C++ was this introduced? This (somewhat controversial) feature is called class template argument deduction (short: CTAD) and has been introduced with C++17. You can read about it here. If you compile this snippet with e.g. -std=c++...
64,606,120
64,606,590
Largest floating point value that can be squared
I have a function that takes in an optional distance parameter dist, but my algorithm works with squared distances. If the user does not specify any value, I want dist to be as large a number as possible. Result foo(double dist = std::sqrt(std::numeric_limits<double>::max())) const; Is the code above safe, or will it ...
If you're careful, you can use std::numeric_limits<double>::infinity . It will do the right thing in comparisons and if you square it, it remains infinite.
64,606,327
64,606,755
Use default parameter for templated function
I have two functions which look very similar to me : template <typename Predicate> vector<int> FindTopItems(const string& query, const Predicate& predicate) const; vector<int> FindTopItems(const string& query, ItemStatus status = ItemStatus::In...
You can set the default value for predicate to ItemStatus, then make a helper class that returns your default value. #include <iostream> #include <vector> #include <string> enum class ItemStatus { Initial }; template <typename T> auto defaultValue() { return T{}; } template <> auto defaultValue<ItemStatus>()...
64,606,334
64,606,566
Dynamic array with new in c++ - cout array[num]
I am trying to diplay the value stored inside the array but only the value ofarray[0] = 13; is shown. For array[1] = 4; it prints out an adress. I read the introduction of new but that doesnt helped. What is wrong? std::cin >> _size; //_size > 2 int* array; array = new int[_size]; array[0] = 13; ...
Your output is weird, try this code and compare it to your entire code, you will understand: int *array; unsigned _size; std::cin>>_size; array=new int[_size]; array[0]=13; array[1]=4; std::cout<<array[0]<<'\n'; std::cout<<array[1]; delete[]array;
64,606,644
64,606,687
overloading operator ostream for template class in c++ not working
so i have this template class: template<class T = int, unsigned int SIZE =2> class FixedPoint { public: explicit FixedPoint(T dollars = 0); FixedPoint(T dollars, T cents); friend std::ostream& operator<<(std::ostream& os ,const FixedPoint& price); private: static lon...
As the error message said, the friend declaration declares a non-template operator<<, but it's defined as a template, they don't match. You can make the friend declaration referring to the operator template, e.g. // forward declaration template<class T = int, unsigned int SIZE =2> class FixedPoint; // declaration temp...
64,607,057
64,607,226
Do unsigned integers get promoted to signed? What is the type of expression (uint16_t)-1 * (uint16_t)-1
For uint32_t and uint64_t results are expected, but promotions for uint8_t and uint16_t are strange. Tests on c++14/c++17, gcc and clang, 64-bit linux, sizeof(int) == 4. #include <cstdint> using namespace std; static_assert( uint8_t(-1)*uint8_t(-1) == 0xfe01); // OK, but why not 1? static_assert( uint8_t(-1)*uint...
it looks like uint8_t is promoted to uint16_t, but uint16_t is promoted to signed int. uint32_t is not promoted uint64_t. No, that's not correct. Only types narrower than int are promoted to int, so if int has more than 16 bits then both uint8_t and uint16_t will be promoted to int. In the case of uint8_t(-1)*uint8_t...
64,607,062
64,607,197
Error in implementation of map.find() for map of pairs C++
I have a map like this map<int,pair<int,int>>diff; I am using it like this int temp; for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { temp=v[j]-v[i]; if(temp>0) { if(diff.find(temp)!=diff.end()) { pair<int,...
The error message explains exactly what is wrong. You are trying to initialise a pair<int, int> with an decltype(diff)::iterator. The simple fix is to dereference the result of find, or to use at pair<int,int> a=diff.at(temp); Note that this is a copy, not a reference, so the following actions are discarded. A better ...
64,607,684
64,607,866
Check if 1/n has infinite number of digits after decimal point
If a user enters a number "n" (integer) not equal to 0, my program should check if the the fraction 1/n has infinite or finite number of digits after the decimal sign. For example: for n=2 we have 1/2=0.5, therefore we have 1 digit after the decimal point. My first solution to this problem was this: int n=1; cin>>n; if...
Your code tries to make use of the fact that 1.0/n is not done with perfect precision, which is true. Multiplying the result by n theoretically should get you something not equal to 1, true. Sadly the multiplication with n in your code is ALSO not done with perfect precision. The fact which trips your concept up is tha...
64,607,718
64,610,106
Order of initialization of static member of explicitly instantiated template and another static variable
This is the simplified form of my problem (based on a real library): // class template with static member variable: template <typename T> struct X { static std::vector<T> v_; }; // definition of that static member variable: template <typename T> std::vector<T> X<T>::v_{}; // explicit instantiation of the class tem...
[basic.start.dynamic]: Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, is partially-ordered if the variable is an inline variable that is not an implicitly or explicitly instantiated specialization, and...
64,607,860
64,734,144
Initialization of std::initializer_list<std::string_view>
The following program #include <initializer_list> #include <string_view> inline constexpr std::initializer_list<std::string_view> s = { "" }; int main() {} compiles with current Clang (12.0.0) but not with current GCC (11.0.0 20201028). With GCC it produces the error prog.cc:4:67: error: modification of '<temporary>...
Yes, you are correct. It is a GCC bug.
64,607,939
64,610,369
Multithreaded Program slower than singlethreaded
I have created a very simple test program that calculates c*A of some scalar c and matrix A. You can either run it online here here or paste the following code in your favorite text editor: #include <iostream> #include <time.h> #include <chrono> #include <thread> void fill_rand_matrix(double* mat, int n){ for...
I'm not knowledgeable enough to give a definitive answer, but as there's no answer so far I'll do my best: Short answer: Multiple sequential iterations over an array of size L (where L is bigger than the size of your largest cache) won't be able to take advantage of any of the caches for a new cache-line access of the...
64,608,543
64,608,641
Control reaches end of non-void function in c++
I wrote the following code to find a maximum of four numbers given by user: #include <iostream> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max_of_four(int a, int b, int c, int d){ if(a>b){ if(b>c){ if(c>d){ return a; } ...
There's flaw in your code actually. There will be many cases where there is value returned. HINT: From a,b,c,d, first find greatest of a,b then find the greatest of c,d. Then compare the 2 answers. This is much easier for you to understand.
64,608,614
64,608,738
C++ How to return dynamically allocated array
I'm getting no matching function for call to error how can I fix this without using vectors. This is my header, I'm getting the error at fList method part in cpp. class Flight{ public: Flight(int fly,int rw,int st); ~Flight(); Flight* fList(int& sizeOfArray); private: int FlightNumber; ...
So int* flightArray; should be Flight* flightArray; Your code is allocating an array of Flights but your variable is declared for integers not Flights. Plus as pointed out by @MikeCAT you need to default constructor for Flight if you are going to allocate them with new[].
64,608,805
64,808,274
std::is_move_assignable_v false though there is a move assignment operator
Context: I've a class DLXMatrix with some attribute which are vector of some local class called Header. Each Header holds some pointer on some other Header which refer to elements of the same vector (think of a structure which is both a vector and a doubly linked list). As a consequence, I cannot use the default copy c...
I'm posting an answer following the indication of @IlCapitano. In the implementation of operator= I needed to do a copy and decided to perform it thanks to a call-by-value. So the prototype was DLXMatrix &operator=(DLXMatrix other); instead of the standard DLXMatrix &operator=(const DLXMatrix &other); This call-by-va...
64,608,846
64,616,090
How do you setup Google Test in VS 2019 from scratch?
I've been trying to set up google test v1.10 in visual studio 2019 for a really long time now and it hasn't been working, and a lot has changed as well. Most of the tutorials are out of data and Microsoft help page says to use the google test adapter but I have an already existing project that I want to add google test...
Follow this link to the T: https://www.bogotobogo.com/cplusplus/google_unit_test_gtest.php You won't have to use CMake. In VS2019, in order to get win32 static lib and console applications, in the create a new project section, select C++ in language tag, Windows in platform tag, and All Project Types in the types tag. ...
64,608,969
64,609,769
Where does my Huffman encoding method go wrong?
I am trying to code a Huffman string encoding algorithm. My solution works this way: since every letter in the string have a special binary code associated to it, search the binary tree and when a letter is found, add it to the map with binary code. (where I went wrong is here) iterate on the string, and for each lett...
You are destroying the code in prefix when you save a leaf with prefix = "", where the code is needed when dropping back down the tree and going to the next branch. You can maintain a single storage area for prefix as you have, passing it by reference. However you need to manage the length of prefix as you go up and do...
64,609,049
64,609,120
Equivalent C++ macro to Rust's include_str
Does C++ have a macro like Rust's include_str!? Macros similar to include! or include_bytes would also meet my requirements.
There's no standard way to do this. There's proposal P1040R6 for std::embed. If you want to experiment with this right now, check out https://github.com/ThePhD/embed (which is by the author of the aforementioned proposal). You'll need to patch your compiler though, so it doesn't seem very portable.
64,609,092
64,617,872
Find causing a segmentation fault
I have a shared library for library interposition with an unordered_map. The unordered_map is filled and consulted through the execution of an application (when intercepting specifics calls). If I try to find an element in the constructor of the library, it generates a segmentation fault. Here is the code for the const...
Here is the code for the constructor causing the segmentation fault: You didn't show how the stats global itself is declared, and without that your code is useless (see also MCVE). But this is almost certainly an instance of static initialization order fiasco. How can I test if is SIOF? And fix it if that's the case...
64,609,254
64,609,584
C++ return directly from operator<<
Is it allowed to directly return while we are sending to ostream? For example, instead of writing: ostream& operator<<(ostream& os, Foo foo) { os << foo.a << foo.b; return os; } Instead, can I directly write: ostream& operator<<(ostream& os, Foo foo) { return os << foo.a << foo.b; } I tried it, and it see...
The two code snippets you post are entirely equivalent. Why? Because (I'm assuming here, for the sake of argument, that foo.a and foo.b are simple data types like int) the << operator for std::ostream returns a reference to itself (see the "Return Value" section in the linked document). Thus, in your first code snippet...
64,609,530
64,609,812
C++ no instance of constructor matches the argument list, using templates
I am trying to instantiate my sarray class. sarray array(10); But I get an error saying that their is no constructor which has a matching definition. The constructor is defined in the sarray header file #ifndef SARRAY_H #define SARRAY_H template <class T> class sarray { public: template<class T>sarray(int size); ...
The template<class T> on top of you class affects the whole class. You do not need to keep adding template<class T> in front of all methods of the class. You do need to do it in the definitions of the methods, when you are writing them outside the class. So your class should become: template <class T> class sarray { pu...
64,609,544
64,611,377
Build an .exe that runs without C++ Redistributable Package
I am using Visual Studio Community 2019 C# (my interface) and Visual Studio 2017 Community C++ (.exe who is called during interface process) I need to export my project to others PC and if they do not have Visual Studio installed they are missing some dll. I know there is an option to select to free from this kind of t...
Ok i found the solution to whom it may concern, in visual studio 2017 (my C++ code) i did this : Right-click your project in “Solution Explorer”, select “Properties” from the popped menu. Then the “Property Pages” dialog opens. In the opened “Property Pages” dialog, select “Configuration Properties->C/C++->Code Gener...
64,609,976
64,610,119
Programmatic bindings in pybind11
I am using pybind11 to export a library written in c++ as a python module. My situation is perhaps a little unusual in that the c++ library already contains structures with all of the metadata of the classes I want to export. I am considering whether I could make use of this existing metadata, rather than re-entering i...
If you dig through the macros you'll find PYBIND11_MODULE expands to a bit of code that is evaluated when your library is loaded from Python. For the rest your code looks like it should work.
64,610,201
64,610,627
Boost concurrent queue non-blocking vs non-waiting
I'm reading the documentation for boost::concurrent::sync_bounded_queue: https://www.boost.org/doc/libs/1_72_0/doc/html/thread/sds.html They have a section listed: Non-waiting Concurrent Queue Operations but also a section listed: Non-blocking Concurrent Queue Operations I don't understand the difference between no...
Warning: everything below is based purely on what I read in the manual. That manual page says for non-blocking operations: The interface is the same as the try operations but is allowed to also return queue_op_status::busy in case the operation is unable to complete without blocking. Under the "Non-waiting Concurrent...
64,610,251
64,610,341
Random Name Generation Between 8 and 16 Characters
So I am trying to generate a random name between 8 and 16 characters. It doesn't need to actually spell a real name it is just a bunch of random letters. So far I have it to generate a random first and last name but they are all sizes of 12 #include <iostream> #include <ctime> using namespace std; void genID(char let...
To generate strings that have 8 to 16 letters, you will have to concatenate 8 to 16 letters. To generate random integer between A and B (both inclusive), you can use A + rand() % (B - A + 1). (quality is not considered) Try this: void genID(char letters[26]) { string firstTemp, lastTemp; int firstLen = 8 + rand...
64,610,280
64,610,323
C++ regex_replace not replacing string
I'm a newbie with C++. I'm trying to learn string replacement. I'm writing a short (supposed to be a tutorial) program to change directory names. For example, I want to change "/home" at the beginning of a directory name with "/illumina/runs" thus: #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else...
std::regex_replace does not modify its input argument. It produces a new std::string as a return value. See e.g. here: https://en.cppreference.com/w/cpp/regex/regex_replace (your call uses overload number 4). This should fix your problem: b2_dir = std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");
64,610,413
64,610,486
std::ostream Composition of Classes
We have the following situation: In Classes A and B, we have overridden the << operator. Now, we have a new class C with data members of objects of A and B. How would we override the << operator here? To be more specific, We need something like this: cout<<objectOfC corresponds to cout<<correspondingObjectOfA<<corresp...
If you already have appropriate overrides for A and B, just use them. ostream& operator<< (ostream& out, const C& obj) { out << *obj.AObject << *obj.BObject; return out; } Because operator<< returns its ostream argument, you can further condense this: ostream& operator<< (ostream& out, const C& obj) { retu...
64,610,423
64,610,543
std::vector.push_back() C++
I want to initialize a vector with alphabetical letters using push_back function. Is it the right way to do it? vector<char> v; char letter = 'A'; for(int i=0; i<26; i++) { v.push_back(letter+i); } It works. I am just wondering whether I should use a type cast letter to an int before adding i to it? Or is there a ...
Note that your code relies on a character encoding scheme that encodes the letters contiguously, like e.g. ASCII. If that assumption holds, you could create the vector using the correct size initially, and use std::iota to initialize all elements: std::vector<char> v(26); // Create a vector of 26 (default-initialized)...
64,610,568
64,905,366
conversion between float and unsigned char [4]
I am using Qt 5 to send data via serial port. The problem comes from a conversion bewteen float and unsigned char [4] with union structure. typedef union { float df; unsigned char uc4[4]; }fuc4; fuc4 t1, t2; t1 = (a+b)/c, t2 = -(a-b)/c; Both is 0 as we can have a look at t1.df and t2.df with qDebug(). Howev...
I've always done this one: float f = something; unsigned char *uc4 = (unsigned char*)&f; You don't need to go through an union for char or unsigned char, though you do for any other types.
64,610,614
64,610,639
error: no matching function for call to vector::push_back
I'm new to C++ and am trying to use pushback function to store food orders in a vector object so that the food orders can be compiled and repeated back later. But I get the error: no matching function for call to ‘std::vector::push_back(OrderEntry*&)’ when I try to use the pushback function to store the food order. #in...
OrderEntry* food_order = new OrderEntry (qty, order); orderQueue.push_back(food_order); is wrong because the elements of orderQueue is OrderEntry while you are trying to push OrderEntry* and OrderEntry don't have constructors that accepts OrderEntry*. It should be OrderEntry food_or...
64,610,833
64,611,209
How to cut flat buffers vector size?
My schema is: table Object { data: [ubyte] } I have the next code: flatbuffers::FlatBufferBuilder fb; std::uint8_t* data = nullptr; const size_t size = 100; auto vector = fb.CreateUninitializedVector(size, sizeof (std::uint8_t), &data); memset(data, 1, size); auto object = CreateObject(fb, vector); fb.Finish(objec...
There's currently no function in the API for this, no, and while it would be possible to add a function for this, it is a bit tricky, and like you already indicate, could only be done right after creation of the vector (front of the buffer == start of vector). You could open a PR/issue on the FlatBuffers repo to implem...
64,611,641
64,612,228
(How to) Input 2 Values at Once using Single 'cin' Statement in a Specific format
Is it possible display an input message as follows? Enter First Fraction:_/_ Enter Second Fraction: _/_ Where _ are Input spaces? Using some sort of the following code?? cout<<"Enter First Fraction: "; cin>>N1>>"/">>D1; cout<<"Enter Second Fraction: "; cin>>N2>>"/">>D2; OR cout<<"Enter First Fraction: "; cin>>N1>>/>>...
Here is the Solution to my problem just in case anyone else is facing it.. Credits go to @qPCR4vir #include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; main() { //This program encourages the user to perform a sum of two fractions. int N1, D1, N2, D2, N, D; char divide{}; syste...
64,611,664
64,611,825
concating multiple strings in one line c++
I tried to overload operator "<<" to get similar behaviour like with std::stringstream. I want to concate multiple strings in one line and pass them to another function after the last word in the line. struct Log { std::string outString; template<typename T> friend Log& operator<<(Log& log, const T& t) ...
You are comparing an integer in the statement if(t == "endl" || t== "\n"), replace it with if(str == "endl" || str == "\n"). Here is the full code: #include <iostream> #include <string> #include <sstream> struct Logg { std::string outString; template<typename T> friend Logg& operator<<(Logg& logg, const T...
64,611,666
64,614,054
Given an unsorted array, how to remove duplicates then sort it?
I get troubles with this, can you help me? I remove duplicate successfully, but then I use bubble sort to sort it but it is inefficient. How can I remove duplicate then sort it? Using 2 functions can not bring what I desire. #include <stdio.h> #include <conio.h> int arr[100]; int n; void RemoveDuplicate(int arr[]); v...
All example are untested and begins with the following if (n<1 || n > sizeof(arr)) return; auto begin = std::begin(arr); auto end = begin+n; Using std::set std::set<int> unique(begin, end); std::copy(unique.begin(), unique.end(), std::begin(arr)); int size = unique.size(); Using heap std::make_heap(begin, end); st...
64,612,034
64,612,202
Why does std::copy() require std::back_inserter to insert into a vector with sufficient capacity?
REFERENCE CODE: #include <vector> #include <algorithm> #include <string> #include <iostream> void print(std::string label, std::vector<int> & arr) { std::cout << label << ":" << " size: " << arr.size() << " cap: " << arr.capacity() << " [ "; for (auto elem : arr) { std::cout << elem << " "; } std::cout << ...
Why can't I use d_arr.begin() as the OutputIt in std::copy when the underlying vector has sufficient capacity? Because the destination vector is empty, and thus std::copy overflows the vector (because assignment of any element is outside the bounds of an empty vector). Is the std::back_inserter() operation optimized...
64,612,137
64,612,431
C++ static member reinitialized after initialization
Im am trying to implement a design of a "HasUtility" template class allowing to create templated static member (utilities) and maintening a list of all utilities (base classes) Here is the code: StaticUtilityBase.h: #include <vector> #include <iostream> class StaticUtilityBase { public: static std::vector<StaticUt...
You are accessing a static object (in this case StaticUtilityBase::all) from the constructor of a different static object (in this case template <typename T> StaticUtility<T> HasUtility<T>::utility;). As there is no ordering guarantee between initialisation of different static objects across translations units what you...
64,612,353
64,612,683
Error initializing shared pointer with an array of list<int>
I'm trying to implement a Graph class with shared_ptr. I've declared my class as below. class Graph { public: Graph(int V); Graph()=delete; void AddEdge(int src, int dest); void BFS(int s); ~Graph(); private: int V; std::shared_ptr<std::list<int>[]> adj; ...
C++11 has only one make_shared function. This is what its prototype looks like: template< class T, class... Args > shared_ptr<T> make_shared( Args&&... args ); T can't be an array. The function accepts arguments that will be passed to the T constructor, but std::list has no constructor that can accept new std::list<i...
64,612,513
64,612,753
Using std::less<> for unique_ptr to raw pointer comparison fails to compile, but works with wrapper?
I want to search by raw pointer in a set of std::unique_ptr, and instead of writing my own comparator class I decided to use the transparent property of std::less<>. Here's an example code based on the cppreference example. This doesn't compile: #include <memory> #include <set> using FatKey = std::unique_ptr<int>; usi...
Neither std::unique_ptr<int> nor int involve user-defined types; in terms of ADL their associated namespaces are namespace std only. When you use a wrapper type you have an associated namespace of the root namespace (the namespace where you declared the wrapper), which means that ADL can find the free operator<s define...
64,612,534
64,612,668
ifstream keeps read even though the file does not exists anymore
I'm facing a problem using std::ifstream to read a file. I have a zip file called "nice_folder.zip" (71.6MB) and the following code that reproduces the issue: #include <filesystem> #include <fstream> #include <iostream> #include <memory> #include <unistd.h> int main() { size_t read = 0; size_t f_size = std::files...
If you're doing this on e.g. linux, then the OS will not actually delete the file until you've closed all file handles to it. So it might seem like the file is deleted, but it's still stored somewhere on disk. See e.g. What happens internally when deleting an opened file in linux. So if you're trying to detect this fil...
64,612,643
64,614,319
How to print the transpose of a 2d vector with different number of columns?
I'm working with some 2d vectors and I'm trying to print the transpose of the vector. The sub vectors are not the same size and whenever there is a space on a column I am getting an out of range error. So I'm looking for a solution to omit the missing parts and instead, print them as spaces. So far I have this : #inclu...
Let's try to concentrate on the task at hand. You want to print a matrix. If an entry of the matrix does not exist, you want to print a space character. Printing the matrix is usually done with two nested loops: for(int row = 0; row < rows; ++row) for(int col = 0; col < cols; ++col) ... Checking if an elem...
64,612,739
64,612,801
(C++) I am trying to read and output a random line from a text file and I keep getting "Floating Point Exception (Core Dumped)" when running it
Basically what the title says. I'm trying to write code that will take in a random word from a file called "words.txt" and output it. I run it and keep getting the error "Floating Point Exception (Core Dumped)". Here's the code: #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <vecto...
You just opened the file and didn't read that. word has no elements, so word[rand()% word.size()] is dividing something by zero. Dividing by zero is not allowed. Also you should check if the opening of file succeeded and something is actually read. Try this: #include <iostream> #include <fstream> #include <string> #inc...
64,613,413
64,613,748
When is static memory allocated in C/C++? At compile time or at the very beginning of when a program is run?
Different sources say different things for me - some StackOverflow answers say that it is allocated at compile time - others say it is "defined" at compile time, and allocated at the very beginning of runtime ("load time" is what some called it), while others say it is allocated at compile time. When is static memory e...
In typical tools, memory with static storage duration is arranged in multiple steps: The compiler generates data in object modules (likely passing through some form of assembly code) that describes needs for various kinds of memory: memory initialized to zero, memory initialized to particular values and is read-only t...
64,613,432
64,613,617
Are concepts as type names in function declarations valid in C++20?
The following code compiles fine on both gcc and clang (trunk with -std=c++20) but errors on msvc (19.27 /std:c++latest). template<typename T> concept subable = requires(T lhs, T rhs) { lhs - rhs; }; auto sub(subable auto x, subable auto y) { return x - y; } int main() { const auto z = sub(4, 5); } afaik th...
Concepts cannot be used to replace typenames in C++20. However, that's not what your code is doing. You are using abbreviated function template syntax, by declaring the type of the parameter to use the placeholder type auto. Abbreviated function templates can be constrained by applying a type-concept name to the auto-d...
64,614,128
64,614,187
(Why) is this instantiation of a template class with a temporary/anonymous object a vexing parse?
This code: // main.cpp template< typename T > class Owner { public: Owner( const T& t ) : t_( t ) {} void func() { } private: T t_; }; class Foo { }; int main( int argc, char* argv[] ) { Owner<Foo> owner( Foo() ); owner.func(); return 0; } generates this error: $ g++ --version && g++ -g ./main.c...
This declaration: Owner<Foo> owner( Foo() ); is indeed a vexing parse. It declares owner as a function that returns an Owner<Foo>, and which has a single parameter. That single parameter Foo() is itself interpreted as a function that returns a Foo and has no parameters. The simplest way to fix this is by using braces ...
64,614,902
64,662,662
Enum class operator override
I have an enum class defined like so in myClass.h: enum class SpeedMode { SPEED_SLOW = 0, SPEED_NORMAL = 1, SPEED_FAST = 2 }; In another file I'd like to use my enum as an int: void myOtherClass::myFunc(const SpeedMode& speed_mode) { int speed_as_int = speed_mode; . . . } In the same file I defined my enum (m...
You need access to the underlying data type of the enum class, meaning the int. The way to do this is to use std::underlying_type<T> to access the integer value. The way you do this is: #include <type_traits> auto speed_mode_as_int = static_cast<std::_underlying_type<SpeedMode>::type>(speed_mode); I made a minimum w...
64,615,013
64,615,112
Multidimensional array logic
I'm currently being bamboozled by a multidimensional array. I know a good deal about programming and I was wondering about the logic pertaining to a question from one of quiz modules from cpp institute. int* t[2] = { new int[2], new int[2] }; for (int i = 0; i < 4; i++) t[i % 2][i / 2] = i; std::cout << t[0]...
It's a way of iterating through all the combinations that works because it's only a 2x2 array. It basically has the same effect as for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { t[i][j] = i + 2*j } } But instead of nesting, it's relying on the fact that you can generate the pairs 0, 0, 0, 1,...
64,615,496
64,615,555
How do I fix this weird while loop error?
I have a while loop that asks the user's query and takes in a response, could be a word, could be a sentence. The output is boggling me. std::string response; while (response != "!quit") { cout << "Query? "; cin >> response; if (response == "!quit") { cout << "Thank you ...
std::cin is going to read until it meats a whitespace. So when you input "how are you ", cin is going to be called thrice, so that it consumes all three whitespaces. So the first cin will read "how ", the second "are ", and the third "you ". So what teaches you is that in order to read a sentence, you need another appr...
64,615,715
64,615,781
Template Class return tuple or value, depend on parameter pack
I want to write a class which has a parameter pack and a function. This function should return the value itself, if there is only one type in the pack and otherwise it should return a tuple. If there pack is empty it can return an empty tuple or void, I don't mind. Something like this(pseudocode): template<typename ......
Since C++17 you can use if constexpr and return type will be deduced by compiler: template<typename ...Args> class A{ std::tuple<Args...> data; public: auto get() { if constexpr (sizeof...(Args) > 1) return data; else if constexpr (sizeof...(Args) == 1) return std::ge...
64,615,821
64,616,135
C++ friend operator overloading with template parameters for nested enums
I ran into an issue while overloading friend bitwise operator with template parameters for nested enums. Originally I ran into the issue with proprietary embedded C++ compiler. After that I tried gcc, clang and MSVC and got exactly the same failure. Except, any GCC version prior to 5.0 that I have tried is able to comp...
The reason is that in the first example the operator| is not in the class inside which the enum types are defined. Hence the function is not being found by ADL (see point 4 of the 2nd list on that page): For arguments of enumeration type, the innermost enclosing namespace of the declaration of the enumeration type is ...
64,616,306
64,617,358
unordered_map to find indices of an array
I want to find indices of a set efficiently. I am using unordered_map and making the inverse map like this std::unordered_map <int, int> myHash (size); Int i = 0; for (it = someSet.begin(); it != someSet.end(); it++) { myHash.insert({*it , i++}); } It works but it is not efficient. I did this so anytime I need t...
The problem is, std::unordered_map, mainly implemented as a list of vectors, is extremely cache-unfriendly, and will perform especially poorly with small keys/values (like int,int in your case), not to mention requiring tons of (re-)allocations. As an alternative you can try a third-party hash map implementing open add...
64,616,431
64,619,177
Xcode "ld: library not found" for C++ makefile project
OS: Mac 10.14.6 -- Xcode ver: 11.3.1 I have an external C++ project (that uses an existing makefile to build) that I imported into Xcode, and when I try to build it I get the following error message: ld: library not found for -ljpeg. Strangely, when I run the same build command ($make all-recursive) from the command li...
Link should also receive a flag of the form -L<path> which has the path to the jpeg library's parent folder, before the -ljpeg flag. So add -L/usr/local/lib to the other linker flags build setting and try again. Easy way to find the correct flags is running pkg-config: pkg-config --libs libjpeg -L/usr/local/Cellar/jpeg...
64,616,665
64,616,818
Represent sum of random access iterators as a random access iterator
Random access iterators are constrained to the difference between two iterators, or to adding or subtracting an integer from an iterator. Rules do not allow addition of two iterators. I stumbled on a situation where adding two iterators could actually be useful: #include <iostream> #include <vector> using std::vector;...
You are asking to allow (left + right) / 2 as a shorter notation for left + (right - left) / 2 because these expressions are equivalent for numbers in mathematics. However, to do that, you would need to define the addition of 2 iterators and division of iterator by a number. Neither of these operations seems to make se...
64,616,725
64,617,348
How can I show gdb to show my variables properly?
For example I have a simple substring class and a simple array. When I'm debugging it's a headache because I need many clicks just to get some kind of sensible information. Is there a way I can markup my source of have some kind of config that says when I print the variable a I actually mean p *a.start@(a.end-a.start) ...
If you have a python-enabled build of gdb, you can add custom pretty printers for your types. You could try adding the following to your .gdbinit: python class MyStringPrinter: "Print a MyString" def __init__ (self, val): self.val = val def to_string (self): ptr = self.val['start'] ...
64,616,788
64,617,172
How to start explorer.exe with QProcess when the path to the specified file contains spaces?
I want to start explorer and select a specific file. So I run QProcess::startDetached(command); with command set to explorer.exe /select,C:\Users\....\file.txt This works fine, but will fail if the path to the file contains spaces. But if I put the path in quotes explorer.exe /select,"C:\Users\....\file.txt" the exp...
How to achieve this is indeed not so intuitive, but also not impossible. Solution Decompose all arguments of the command, explorer.exe, as separate strings, i.e. /select, ,, the_path. Example QProcess::startDetached("explorer.exe", QStringList{"/select", ",", "C:\\Users\\Your Username\\Desktop\\Folder With Spaces\\file...
64,616,857
64,616,889
Store a matrix by columns instead of rows
If I'm given the matrix: A B C D E F G H I and it is stored in a vector by rows: [A, B, C, D, E, F, G, H, I] How can I use the above vector with a for loop to store the transposed version in another vector. [A, D, G, B, E, H, C, F, I]
You have 3 rows with 3 elements (because number of columns is 3) in the old vector and you will have 3 columns with 3 elements (because number of rows is 3) in the new vector. Therefore, it can be realized like this: int nRows = 3, nCols = 3; for (int i = 0; i < nRows * nCols; i++) { int r = i / nCols, c = i % nCol...
64,617,325
64,617,504
Variadic Template Class not fully expanded
I am trying to create something similar to a type-safe multiqueue. The idea is that when I push an item, it will be added to a queue consisting of objects of the same type. All the queues will have a common interface(the queue_intf in this case) that will do some processing. The code I came up is the following: #includ...
To explain this, let's use a simplified example, you have just two classes: class base { public: void method(int *); }; class derived : public base { public: void method(char *); }; And you attempt to call it: derived d; int i; d.method(&i); This fails. Name lookup starts at the given derived class, and...
64,617,490
64,617,689
Query breaks whenever I add MAX() functions or grouping statements
I have some tables laid out like so: Airplane (airplaneID number(2) primary key, airplaneName char(20), cruisingRange number(5)); Flights (airplaneID number (2), flightNo number(4) primary key, fromAirport char(20), toAirport char(20), distance number(4), depart timestamp, arrives timestamp, foreign key (airpl...
You can't mix implicit and explicit joins. I suggest SELECT Employees.employeeName, MAX(Airplane.cruisingRange) FROM Employees JOIN Certified ON Employees.employeeID = Certified.employeeID JOIN Airplane ON Airplane.airplaneID = Certified.airplaneID GROUP BY Employees.employeeName HAVING COUNT(*) > 3 which works fine. ...
64,617,513
64,617,525
What's the difference between &table[0][0] and &table?
I've been successfully trying to pass a 2D-array to a function, see code below. What I don't get: Why does my "method C" (see code below) not work? What's the difference between &table[0][0] and &table? Both of them point to the same memory address. The former works as argument passed to my function, the latter doesn't...
Main difference: What is actually being pointed to, and from that its type. The expression &table points to the array table itself, and it will have the type int(*)[3][2]. The expression &table[0][0] is a pointer to a single element in the sub-array table[0], and will have the type int*. The reason "method A" works, ev...
64,617,776
64,617,863
Why does std::set::insert() call operator<() with bad parameter
I need help to understand why std::set<T>::insert(T) is calling operator<(const T&, const T&) with an invalid reference as its second parameter, creating a segfault upon my first insertion. Here is the class whose objects I want to insert in a set: /** * A CPC category. */ class Category { private: char m_sect...
And here is the code creating the set: 'Fraid not. You created a pointer-to-set, but it doesn't actually point to any set; it's just an uninitialised pointer. You could use new to dynamically allocate a set, but don't do that unless you have to. In fact, don't use pointers unless you have to. Your needs here will be ...
64,618,195
64,618,291
why a c++ application has three threads started by default?
There is an empty Windows console C++ application. In my mind, a process would have one thread started by default, but it shows three threads when debugging it. The program as follows: int main() { return 0; } and the debug information is:
ntdll.dll threads are in fact operating system threads started from library you link against. All your code is running on thread 16472. Usually these are threadpool workers to load other dynamic libraries for your app. Windows 10 is optimizing process startup by utilizing multiple CPU cores to initialize faster.
64,618,204
64,619,634
How do I read only integers from a file into a c++ program that also has strings?
I have a file that contains, numbers(ints) and words both, I want to read only the integers, Please ignore the macros if they are annoying, However I only need to have the integers but I have to be sure to also read the strings and then disregard them What do I have to modify here: #include <iostream> #include <vector>...
You can read the values from the text file into a vector of strings. From there you can use the standard library and its algorithms to extract integers from strings. In this particular solution, I choose to use the <regex> library only to assist in pattern matching of characters. The use of <regex> does not actually ex...
64,618,247
65,273,896
How to play video backwards in qt using vlc-qt libvlc
I am developing a media player using vlc-qt , Actually I want a button which will play do the fast backward operation. I don't have the problem with the fast forward operation but not able to implement the fast backward operation, Is there any function there in vlc-qt which will play the video backwards. Here are the b...
VLC does not have this capability. As a workaround, you could try VLC with ffmpeg. I never used it, but: You can use ffmpeg to reverse a video, see this and Reverse video playback through ffmpeg, e.g. You can use ffmepg with VLC, see this, e.g. So I guess you could accomplish what you need with this solution. Other r...
64,618,691
64,619,149
Why did the queue stop traversing at the median element?
When I try to check the correction of my postfix expression, the output values performed disrupted at the middle of the elements in the queue. There is not any reminders from the IDE but it is certain that some problems exist within my code. Why did it happen? This is my test code: int main(){ op['('] = 0; op['...
Lets start with a complete, but simple example with the same loop logic: #include <iostream> #include <queue> using namespace std; int main() { //Make a queue queue<int> q; // put a few items in it for (int count = 1 ; count < 6; count++) q.push(count); // run asker's logic for (int index = 0; ...
64,618,840
64,619,245
Controlling output of Boost.Test source location format
Catch2 and Boost.Test provide similar features for writing unit tests. For a certain project I have to use Boost.Test instead of Catch2. The problem I have is that both use different format outputs. For example, Catch2 will say that the was a fail in test.cpp:9 (see example below). However Boost.Test will say test.cpp(...
I found a solution in this historical post: https://richarddingwall.name/2008/06/01/using-the-boost-unit-test-framework-with-xcode-3 Using the (lost of) art of virtual function override and Boost.Test fixtures: Simply add this code (some updates to the original post, with minor formats and C++11 updates): #include<boos...