question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
70,861,484
70,862,527
showing the full content of ImageType in DCMTK
I'm trying to read a number of Siemens DICOM images with DCMTK, some of which are mosaic images. I'm looking for a quick way to find those. What I can see with mosaic images is that this is specified in the ImageType tag, e.g. $ dcmdump ${im0} | grep ImageType (0008,0008) CS [ORIGINAL\PRIMARY\ASL\NONE\ND\NORM\MOSAIC] # 40, 7 ImageType Most of the tags are easily read with findAndGetOFString() (or similar for floats etc), but if I do tmpdata->findAndGetOFString(DCM_ImageType, tmpstring); std::cout << "image type: " << tmpstring << "\n"; for DcmDataset* tmpdata and OFString tmpstring, then the content of tmpstring is only ORIGINAL so the rest of the value is never printed. In dcmdump it is printed, but there the value of DCM_ImageType never seems to be stored in a string, which I do need it to be. Would there be a similar command to findAndGetOFString() for 'code strings'? Maybe I'm missing something obvious!
Image Type (0008,0008) is a multi-valued attribute. That is, it may include several values which are separated by the backslash character. Note, that "officially", the backslash is not part of the attribute's value. It is a delimiter between several values of the attribute. This is what you have. So in terms of DICOM, there is no "one value" but multiple ones. The DCMTK API allows you to handle this (of course). findAndGetOFString() has a third parameter ("index") to define which of the multiple values you want to obtain. The behavior that you probably expect is what findAndGetOFStringArray() does. As an alternative, you could iterate through the multiple values of the attribute by obtaining the "Value Multiplicity" first and then loop through the values like DcmElement* element = tmpdata->findAndGetElement(DCM_ImageType); int numberOfValues = element->getVM(); for(int index = 0; index < numberOfValues; index++) { OFString valueAtIndex; element->GetOfString(valueAtIndex, index); /// ... your concatenation goes here... }
70,862,064
70,863,591
Friend class of template class problem (C++) (error: 'LinkedList' is not a class template)
I am trying to implement a generic Linked list in C++ and I get an error that I don't know how to deal with. Here is my Link class implementation (which is also generic): #ifndef LINK_H #define LINK_H #include <iostream> #include "typeinfo.h" #include "LinkedList.h" template <class T> class Link { public: //|-------------------- Constructors -------------------- Link(T data): m_data(data), next(NULL){} //|-------------------- Methods -------------------- T getData(){ return m_data; } T& getNext(){ return next; } void setNext(Link* newLink){ next = newLink; } void setData(T data){ m_data = data; } //|-------------------- Operator overload -------------------- bool operator==(Link& other){ if(this->m_data == other.m_data) return true; return false; } void operator++(){ this = this->next; } //|-------------------- Friend functions -------------------- friend std::ostream& operator<<(std::ostream& out,const Link<T>& link){ out<<link.m_data; return out; } //|-------------------- Destructor -------------------- virtual ~Link(){} protected: private: //|-------------------- Private fields -------------------- T m_data; Link<T>* next; friend class LinkedList<T> }; #endif // LINK_H As you can see I am trying to let LinkedList<T> be a friend of Link<T> so I can get access to its fields (I want them to stay private). Now, I think its relevant to post all of my LinkedList<T> implementation because its a lot of code, but here's how I defined the class: #ifndef LINKEDLIST_H #define LINKEDLIST_H #include "List.h" #include "Link.h" template <class T> class LinkedList : public List<T> { public: and here are the fields: private: //|-------------------- Private fields -------------------- Link<T>* head; Now, I get this error: error: 'LinkedList' is not a class template I have tried to search the error and found this. But it does not seem to be the problem in my implementation. I also found this. But I could not understand how to implement this forward declaration in my case (or why I even need it). I'd really appreciate clarification here. Thanks in advance
Simply add a forward declaration of LinkedList before the definition of the Link class like this: template<typename U> class LinkedList; // Now the definition as you have it above... template <class T> class Link { public: ... See here. BTW, you're missing a ; after your friend declaration in your first code block.
70,862,456
70,862,498
Difference between data assignment in pointer and a variable
Why does the program exit with exception when i use the array variant instead of the pointer. int main() { // unsigned char data[1920 * 1080 * 4]; this causes the exception unsigned char* data = new unsigned char[1920 * 1080 * 4]; std::cout << "Hello World!\n"; }
Automatic storage duration (the commented case) has a limit of about 1Mb on current platforms. Dynamic storage duration (the uncommented case) allows for much larger contiguous blocks to be allocated. (In excess of 1Gb on current platforms). The C++ standard doesn't mandate specific limits.
70,862,819
70,862,876
Using a field of an abstract class as a default argument of a method (c++)
I wrote an abstract class called "List", which I basically use as an interface for other implementation methods of lists (such as dynamic array and linked list). Now, I have a method called "add", with 2 arguments, the first one is the data to add and the second is the position where to add. I want to set the default value of this position to be the end of the list (i.e, its size). Here's what I wrote: #ifndef LIST_H #define LIST_H template <class T> class List { public: List(): m_size(0) {} virtual bool isEmpty() const=0; virtual void set(int index, T value)=0; virtual int getSize() const=0; virtual void add(T data, int index = m_size )=0; //The problem is here virtual T remove(int index)=0; virtual ~List(){} virtual T operator[](int index) const =0; virtual bool operator==(const List<T>& other) const =0; protected: int m_size; }; #endif // LIST_H But I get the following error: error: invalid use of non-static data member 'List<T>::m_size'| Is there a way to fix this problem? Also, is it correct to implement the constructor as I did? do I need to call this constructor in the init line of the derived classes constructors or does the compiler does it implicitly? Thanks in advance.
You cannot use members as default arguments of methods. Instead, write an overload. It doesn't need to be virtual when it calls the virtual add(T,int): void add(T data) { add(data,m_size ); }
70,863,308
70,875,111
Given n points, how can I find the number of points with given distance
I have an input of n unique points (X,Y) that are between 0 and 2^32 inclusive. The coordinates are integers. I need to create an algorithm that finds the number of pairs of points with a distance of exactly 2018. I have thought of checking with every other point but it would be O(n^2) and I have to make it more efficient. I also thought of using a set or a vector and sort it using a comparator based on the distance with the origin point but it wouldn't help at all. So how can I do it efficiently?
There is one Pythagorean triple with the hypotenuse of 2018: 11182+16802=20182. Since all coordinates are integers, the only possible differences between the coordinates (both X an Y) of the two points are 0, 1118, 1680, and 2018. Finding all pairs of points with a given difference between X (or Y) coordinates is a simple n log n operation. Numbers other than 2018 might need a bit more work because they might be members of more than one Pythagorean triple (for example 2015 is a hypotenuse of 3 triples). If the number is not given as a constant, but provided at run time, you will have to generate all triples with this hypotenuse. This may require some sqrt(N) effort (N is the hypotenuse, not the number of points). One can find a recipe on the math stackexchange, e.g. here (there are many others).
70,863,429
70,863,802
Parsing text file with symbol
I cant parse all text from .txt file But when I run my code, I don't get what I wanted :( My code: int main() { /* inside "logMsg.txt" 1/ [111]{1}(text line from 111); 2/ [222]{2}(text line from 222); 3/ [333]{3}(text line from 333); */ ifstream textfile("logMsg.txt"); string log_line; string log_time; string log_type; string log_comment; // Get line number getline(textfile, log_line, '/'); // Get Time by unix getline(textfile, log_time, '['); getline(textfile, log_time, ']'); // Get type of the function getline(textfile, log_type, '{'); getline(textfile, log_type, '}'); // Get comment from data_ getline(textfile, log_comment, '('); getline(textfile, log_comment, ')'); cout << "Line Of the log: " << log_line << "\n"; cout << "Type of the log: " << log_type << "\n"; cout << "Time of the log: " << log_time << "\n"; cout << "Comment of the log :" << log_comment << "\n"; } Console: Line Of the log: 1 Type of the log: 1 Time of the log: 111 Comment of the log :text line from 111 I wanted the parser to read all the lines, but the result is completely different I don't understand what I'm doing wrong, I trying to get the following result: Line Of the log: 1, 2, 3, Type of the log: 1, 2, 3, Time of the log: 111, 222, 333, Comment of the log: text line from 111, text line from 222, text line from 333, plz help :(
I would recommend using regular expressions for this: The example below just parses each line using a given pattern. You may need to modify it, for instance, allowing whitespaces around certain fields. [Demo] #include <fmt/core.h> #include <iostream> // cout #include <regex> #include <sstream> // istringstream #include <string> // getline int main() { const std::string input{"1/ [111]{1}(text line from 111);\n2/ [222]{2}(text line from 222);\n3/ [333]{3}(text line from 333);"}; std::istringstream iss{input}; std::string line{}; while (std::getline(iss, line)) { const std::regex pattern{R"(([\d+])/\s*\[(\d+)\]\{(\d+)\}\(([^)]+)\);)"}; std::smatch matches{}; if (std::regex_match(line, matches, pattern)) { std::cout << fmt::format ("Line: {}, type: {}, time: {}, comment: {}\n", matches[1].str(), matches[2].str(), matches[3].str(), matches[4].str()); } } } // Outputs: // // Line: 1, type: 111, time: 1, comment: text line from 111 // Line: 2, type: 222, time: 2, comment: text line from 222 // Line: 3, type: 333, time: 3, comment: text line from 333 Should you want a different output (e.g. as it seems you suggest in your question, print all the line numbers, then all the times, and so on), you may want to use std::vectors for keeping that information, and printing it at the end. [Demo] #include <algorithm> // copy #include <iostream> // cout #include <iterator> // ostream_iterator #include <regex> #include <sstream> // istringstream #include <string> // getline int main() { const std::string input{"1/ [111]{1}(text line from 111);\n2/ [222]{2}(text line from 222);\n3/ [333]{3}(text line from 333);"}; std::istringstream iss{input}; std::vector<std::string> numbers{}; std::vector<std::string> types{}; std::vector<std::string> times{}; std::vector<std::string> comments{}; std::string line{}; while (std::getline(iss, line)) { const std::regex pattern{R"(([\d+])/\s*\[(\d+)\]\{(\d+)\}\(([^)]+)\);)"}; std::smatch matches{}; if (std::regex_match(line, matches, pattern)) { numbers.push_back(matches[1]); types.push_back(matches[2]); times.push_back(matches[3]); comments.push_back(matches[4]); } } std::cout << "Line of the log: "; std::copy(numbers.cbegin(), numbers.cend(), std::ostream_iterator<std::string>(std::cout, ", ")); std::cout << "\n"; std::cout << "Type of the log: "; std::copy(types.cbegin(), types.cend(), std::ostream_iterator<std::string>(std::cout, ", ")); std::cout << "\n"; std::cout << "Time of the log: "; std::copy(times.cbegin(), times.cend(), std::ostream_iterator<std::string>(std::cout, ", ")); std::cout << "\n"; std::cout << "Comment of the log: "; std::copy(comments.cbegin(), comments.cend(), std::ostream_iterator<std::string>(std::cout, ", ")); std::cout << "\n"; } // Outputs: // // Line of the log: 1, 2, 3, // Type of the log: 111, 222, 333, // Time of the log: 1, 2, 3, // Comment of the log: text line from 111, text line from 222, text line from 333, Although you'd better use a single std::vector of structs, with proper types for the numbers, types and times. In this case, you would need to convert the strings from matches to the struct's ints (you could do that with std::stoi). [Demo] struct LineInfo { int number{}; int type{}; int time{}; std::string comment{}; }; std::vector<LineInfo> line_infos{};
70,863,728
70,863,789
What should I do with this error on input? Can you also suggest how to make my code better, I converted it from C into C++
There is an error in this line cin >> X >> Y; This is the function it belongs into void InputData(int *X,int *Y) { cout << "Enter 2 integer values: "; cin >> X >> Y; } Below is the whole code #include <iostream> using namespace std; void Message(); void InputData(int *X, int *Y); void OutputData(int X, int Y, int Sum); int ComputeSUM(int X, int Y); int main() { int X1,X2,SUM; Message(); InputData(&X1,&X2); SUM=ComputeSUM(X1,X2); OutputData(X1,X2,SUM); return 0; } void Message() { cout << "This program computes and displays SUM of 2 integer values!" << endl <<endl; } void InputData(int *X,int *Y) { cout << "Enter 2 integer values: "; cin >> X >> Y; } void OutputData(int X, int Y, int Sum) { cout << "The SUM of " << X << " and " << Y << " is " << Sum << endl; } int ComputeSUM(int X, int Y) { int Sum; Sum=X+Y; //return(X+Y) return(Sum); } See what's on the terminal See what's on the terminal ------------------------------------------------------------ Below is the original code in C language #include <stdio.h> #include <conio.h> void Message(); void InputData(int *X, int *Y); void OutputData(int X, int Y, int Sum); int ComputeSUM(int X, int Y); int main() { int X1,X2,SUM; clrscr(); Message(); InputData(&X1,&X2); SUM=ComputeSUM(X1,X2); OutputData(X1,X2,SUM); getch(); return(0); } void Message() { printf("This program computes and displays SUM of 2 integer values!\n\n"); } void InputData(int *X,int *Y) { printf("Enter 2 integer values; "); scanf("%d%d",X,Y); } void OutputData(int X, int Y, int Sum) { printf("The SUM of %d and %d is %d\n",X,Y,Sum); } int ComputeSUM(int X, int Y) { int Sum; Sum=X+Y; //return(X+Y) return(Sum); }
cin >> X >> Y; ->cin >> *X >> *Y;
70,863,964
70,864,032
I want the user to input the day number as the value of the parameter of the called function using cin
So, as you see in the question I want to make the user input the value of the arguement daynum down when I call the function getday, and not me who enters it. However I can't seem to get it right. I have tried cin << getday(); but it's wrong I looked in the internet to get an idea I guess and I tried getday(cin); but still it's wrong kinda clueless here about how to use cin with the function call. #include <iostream> using namespace std; string getday(int daynum){ string dayname; switch(daynum){ case 0: dayname = "sunday"; break; case 1: dayname = "Monday"; break; case 2: dayname = "Tuesday"; break; default: dayname = "invalid day number"; } return dayname; } int main() { cout << "Enter daynum" << endl; return 0; }
You have to create a temporary variable, fill it with user value using cin, and then pass it to your function: string getday(int daynum) { string dayname; switch (daynum) { case 0: dayname = "sunday"; break; case 1: dayname = "Monday"; break; case 2: dayname = "Tuesday"; break; default: dayname = "invalid day number"; } return dayname; } int main() { cout << "Enter daynum" << endl; int daynum; cin >> daynum; cout << getday(daynum) << endl; return 0; }
70,864,475
70,867,380
reading new line from file and writing to another file in C++ using streams. not reading new line
I am reading IO streams in C++ and have following code int main() { fstream output_file; output_file.open("cout.txt", ios::out); fstream input_file; input_file.open("cin.txt", ios::in); // backup existing stream buffers streambuf* cin_old_streambuf = cin.rdbuf(); streambuf* cout_old_streambuf = cout.rdbuf(); // Get output stream buffer of file and redirect to cout streambuf* output_file_streambuf = output_file.rdbuf(); cout.rdbuf(output_file_streambuf); // Get input stream buffer of file and redirect to cin streambuf* input_file_streambuf = input_file.rdbuf(); cin.rdbuf(input_file_streambuf); /* What ever you do with cout will write to file. */ string line; getline(cin, line); cout << line; getline(cin, line); cout << line; getline(cin, line); cout << line; getline(cin, line); cout << line; } My input file cin.txt My name is ravi My age is 45 output file cout.txt is My name israviMy age is 45 My question is why program is not reading \n in input. My understanding is that getline reads newline. I am expecting output file is similar to input file. Kindly help what change do I have to main
While getline(cin, line); does retrieve the input from your other file line by line, if you want new lines when printing with cout << line; you should still follow the standard of adding either "\n" or endl; at the end of your cout lines. The last part of your code should look like this. getline(cin, line); cout << line << endl; getline(cin, line); cout << line << endl; getline(cin, line); cout << line << endl; getline(cin, line); cout << line << endl;
70,865,226
70,866,001
How to iterate over enumerators of an enum class?
Is there a way to initialize a container (e.g. std::unordered_set<char>) with the enumerators of an enum class? I have this class: #include <iostream> #include <unordered_set> class Foo { public: inline static const std::unordered_set<char> chars_for_drawing { '/', '\\', '|', '-' }; }; int main( ) { for ( const char ch : Foo::chars_for_drawing ) { std::cout << ch << ' '; } } But I want the chars_for_drawing set to be initialized with the enumerators: #include <iostream> #include <unordered_set> class Foo { public: enum class AllowedChars : char { ForwardSlash = '/', BackSlash = '\\', VerticalSlash = '|', Dash = '-' }; // inline static const std::unordered_set<char> chars_for_drawing { '/', '\\', '|', '-' }; // not like this inline static const std::unordered_set<char> chars_for_drawing { static_cast<char>( AllowedChars::ForwardSlash ), static_cast<char>( AllowedChars::BackSlash ), static_cast<char>( AllowedChars::VerticalSlash ), static_cast<char>( AllowedChars::Dash ) }; }; int main( ) { for ( const char ch : Foo::chars_for_drawing ) { std::cout << ch << ' '; } } As can be seen, the second approach is a bit messy. Is there way to iterate over the enumerators and assign them to the unordered_set? Maybe by using a lambda?
No there is no straightforward way. Something one often forgets: The range of the enums values is determined by its underlying type. The enumerators are just some named constants. Your enum: enum class AllowedChars : char { ForwardSlash = '/', BackSlash = '\\', VerticalSlash = '|', Dash = '-' }; helps for iterating as much as a struct { char value; static const char ForwardSlash = '/'; static const char BackSlash = '\\'; static const char VerticalSlash = '|'; static const char Dash = '-'; }; does: Not at all. Things are different when the enumerators have consecutive values and a hack that is used sometimes is to use a special enumerator to denote the "size": enum class AllowedChars : char { ForwardSlash, BackSlash, VerticalSlash, Dash, SIZE }; int main() { for (int i=0;i< static_cast<int>(AllowedChars::SIZE); ++i){ std::cout << i; } } That alone is a little silly, because the mapping to the actual characters is lost. However, it can be supplied by an array: #include <iostream> enum class AllowedCharNames : char { ForwardSlash, BackSlash, VerticalSlash, Dash, SIZE }; char AllowedChars[] = {'/','\\','|','-'}; int main() { std::cout << AllowedChars[static_cast<size_t>(AllowedCharNames::Dash)]; for (int i=0;i< static_cast<int>(AllowedCharNames::SIZE); ++i){ std::cout << AllowedChars[i]; } } TL;DR Reconsider if an enum is the right tool for the job. Enums are often overestimated for what they can really do. Sometimes not an enum is the better alternative.
70,865,456
70,869,119
CMake: What formatting does execute_process() do?
I need to call the findstr Windows command (grep on Linux) from my CMakeList.txt. If I do this, it is working : execute_process( COMMAND findstr "NABO_VERSION " nabo\\nabo.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} RESULT_VARIABLE FINDSTR_RESULT ERROR_VARIABLE FINDSTR_ERROR OUTPUT_VARIABLE FINDSTR_OUT OUTPUT_STRIP_TRAILING_WHITESPACE ) I get the output: FINDSTR_ERROR = FINDSTR_OUT = #define NABO_VERSION "1.0.7" #define NABO_VERSION_INT 10007 FINDSTR_RESULT = 0 However, the space at the end of "NABO_VERSION " is not taken into account. I have to add /c: before my string. So I get this following code : execute_process( COMMAND findstr /c:"NABO_VERSION " nabo\\nabo.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} RESULT_VARIABLE FINDSTR_RESULT ERROR_VARIABLE FINDSTR_ERROR OUTPUT_VARIABLE FINDSTR_OUT OUTPUT_STRIP_TRAILING_WHITESPACE ) But now it doesn't work and I get this: FINDSTR_ERROR = FINDSTR_OUT = FINDSTR_RESULT = 1 The command works well in PowerShell or CMD, but not from CMake. I think that CMake modify the command, but in what way ?
So I created a test file called nabo\nabo.h with the following contents: #define NABO_VERSION "1.0.7" #define NABO_VERSION_INT 10007 Then at cmd, I wrote: > findstr "NABO_VERSION " nabo\nabo.h #define NABO_VERSION "1.0.7" #define NABO_VERSION_INT 10007 and got both lines back. Adding /c: is necessary: > findstr /c:"NABO_VERSION " nabo\nabo.h #define NABO_VERSION "1.0.7" Now to write this in CMake: # test.cmake cmake_minimum_required(VERSION 3.21) # Script mode, no project() call execute_process( COMMAND findstr "/c:NABO_VERSION " [[nabo\nabo.h]] WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} RESULT_VARIABLE FINDSTR_RESULT ERROR_VARIABLE FINDSTR_ERROR OUTPUT_VARIABLE FINDSTR_OUT OUTPUT_STRIP_TRAILING_WHITESPACE ) message(STATUS "FINDSTR_ERROR = ${FINDSTR_ERROR}") message(STATUS "FINDSTR_OUT = ${FINDSTR_OUT}") message(STATUS "FINDSTR_RESULT = ${FINDSTR_RESULT}") Running this script returns the expected result: >cmake -P test.cmake -- FINDSTR_ERROR = -- FINDSTR_OUT = #define NABO_VERSION "1.0.7" -- FINDSTR_RESULT = 0 This works because, as the findstr /? output says: Use spaces to separate multiple search strings unless the argument is prefixed with /C. So then you just need the quotes in CMake to ensure the space is included in the whole argument.
70,865,483
70,879,278
Qt cross-platform mobile ADS support?
I have a mobile app developed in Qt. Is there a way to support ads with Qt? Thanks in advance!
There's a cool, newly released, first party Advertising library from Qt. To use it: be sure you have Qt 5.15.0 or higher installed (up to 6.2.2). Install Qt Digital Advertisement plugin from either the installer or from the Maintenance Tool of your already installed Qt environment. Copy the profile.dat and configMobile.dat files in your root project (these files will be created specially for your account, and handed over to you from the Qt team) Edit your qml.qrc project file to include both of the files from point 3. ... <file>profile.dat</file> <file>configMobile.dat</file> </qresource> Place the MobileAd qml view inside your screen qml. And you're all done! For now Qt has a single MobileAd qml component, that can be manipulated at your own desire and from which you can create: Banner (Anchor) ads Interstitial (Fullscreen) ads Native (Inline) ads In the near future the library will also support Rewarded ads. For more details please follow the documentation or blog posts.
70,865,904
70,866,525
dynamic_cast downcasting: How does the runtime check whether Base points to Derived?
I am interested in understanding how, generally speaking, the runtime checks whether a base class actually points to a derived class when using dynamic_cast to apply a downcast. I know that each virtual table of a polymorphic class contains RTTI too (in the form of type_info pointers).
Every compiler is going to have slight differences in implementation, but I'm going to use MSVC as a reference as they easily supply the source with VS. You can view all of the details on how MSVC does it by going to your Visual Studio installation and going to /Community/VS/Tools/MSVC/${VERSION}/crt/src/vcruntime/rtti.cpp The compiler will internally convert dynamic_cast's to call the function __RTDynamicCast (or __RTCastToVoid if try to cast to a void*), this will take in the RTTI info for the target type and the source type. The key element in the _RTTITypeDescriptor structure is the fully decorated name. It will then dispatch to one of 3 different implementations depending on whether the input type has single inheritance, multiple inheritance, or virtual inheritance. For single inheritance FindSITargetTypeInstance will walk through the the list of base class types, and if it finds a match by pointer comparison it will return the class descriptor. If it fails to find a match by pointer comparison it will try again using string comparisons. For multiple inheritance FindMITargetTypeInstance will walk the class hierarchy in a depth-first, left-to-right order until it has seen the descriptor for both the source type and the target type. Every comparison is done through TypeidsEqual which will first try to do a pointer comparison, but will immediately fallback to string comparison, this differs from single inheritance in that single inheritance did this in 2 separate loops as it is likely the pointers would match. For virtual inheritance FindVITargetTypeInstance will walk the entire class hierarchy. This is the slowest of the three as it cannot exit early due to potential diamond problems. Every comparison is done through TypeidsEqual. Once the descriptor for the type has been found it will use that to calculate an offset from the source pointer to the target pointer. Overall the code is fairly simple and incredibly well documented, though I did leave out some nuances like checking to see if the base class was publicly derived, or distinguishing between down-casts, up-casts, and cross-casts.
70,866,546
70,866,707
does malloc(sizeof(Class1)) allocate the same size of memory as new Class1?
For any class, say "Class1" Does cpp standard guarantee that malloc(sizeof(Class1)) allocate the same size of memory as allocated by new operator? new Class1
If the non-array new expression's allocation function call is neither omitted nor extended as explained below, it will call an operator new to allocate storage with a size argument exactly equal to sizeof of the object type. (But not for array new expressions.) However, a new expression's allocation might be extended to provide storage for other new expressions as well, in which case the argument given to operator new will be the sum of the required storage for the new objects plus necessary padding for alignment. In the other new expressions for which the extended new expression's allocation provides storage no operator new will called. Additionally, a call to an allocation function may be completely omitted if the storage can be provided in another way (e.g. on the stack). How an operator new obtains storage is less clear. operator new overloads and replacements can be defined by the program and are free to obtain the storage in whatever way suits them. The default implementation of the global operator new which is provided by the compiler/standard library has no requirements placed on it either in regards to how it acquires the memory. It doesn't need to use std::malloc, for example. In practice, I think implementations usually simply call std::malloc with the same size argument to acquire the memory, at least absent additional debugging mechanisms requiring additional storage. So the answer depends on what exactly you identify as the size of the allocation. If you refer to the size requested by a call to operator new, then there may not be a unique call for the new expression, but if there is, the size argument given to it will exactly match sizeof(Class1). If you refer to the number of calls and argument given to std::malloc, then the standard doesn't place any requirements on whether or not std::malloc calls happen and with what arguments. If you go down even further, it is also completely up to the implementation how std::malloc itself obtains memory. Of course that will strongly depend on the operating system and so on. Aside from this allocation, the constructor call to Class1 may also cause more memory allocations to occur (but not for the storage of the object created by new itself), which can never happen with malloc. In addition to everything mentioned above, under the as-if rule, a compiler is furthermore allowed to compile the program in any way as long as it has the same observable behavior as by the rules of the abstract machine (for which the explanation above applies). Allocation in general and calls to operator new without observable side-effect or calls to std::malloc specifically are not an observable behavior and therefore in the compiled executable their number of calls and arguments with which they are called may differ. In particular calls to these functions may be optimized away by the compiler completely if they are not required. (E.g. if memory is allocated that is never used.)
70,866,579
70,866,580
How to make a new Visual Studio C++ project aware of an existing shared project?
The new(er) Shared C++ Project template in Visual Studio is much easier to use than previous ways code sharing was tackled. Adding one to your solution is as simple as "Add -> New Project -> Shared Items Project," and voilà! Any code inside that project is visible to all your existing projects just as if it existed in their own root directories. Unfortunately, there is one potential hang-up: If you add new projects to your solution afterwards, they don't automagically see the shared project. (Not sure if this is true for all forms of VS C++ project templates, but it certainly occurs in the project types we were working with.) If this were, say, a C# project, we could just add a reference. But C++ project properties don't provide such a simple method in this case. As fun as it is running down linker errors, having to amend several of the project's dependency paths defeats the entire purpose of the shared project template. I've searched everywhere but I simply cannot find an explanation of how to make a new project "see" an existing shared project. Is there a simple way to fix this?
As it happens, there is a quick and simple way to remedy this problem. All that's needed is a single change to the project file. Open up the new project's .vcxproj file (as text) and find the tag that reads <ImportGroup Label="Shared"> (for a new project, this tag will likely be empty). Then, just add your shared project's path like so: Turn this: <ImportGroup Label="Shared"> </ImportGroup> into this: <ImportGroup Label="Shared"> <Import Project="some/project/path.vcxitems" Label="Shared" /> </ImportGroup> And that's all you should need to do! No mucking around with any external dependency paths or other project settings. Just this one step.
70,866,681
70,867,446
How to run cuda cooperative template kernel
I am trying to unsuccessfully launch template kernel as cooperative kernel in CUDA C++ , what am I doing wrong error Error cannot determine which instance of function template "boolPrepareKernel" is intended I try to invoke kernel like below ForBoolKernelArgs<int> fbArgs = ...; int device = 0; cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, device); cudaLaunchCooperativeKernel((void*)boolPrepareKernel, deviceProp.multiProcessorCount, fFArgs.threads, fbArgs) ; kernel is defined like template <typename TYO> __global__ void boolPrepareKernel(ForBoolKernelArgs<TYO> fbArgs) { ... } I tried parametrarize launch (in this example with int) like cudaLaunchCooperativeKernel((void*)(<int>boolPrepareKernel), deviceProp.multiProcessorCount, fFArgs.threads, fbArgs) ; but I get error no instance of overloaded function matches the argument list argument types are: (<error-type>, int, dim3, ForBoolKernelArgs<int>) For suggested case cudaLaunchCooperativeKernel((void*)(boolPrepareKernel<int>), deviceProp.multiProcessorCount, fFArgs.threads, fbArgs) My error is no instance of overloaded function matches the argument list argument types are: (void *, int, dim3, ForBoolKernelArgs<int>) This is probably sth simple but I am stuck - thanks for help !! For reference kernel launch like boolPrepareKernel << <fFArgs.blocks, fFArgs.threads >> > (fbArgs); works but of course grid synchronization is unavailable.
Here is a minimal example that will compile: $ cat t1954.cu template <typename TYO> struct ForBoolKernelArgs { TYO val; }; template <typename TYO> __global__ void boolPrepareKernel(ForBoolKernelArgs<TYO> fbArgs) { } int main(){ ForBoolKernelArgs<int> fbArgs; void *kernel_args[] = {&fbArgs}; cudaLaunchCooperativeKernel((void*)(boolPrepareKernel<int>), 1, 1, kernel_args) ; } $ nvcc -o t1954 t1954.cu $ Probably the main issue you had remaining is that you are not following proper instructions for passing kernel arguments.
70,866,692
70,867,005
What is member interpretation in Range-based for loop (since C++11)?
I read this documentation for a range-based for loop: The member interpretation is used if the range type has a member named begin and a member named end. This is done regardless of whether the member is a type, data member, function, or enumerator, and regardless of its accessibility. Thus a class like class meow { enum { begin = 1, end = 2}; /* rest of class */ }; cannot be used with the range-based for loop even if the namespace-scope begin/end functions are present. I do not understand this paragraph. What does the member interpretation do so as to forbid the example class being used with the range-based for loop?
The "member interpretation" refers to begin_expr and end_expr using members of the iterated type in contrast to using plain offsets for arrays or begin and end free functions. The array interpretation is off the table, because it is only used for arrays. Next consider that there is std::begin and std::end: Custom overloads of begin may be provided for classes and enumerations that do not expose a suitable begin() member function, yet can be iterated. Now consider this example: #include <iostream> #include <vector> class meow { enum { begin = 1, end = 2}; public: std::vector<int> data; }; // non-const iterators auto begin(meow& m){ return m.data.begin(); } auto end(meow& m) { return m.data.end(); } // const iterators auto begin(const meow& m){ return m.data.begin(); } auto end(const meow& m) { return m.data.end(); } int main() { meow m; for (const auto& e : m) {} } We want to iterate the meows data. But it does not work. The member interpratation is choosen, even though meow::begin and mewo::end are private and the begin and end functions could be used. Hence the error: <source>: In function 'int main()': <source>:17:26: error: 'meow::<unnamed enum> begin' is private within this context for (const auto& e : m) {} ^ <source>:5:12: note: declared private here enum { begin = 1, end = 2}; ^~~~~ <source>:17:26: error: 'begin' cannot be used as a function for (const auto& e : m) {} ^ <source>:17:26: error: 'meow::<unnamed enum> end' is private within this context <source>:5:23: note: declared private here enum { begin = 1, end = 2}; ^~~ <source>:17:26: error: 'end' cannot be used as a function for (const auto& e : m) {} ^ The example works fine when we remove the private enum: #include <iostream> #include <vector> class meow { //enum { begin = 1, end = 2}; public: std::vector<int> data; }; // non-const iterators auto begin(meow& m){ return m.data.begin(); } auto end(meow& m) { return m.data.end(); } // const iterators auto begin(const meow& m){ return m.data.begin(); } auto end(const meow& m) { return m.data.end(); } int main() { meow m; for (const auto& e : m) {} } Live Demo
70,866,834
70,867,528
How to get a bitmap from a hdc?
I can load a hbitmap into a hdc like this: Gdiplus::Color Color{ 255, 255, 255 }; hBitmap = NULL; Gdiplus::Bitmap* bitmap = Gdiplus::Bitmap::FromFile(L"home.png", false); if (bitmap) { bitmap->GetHBITMAP(Color, &hBitmap); delete bitmap; } BITMAP bm; GetObject(hBitmap, sizeof(bm), &bm); HDC hDCMem = CreateCompatibleDC(NULL); HBITMAP hBitmapOld = (HBITMAP)SelectObject(hDCMem, hBitmap); How could I do the reverse, getting back a bitmap loaded into a specific hdc? I would need first, retrieve the hbitmap and then the bitmap from it? How?
You can use GetCurrentObject() to access the HBITMAP (and HPALETTE) currently selected into an HDC. Alternatively, you can create a new HBITMAP of desired dimension and color depth, SelectObject() it into a new memory HDC, and then BitBlt()/StretchBlt() the source HDC into it. Either way, once you have an HBITMAP, you can create a new GDI+ Bitmap from it using the Bitmap(HBITMAP, HPALETTE) constructor or Bitmap::FromHBITMAP() method.
70,867,837
70,870,772
getline error in C++ code to swap uppercase to lowercase and vice-versa of a user inputted string
I am learning C++ and I came across this error that I cannot seem to fix. The code should get a string from the user, then swap the uppercase characters to lowercase characters, and lowercase characters to uppercase characters: #include <iostream> #include <string> using namespace std; void swapCase (const string& s) { string str; str.assign(s); for(int i=0;str[i]!='\0';i++) { if (str[i] >= 'A' && str[i] <= 'Z') //checking for uppercase characters { str[i] = tolower(str[i]); } //converting uppercase to lowercase else if (str[i] >= 'a' && str[i] <= 'z') //checking for lowercase characters { str[i] = toupper(str[i]); //converting lowercase to uppercase } } cout << str << endl; // output } int main() { const string str; cout << "Enter the string "; //prompt user getline(cin, str); // input swapCase(str); //send string to function return 0; } main.cpp:23:3: error: no matching function for call to 'getline' getline(cin, &str);
Let me summarize comments: how would I assign a variable to str if I want to keep it as const? answer is: U can't assign nothing to const variables, u can only initialize const variables. In your case u can do the following (showing only posibility not recommend do that): string temporary_str; getline(cin, temporary_str); // input const string str = temporary_str; // not assigning but initializing // cant do after initialization: str = tremporary_str; // it is assignation cant be done with const on left side swapCase(str); //send string to function this yours question made me think that u think that u cant pass non-const variables into swapCase. It's wrong: u can pass any string to swapCase. const modifier in function argument means that u wont change this variable inside function. So u can do simply: string str; cout << "Enter the string "; //prompt user getline(cin, str); // input swapCase(str); //send string to function Some other recomendations (in code comments): use std::isupper and std::islower like this: #include <iostream> #include <string> using namespace std; void swapCase (const string& s) { string str = s; // can be done without assign for(int i=0; i < str.size(); i++) // not sure that str[i]!='\0' is good idea for c++ { if (isupper(str[i])) //checking for uppercase characters { str[i] = tolower(str[i]); //converting uppercase to lowercase } else if (islower(str[i])) //checking for lowercase characters { str[i] = toupper(str[i]); //converting lowercase to uppercase } } cout << str << endl; // output } int main() { string str; cout << "Enter the string "; //prompt user cout << std::flush; // I recommend it to be exactly displayed on the screen getline(cin, str); // input swapCase(str); //send string to function return 0; } EDIT: some information about flushing: when u write cout << something; it not actually writes it immediately, it says save it to write and at one day it writes out (if program ends with 0 code it writes what it promise), actually flushing is happening time to time automatically but to force write what in internal buffer use std::flash or std::endl because it contains std::flush inside it, the other side of flushing it can slower the program, so if u know that u will write something and u don't actually need to be printed instantly don't use std::endl use \n because it causes flaush only in console but not in file (it was a rough approximation), see code below : #include <iostream> #include <fstream> int main() { std::cout << "This will be printed because endl have flush inside it" << std::endl; std::cout << "This will be printed because flush after it" << std::flush; std::cout << "This will be printed in console because in console \\n means flush \n"; std::ofstream example_file("example.txt"); example_file << "This will be printed in file because endl have flush inside it" << std::endl; example_file << "This won't be printed in file even with \\n because writing in file \\n doesn't mean flash \n"; std::cout << "This won't be printed"; _Exit(1); // imitates something bad happend }
70,867,866
70,868,038
C++ Passing templated functions to function
I need to pass a templated function to a function. Until now I haven't found any great advices on google. This is what I tried: #include <iostream> #include <sstream> using namespace std; struct event { bool signal; }; template<typename T> void out_stream(T &stream, event &evt) { stream << evt.signal; } template <typename F> void doOperation(F f) { event test; test.signal = 0; stringstream ss; f(ss, test); } int main() { doOperation(out_stream); return 0; } And that's the error the compiler gives me: main.cc:27:3: error: no matching function for call to 'doOperation' doOperation(out_stream); ^~~~~~~~~~~ main.cc:16:6: note: candidate template ignored: couldn't infer template argument 'F' void doOperation(F f) ^ 1 error generated. Some (I hope) useful information about my g++ compiler setup: Apple clang version 13.0.0 (clang-1300.0.29.30) Target: x86_64-apple-darwin20.6.0 Thread model: posix Thank you in advance :)
For this particular case, you could help the compiler deduce T by calling doOperation with out_stream<std::stringstream>. Also, within doOperation, you need to use f instead of F. [Demo] #include <iomanip> // boolalpha #include <iostream> // cout #include <sstream> // stringstream struct event { bool signal{}; }; template<typename T> void out_stream(T& stream, const event& evt) { stream << std::boolalpha << evt.signal; } template <typename F> void doOperation(F&& f) { std::stringstream ss{}; f(ss, event{true}); std::cout << ss.str() << "\n"; } int main() { doOperation(out_stream<std::stringstream>); } // Outputs: // // true As suggested in the comments though, other options you have instead of passing an instantiation of a function template are: Change out_stream to accept a std::ostream&. Pass a generic lambda that just calls the instantiation of the function template. [Demo] #include <iomanip> // boolalpha #include <iostream> // cout #include <sstream> // stringstream struct event { bool signal{}; }; void out_stream1(std::ostream& stream, const event& evt) { stream << std::boolalpha << evt.signal; } template <typename T> void out_stream2(T& stream, const event& evt) { stream << std::boolalpha << evt.signal; } template <typename F> void doOperation(F&& f) { std::stringstream ss{}; f(ss, event{true}); std::cout << ss.str() << "\n"; } int main() { doOperation(out_stream1); doOperation([](auto& stream, const auto& evt) { out_stream2(stream, evt); }); } // Outputs: // // true // true Notice also there are no templated functions, but function templates. out_stream is a function template and needs to be instantiated with a given type, e.g. out_stream<std::stringstream>, to become a function. In the call doOperation(out_stream);, the compiler is unable to deduce the type to instantiate out_stream with.
70,868,003
70,868,701
Calling functions and passing arguments through map in c++?
I've been trying to figure out how I can use std::map to call functions and pass arguments to said functions based on a key. I'm translating a project I made in Python to C++, but I've been stuck on this, and I really don't want to resort to a mess of if-elses. The way I did that in Python was as so: return_operation = { "*": Operations.multiply, "^": Operations.exponent, "**": Operations.exponent etc... } result = return_operation["*"](num_1, num_2) Is there some sort of way to accomplish this is C++? I've tried using std::map but I keep getting: Error C2276 '&': illegal operation on bound member function expression. I'm still very new to C++ and I'm totally lost. namespace std{ class Calculator { public: void multiply(double num_1, double num_2) { cout << "MULTIPLYING!" << endl; // Normally it would return the result of multiplying the two nums // but it only outputs to the console until I can figure this out. } void initialize() { void (Calculator::*funcPtr)(); funcPtr = &multiply; unordered_map<string, Calculator()> operator_function = { {"*", &multiply} }; } }; }
First off, you can't add custom types to the std namespace. Only specializations of existing templates. Second, you are using the wrong mapped type for the unordered_map. Try something more like this instead: class Calculator { private: typedef double (Calculator::*FuncType)(double, double); unordered_map<string, FuncType> operator_function = { {"*", &Calculator::multiply}, {"^", &Calculator::exponent}, {"**", &Calculator::exponent} // and so on ... }; double multiply(double num_1, double num_2) { cout << "MULTIPLYING!" << endl; return num_1 * num_2; } double exponent(double num_1, double num_2) { cout << "EXPONENT!" << endl; return pow(num_1, num_2); } public: double do_math(string op, double num_1, double num_2) { FuncType func = operator_function[op]; return (this->*func)(num_1, num_2); } }; Then, to call a function in the map, you can do this: Calculator calc; ... double result = calc.do_math("*", num_1, num_2); Online Demo Alternatively, Calculator doesn't really need to be stateful in this example, so the methods could be static to avoid needing an actual Calculator object: class Calculator { private: typedef double (*FuncType)(double, double); static unordered_map<string, FuncType> operator_function; static double multiply(double num_1, double num_2) { cout << "MULTIPLYING!" << endl; return num_1 * num_2; } static double exponent(double num_1, double num_2) { cout << "EXPONENT!" << endl; return pow(num_1, num_2); } public: static double do_math(string op, double num_1, double num_2) { FuncType func = operator_function[op]; return func(num_1, num_2); } }; unordered_map<string, Calculator::FuncType> Calculator::operator_function = { {"*", &Calculator::multiply}, {"^", &Calculator::exponent}, {"**", &Calculator::exponent} // and so on ... }; double result = Calculator::do_math("*", num_1, num_2); Online Demo Alternatively, you could use lambdas instead of class methods, eg: class Calculator { private: using FuncType = std::function<double(double, double)>; static unordered_map<string, FuncType> operator_function; public: static double do_math(string op, double num_1, double num_2) { if (op == "**") op = "^"; FuncType func = operator_function[op]; return func(num_1, num_2); } }; unordered_map<string, Calculator::FuncType> Calculator::operator_function = { {"*", [](double num_1, double num_2) { cout << "MULTIPLYING!" << endl; return num_1 * num_2; } }, {"^", [](double num_1, double num_2) { cout << "EXPONENT!" << endl; return pow(num_1, num_2); } } // and so on ... }; double result = Calculator::do_math("*", num_1, num_2); Online Demo
70,868,044
70,868,615
How to link Cmake project in CXX Rust and use on Rust?
I did this in cxx: fn main() { cxx_build::bridge("src/main.rs") .file("src/something.cc") .flag_if_supported("-std=c++17") .compile("my_demo"); } I want to link something.cc with another C++ library, but still run everything on Rust. I thus want to call C++ code, from Rust, and still have it compiled and linked using Cargo. All the projects I find are the inverse: compiling rust from Cmake and using on C++. So, how do I compile a cmake project from build.rs and link to something.cc?
cxx can work with Cargo and C++ build systems. autocxx might also be useful.
70,868,249
70,868,954
Rpath/Runpath handle with dependent shared libraries in CMAKE
I will put you in context: I have 2 third party shared libraries: libA.so and libB.so. My program contains only calls to libA.so symbols. The libA.so internaly needs to call to libB.so. If I readelf LibA.so it has a RunPath pointing to a path from the third party developer that doesn't exsist in my system. My program builds with cmake. I use find_library(A) and find_libary(B) and then add them to my program executable target with target_link_libraries(my_executable PUBLIC A B) With this setup the generated executable contains a correct RUNPATH for both libA.so and libB.so. The problem is that when running the executable the libB.so file is not found. I need to keep the .so files in the place they are. Setting up LD_LIBRARY_PATH env variable or moving to a ldd valid folder is not an option. I have tried these solutions and they work btw. How could I make the executable to find libB.so in this case. Thanks in advance.
You can change RPATH with a tool named patchelf: sudo apt install patchelf patchelf --set-rpath \$ORIGIN libMyLibrary.so Note that $ORIGIN here means "search in the folder where this library located". You can also combine values like this: \$ORIGIN:\$ORIGIN/../lib. This is convenient if you want to keep unix-like installation structure (executables in bin, libraries in lib).
70,868,297
70,870,762
Pathfinding in a lattice - help to understand example
I am working on a problem where I calculate the number of possible paths to a lattice of N * N possible options. There have been some mathematical answers that suggest a simple "combinatorics" answer, but I have no experience with combinatorics. Searching around I found this relatively short answer, but it does not make much sense to me, even when I try to step through the sequential logic to follow the code. #include <iostream> #include <vector> uint64_t lattice_path(size_t grid_size) { std::vector<uint64_t> grid((grid_size + 1) * (grid_size + 1), 1); for (int rows = grid_size - 1; rows >= 0 ; --rows) { for (int cols = grid_size - 1; cols >= 0; --cols) { int pos = (cols * (grid_size + 1)) + rows; grid.at(pos) = grid.at(pos + 1) + grid.at(pos + (grid_size + 1)); } } return grid.at(0); } int main() { std::cout << "Paths: " << lattice_path(20) << std::endl; return 0; } This code was taken from http://tvarley.github.io/blog/euler/cpp/problem_015 this website - (bad author for submitting answers xD) - some edits to make cleaner. I chose this code because of my goals to use STL containers and method/member functions to solve the problem, but the sequential logic makes little sense to me in this example. Usually the problems on projecteuler have simpler precursor examples (like the 2x2 grid) which are easy to model out in code by examining sequential logic. Then it is as simple as putting in the larger test. In this case, though, I can't really model out the simple lattice in code.
There are quite a few ways how you can arrive at the correct answer for this question, depending on how you approach it. I would highly recommend you to first try to solve the puzzle on your own & not to look at other solutions - that usually has the best learning effect. I'll only explain the logic behind the different approaches, but not provide any code examples for them. Number of paths to a specific point There are only two ways you can arrive at a certain point in the grid: either you come to it from the point directly above from it or from the point directly to it's left. For the top & left side of the grid it's easy; there is only one way to reach each point - by moving straight in the specific direction, e.g.: From that you can start to fill in the number of possible paths to each point. Because there are only 2 ways on how to get to each point, the number of possible paths to a specific point is the sum of the possible paths of the point directly to the left and the point directly above that point, e.g.: From that you can just keep going to fill in all the other points on the grid until you reach the bottom-right corner, which will contain your solution: In this case for a 3 × 3 grid the number of possible paths would be 20. This is also the approach your code sample uses: it calculates the number of possible paths for each point in the grid - although it does so from the bottom to the top instead of from the top to the bottom like in my example. Here's a godbolt that shows the grid your code is building. Noticing the pattern From the above approach you might notice two things: We calculate each number as the sum of two neighbors The numbers seem to follow some pattern In fact the numbers we were calculating are the binomial coefficients - notice how the 3 × 3 grid from above matches the elements of pascal's triangle: So you can cut out the grid calculation from above & instead simply calculate the binomial coefficient you're looking for. In this case for a x × y grid the formula would be: If we pluck in 20 for both x & y we get the correct answer as well: Always the same moves You're only ever allowed to move either right or down - so the only way to get one square down is to move down, and the only way to get to the right is a move to the right (and there's no way to move left / up) - so the amount of moves you make - regardless of which path you take - is always the same. Namely exactly the height of the grid moves down and exactly the width of the grid moves to the right. e.g. on a 4x3 grid you get exactly 4 moves to the right and 3 moves down: So at the beginning you have a "bag" of all moves you can make, in the above case it would be {⮞,⮞,⮞,⮞,⮟,⮟,⮟} and at every point of the path you get to choose if you want to take a ⮞ or a ⮟ from your bag, to move into that direction (unless you run out of one, in that case you only have one choice). The mathematical term for this "bag" would be a Multiset. In the above case we could also write it as {⮞⁴, ⮟³}, to make it shorter. Now to answer the question how many possible paths there are we need to find out how many possible ways there are to use the elements from our multiset, e.g.: ⮞⮞⮞⮟⮞⮟⮟, ⮟⮞⮟⮞⮟⮞⮞, etc... So we're looking for all possible permutations of our multiset (with the same length as we have elements in the multiset) This is called a multiset permutation, and the formula for it is quite easy to remember: where n is total amount of items in the multiset (7 in the example above), and m₁, m₂, etc... are the counts of each element in the set (in this case we just have m₁ = 4 and m₂ = 3, so n = 7). So to generalize it in a grid of size x × y the formula for the number of possible paths would be: If you pluck in 20 for both x & y into the above equation you get the same correct answer of 137846528820, for the number of possible paths in a 20 × 20 grid. This approach also has the benefit that it works in more than 2 dimensions, e.g. you could also solve a 3 dimensional variant of this puzzle with this.
70,869,324
70,869,735
CL/cl.hpp: No such file or directory | NVIDIA GeForce
Good afternoon! I'm trying to run code in C++ that has the following line: #include <CL/cl.hpp> But launching the program gives this error: fatal error: CL/cl.hpp: No such file or directory What have I tried to do? Completely reinstalling mingw64 Uninstalled Visual Studio 2019 and installed Visual Studio 2022 Installed NVIDIA Cuda according to the instructions (I also updated the NVIDIA drivers): https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/index.html Cuda is fully operational. I checked with the code examples that come with CUDA. P.S. As far as I know, OpenCl is part of CUDA. Thanks!
It is best to include the OpenCL headers in the same directory where the source code of your Visual Studio Project is. You then have to tell Visual Studio where these files are located. To configure the project and set the file paths, see this answer. You don't need to install CUDA at all. The OpenCL Runtime is included in the Nvidia graphics drivers already.
70,869,535
70,869,707
std::barrier is_nothrow_invocable_v<CompletionFunction&> shall be true error
I am trying to simulate a dice roll program, to be more specific get the number of rolls necessary to get n dices to be 6 at the same time. So this is a textbook example of fork-join model in order to simulate rolls simultaneously and then check result after each iteration. #include <iostream> #include <vector> #include <thread> #include <random> #include <array> #include <barrier> auto random_int(int min, int max) { static thread_local auto engine = std::default_random_engine{ std::random_device{}() }; auto dist = std::uniform_int_distribution<>(min, max); return dist(engine); } int main() { constexpr auto n = 5; auto done = false; auto dice = std::array<int, n>{}; auto threads = std::vector<std::thread>{}; auto n_turns = 0; auto check_result = [&] { ++n_turns; auto is_six = [](int i) {return 6 == i; }; done = std::all_of(std::begin(dice), std::end(dice), is_six); }; auto bar = std::barrier{ n,check_result }; for (int i = 0; i < n; ++i) { threads.emplace_back([&, i]{ while (!done) { dice[i] = random_int(1, 6); bar.arrive_and_wait(); }}); } for (auto&& t : threads) { t.join(); } std::cout << n_turns << std::endl; } And I am getting the following error: error C2338: N4861 [thread.barrier.class]/5: is_nothrow_invocable_v<CompletionFunction&> shall be true 1>C:\Users\eduar\source\repos\C++20\C++20\main.cpp(114): message : see reference to class template instantiation 'std::barriermain::<lambda_1>' being compiled Can someone please hint what am I doing wrong and how to fix this?
The issue is in the error message. Which is great, even cites exactly the part of the standard which has this requirement: [thread.barrier.class]/5: CompletionFunction shall meet the Cpp17MoveConstructible (Table 28) and Cpp17Destructible (Table 32) requirements. is_­nothrow_­invocable_­v<CompletionFunction&> shall be true. You're currently missing the last part: your lambda isn't nothrow-invocable. That's an easy fix tho: auto check_result = [&]() noexcept // ^~~~~~~~ { ++n_turns; auto is_six = [](int i) {return i == 6; }; done = std::all_of(std::begin(dice), std::end(dice), is_six); }; I also took the opportunity to flip your Yoda conditional, because there is no reason to write Yoda conditionals.
70,869,803
70,870,625
C++ - Code crashes when trying to sort 2d vector
I'm writing a code in C++ and it's always giving the same error: Segmentation Fault, but I don't know why this is happening. I've created a small program that gives the error. #include <vector> #include <iostream> #include <algorithm> using namespace std; int N = 17; vector<vector<int>> v; void func(vector<int>& x){ for(int i = 0; i < N; i++){ v.push_back(vector<int>(x)); } } int main(){ int n = 5; vector<int> v2(n, 0); func(v2); cout << v.size() << endl; // prints 17 sort(v.begin(), v.end(), [&n](const auto &a, const auto &b){ for(int i = 0; i < n; i++) if(a[i] != b[i]) return a[i] < b[i]; return true; }); return 0; } The function func is supposed to do a recursive computation. I pass v2 by reference because I push and pop elements from it. When I got to a certain point in recursion, I add it to the global 2d vector v. My code's working to every test case I tried except this one. The fun thing is that the programs works with no error when N < 17. The error is happening at the lambda sort. There is an 'a' that breaks the code. Even if erase the for loop, it still crashes. I know that using global variable is bad, but in competitive programming this is a common practice. I'm compiling with the following: g++ test.cpp && ./a.out My g++ version: (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 EDIT: Thanks to @DrewDormann, I managed to fix it. Just changing the return of the lambda function to false instead of true.
std::sort requires irreflexivity. From [alg.sorting] in the standard: The term strict refers to the requirement of an irreflexive relation (!comp(x, x) for all x) However, the lambda returns true for comp(x, x). The fun thing is that the programs works with no error when N < 17. It's undefined behavior. It's unlucky if it works by chance.
70,869,835
70,870,169
How to push objects to a static vector while in the contructor of a class in C++
I need to get in a vector the names of some cities as soon as they are created... In order to accomplish that I created a static vector for the class City, however when I try to compile my code I get the error error: lvalue required as unary '&' operand this->cities.push_back(&this); ^~~~ What am I doing wrong? My code is the following... #include <iostream> #include <ctime> #include <vector> using namespace std; class City { private: string name; static vector<City *> cities; public: string getName() { return name; } City(string name) : name{name} { this->cities.push_back(&this); }; ~City(){}; } hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"}; int main() { }
this is already a City* pointer, so drop the & from &this. Also, don't forget to actually define the static vector object. Also, you should account for the class' copy/move constructors and destructor, to make sure you don't miss adding pointers, or leave behind dangling pointers. Try this: #include <iostream> #include <ctime> #include <vector> using namespace std; class City { private: string name; static vector<City *> cities; public: string getName() { return name; } City(string name) : name{name} { cities.push_back(this); } City(const City &src) : name{src.name} { cities.push_back(this); } City(City &&src) : name{std::move(src.name)} { cities.push_back(this); } ~City() { cities.erase(std::find(cities.begin(), cities.end(), this)); } }; vector<City *> City::cities; City hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"}; int main() { }
70,869,846
70,869,859
How to delete/free a string literal?
I have a std::vector<const char*> which I populate by .push_back("something"). How to delete contents not including std::string's header? delete segfaults, and std::free needs void* and it "cannot initialize [..] with an lvalue of type 'const char *'".
String literals have static storage duration. You may not delete them using the operator delete. String literals will be alive until the program ends, You may delete what was created using the operator new. You can just erase all or selected elements of the vector or clear it entirely.
70,869,946
70,871,569
When not to use auto as described in Bjarne Stroustrup book: A Tour of C++
I was reading A Tour of C++ and got confused as to the reason to use auto. We use auto where we don’t have a specific reason to mention the type explicitly. ‘‘Specific reasons’’ include: • The definition is in a large scope where we want to make the type clearly visible to readers of our code. • We want to be explicit about a variable’s range or precision (e.g., double rather than float). I get the part that if we are in a large scope, we want people to see the types but I don't get the part about being explicit about a variable's range? What's meant by range here? Is it the same as precision? EDIT: this question was closed but what the question I have asked is directed at what the author means and the example provided. Nothing broad about it. I don't see how that can stray into opinion-land as I am not asking why auto should ever be used but what is meant by range. The comments provided provide an answer.
The "range" of a variable in that sentence refers to the minimum and maximum values it can hold. For example, the range of a signed char is typically -128 to 127.
70,870,193
70,870,308
Introduce variable in a C++ constraint
Given a require block on a struct such as this one template<typename A, typename B, typename C> struct MyOtherTypeLevelFunction<A, B, C>; template<typename A, typename B, typename C> requires (MyConcept<MyTypeLevelFunction<A, B, C>>) && (MyOtherConcept<MyTypeLevelFunction<A, B, C>>) struct MyOtherTypeLevelFunction<A, B, C> { using Output = MyTypeLevelFunction<A, B, C>::T; } Is is possible to introduce a variable to avoid repeating calls to MyTypeLevelFunction? Ideally both in the requires block and the structure body. I tried the following, but it fails with Default template argument in a class template partial specialization. template<typename A, typename B, typename C> struct MyOtherTypeLevelFunction<A, B, C>; template<typename A, typename B, typename C, typename X = MyTypeLevelFunction<A, B, C>> requires (MyConcept<X>) && (MyOtherConcept<X>) struct MyOtherTypeLevelFunction<A, B, C> { using Output = X::T; }
You can create a combined concept: template <typename F> concept MyCombinedConcept = MyConcept<F> && MyOtherConcept<F>; template<typename A, typename B, typename C> requires MyCombinedConcept<MyTypeLevelFunction<A, B, C>> struct MyOtherTypeLevelFunction<A, B, C> { using Output = MyTypeLevelFunction<A, B, C>::T; } and optionally put MyCombinedConcept in a detail namespace if it's an implementation detail.
70,870,201
70,870,594
Hashing words in C++?
I have a text file that I read the data from and search the names inside to keep track of it. I want to use Hashing instead of Arrays for the speed of search, and I don't want to insert a name twice if it's already included in the hash. (I found some code about hashing but the example code was for numbers not for strings or words. How should I approach? Keep the first letter in ASCII or combine all letters and % by a number? Not sure exactyle how to do it.) Can you provide a short sample code if it's possible? Let's say; get every word in a text file with Getline and add it to Hash Table if the word is not included already. Method does not matter (Chaining, linear probing etc.) Please do not use any fancy library.
You can just use an unordered_set #include <string> #include <unordered_set> #include <fstream> std::unordered_set<std::string> file_to_unordered_set(const std::string& filename) { std::unordered_set<std::string> tbl; std::ifstream fs(filename); if (!fs) { throw std::runtime_error("bad file"); } std::string line; while (std::getline(fs, line)) { tbl.insert(line); } return tbl; } int main() { auto words = file_to_unordered_set("<some file path>"); return 0; }
70,870,562
70,871,142
Explaining output (inheritance, c++)
Consider the following program: using namespace std; class A{ private: int _a; public: A(int a): _a(a) {cout<<"A-ctor: a= "<<_a<<endl;} A(const A& other) : _a(other._a) { cout<< " A-copy ctor: _a= " << _a<< endl; } ~A() {cout << "A-dtor" << endl;} }; class B{ private: A* _aPtr; public: B(int a=0) : _aPtr(new A(a)) { cout << "B-ctor"<<endl;} ~B() {cout<<"B-dot"<<endl; delete _aPtr;} }; class C:public B{ public: C(int a=5) : B(a) {cout<< "C-ctor"<<endl;} C(const C& other) : B(other) {cout<< "C-copy ctor"<<endl;} ~C() {cout<<"C-dtor"<<endl;} }; int main() { C c1; C c2(c1); return 0; } I would expect a compilation error since B does not have a copy-constructor and we try to use with C c2(c1) But the actual output is: A-ctor: a= 5 B-ctor C-ctor C-copy ctor C-dtor B-dot A-dtor C-dtor B-dot A-dtor Why there is no compilation error here? Thanks in advance.
I would expect a compilation error since B does not have a copy-constructor But B does have a copy-constructor. Its copy constructor is implicitly defined. Why there is no compilation error here? Because the program is well-formed. But even if it has a copy constructor, I suppose the copy would be shallow, meaning the pointer field of the instances that was passed by reference would be copy in a shallow way and basically would point to the same location in the heap memory Correct. so how come A -dtor appears twice in the output? Once the second C object, and its B base sub object is destroyed, the same pointer that had been invalidated by the destructor of the first B object will be deleted again. The consequence is that the behaviour of the program is undefined. The program is broken; don't do this. When you release a resource - such as dynamic memory - in a user defined destructor, you typically have to implement the copy and move assignment operators and constructors, because the implicit definitions would have counter-productive behaviour. This is known as the rule of 5 (known as rule of 3 prior to C++11). You have violated the rule of 5 by relying on the implicit constructor despite releasing dynamic memory in the destructor. More generally, I recommend studying the RAII idiom. Furthermore I recommend that you avoid owning bare pointers such as _aPtr and use smart pointers such as std::unique_ptr instead. Lastly, I recommend avoiding unnecessary dynamic allocation.
70,871,299
70,871,583
Make the compiler deduce the parameter of a function before compilation
Here is an example of my problem. #include <stdio.h> //template<std::size_t A> <-- Tried to solve the problem by using template void func1(const int power){ const int length = 1 << power; int twoDArrayA[length][length]; for (int j = 0; j < power; j++) { /* Code */ } } int main() { func1(4); func1(3); func1(2); } I wonder if I could somehow allow the compiler to deduce parameter power in func1 before it compiles. So instead of compiles one function, it compiles 4 functions in the format of func1 with different power value. The reason for this is because I would like to use Vitis HLS to unroll the loop and partition the matrix so that it could be implemented onto a FPGA, where a variable-length loop or array cannot work properly.
You can do this with a template, but you've got the wrong syntax. It should be: template<std::size_t power> void func1(){ const std::size_t length = 1 << power; int twoDArrayA[length][length]; ... } int main() { func1<4>(); ... } Note that your variable length array (VLA) is legal C++ if length is a compile-time constant (as it is here). Nevertheless, std::array would be a better bet. PS: Thanks for telling us why you want to do this. That was a nice touch.
70,871,732
70,871,784
How to use commas to split chars in a loop?
I'm writing a program in c++ and I'm trying to separate letters like this: "A,B,C" But it comes out like this, and I don't know why: ",A,B,C". Help? My code is below: #include <iostream> #include <ctype.h> using namespace std; int main() { char startChar='Z'; char stopChar='A'; while (startChar>stopChar) { cin >> startChar; startChar = toupper(startChar); cin >> stopChar; stopChar=toupper(stopChar); } for (char chLoop=startChar; chLoop<=stopChar; chLoop++) { if (stopChar > startChar) cout << ","; cout <<chLoop; } } thanks!
When stopChar is C and startChar is A, this condition will be true and therefore a , will be printed in every iteration of the loop (including the first): if (stopChar > startChar) cout << ","; You can fix it by changing it to: if (chLoop != startChar) std::cout << ','; That is, only if chLoop is not startChar, print a ,. Another option that doesn't require an if at all: std::cout << startChar; // print the first char before the loop for (char chLoop = startChar + 1; chLoop <= stopChar; chLoop++) { std::cout << ',' << chLoop; // now print the , unconditionally }
70,871,840
70,871,856
How to remove the leading 0 and the last 0 in this code?
I am attempting to write a program that asks for user input of a positive integer larger than 2. The program is supposed to output all the positive integers that are smaller than the user input and that are multiples of 3. However, when running my code I noticed there are two annoying 0’s that keep appearing and aren’t supposed to be there. Any help on how to remove them or make the code better? Thank you! #include <iostream> using namespace std; int get_numbers(int x) { for (int i = 0; i < x; i += 3) { cout << i << " "; } return 0; } int main() { int integer = 0; cout << "Enter a positive integer larger than 2: "; cin >> integer; cout << get_numbers(integer); }
Let's walk through your code and explain it. There are 2 important parts that have cout: for (int i = 0; i < x; i += 3) { cout << i << " "; } What does this loop mean? Well Start i at 0 Go while i is less than x Increment i by 3 Print every i. The important part is 1. You are starting i at 0, you will print 0. To fix this, don't start at 0! Start at a different number (probably 3 from your description of the desired behaviour). The other cout is here: cout << get_numbers(integer); You are printing the return of the function get_numbers. If you look in that function, it only returns 1 thing: return 0; So you are going to print 0! This function doesn't need to return anything, so just do: void print_numbers_in_increments_of_3(int x); And remove the cout.
70,872,391
70,872,666
Unable to retrieve a static vector from inside a class
I want to get a vector from the class City, however I am not able to see any of those cities generated, in the vector cities being displayed... However I do know that they are being generated as I can see their names as well as the size being incremented being displayed in the constructor. Contructor for: Hong Kong 1 Contructor for: Bangkok 2 Contructor for: Macau 3 Contructor for: Singapura 4 Contructor for: Londres 5 Contructor for: Paris 6 Contructor for: Dubai 7 Contructor for: Delhi 8 Contructor for: Istambul 9 Contructor for: Kuala 10 Contructor for: Lumpur 11 Contructor for: Nova Iorque 12 Contructor for: Antalya 13 Contructor for: Mumbai 14 Contructor for: Shenzen 15 Contructor for: Phuket 16 What am I doing wrong?? Bellow is my code: As you can see I have commented out the destructor, however I am still unable to see any city in the vector, as calling the function display_cities() will render nothing but a 0, being displayed: #include <iostream> #include <ctime> #include <vector> using namespace std; class City { private: string nome; static vector<string> cities; public: static vector<string> getCidades() { return cities; } string getNome() { return nome; } City(string nome) : nome{nome} { this->cities.push_back(this->nome); cout << "Contructor for: " + this->nome << endl << this->cities.size() << endl; }; // ~City(){}; } hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"}; vector<string> City::cities; void display_cities() { vector<string> cities = City::getCidades(); cout << cities.size() << endl; for (size_t i = 0; i < cities.size(); i++) { cout << cities[i] << endl; } } int main() { display_cities(); return 0; }
You have to create a city object in main. Try passing all those constructors in main as a city object. Also, I compile your original code with vs c++17 and it throws an exception. int main() { City hongKong{ "Hong Kong" }, bangkok{ "Bangkok" }, macau{ "Macau" }, singapura{ "Singapura" }, londres{ "Londres" }, paris{ "Paris" }, dubai{ "Dubai" }, delhi{ "Delhi" }, istambul{ "Istambul" }, kuala{ "Kuala" }, lumpur{ "Lumpur" }, novaIorque{ "Nova Iorque" }, antalya{ "Antalya" }, mumbai{ "Mumbai" }, shenzen{ "Shenzen" }, phuket{ "Phuket" }; display_cities(); return 0; }
70,872,795
70,872,841
what does the arrow operator means and how can be converted to python?
i am new to c++ and i know so much more python than c++ and i have to change a code from c++ to python, in the code to change i found this sentence: p->arity = std::stoi(x, nullptr, 10); i think for sake of simplicity we can use p->arity = x; /* or some whit pointers im really noob on c++ but i think this is not importan */ in python does this means something like p[arity] = x or similar? or what? im a little lost whit all these new(for me) concepts like pointers and memory stuff but now whit -> operator thanks in advance
What I understand about the arrow operator from this post: An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. Since Python doesn't deal with pointers, this is not directly comparable. However, you can think of its usage as similar to the dot operator in Python. class Random: arity = 0 p = Random() p.arity = x
70,873,074
70,873,241
Using member function without taking address?
class C{ public: int i(){return 3;} }; void memfn(int (C::* const & func)()){} void fn(int (* const & func)()){} int main() { fn(&foo); //Works fn(foo); //Works memfn(&C::i); //Works memfn(C::i); //Doesn't Work } When passing a function pointer as a parameter, the address-of operator is optional on the function. Why does it not work if removed on a member function?
There is an implicit conversion from global function references, or static member function references, or non-capturing lambdas, to function pointers. This is for capability with C. But such implicit reference-to-pointer conversions are not for non-static member functions (and capturing lambdas!), because they need an implicitly passed this pointer to work, the conversion just lacks that thing. In your case, if we make i() static, then it can be passed to fn either by reference or by address.
70,873,103
70,873,404
push_back crashed when using std::vector if the type only defined copy constructor with c++11
The code like this: #include <iostream> #include <vector> struct Foo { int i; double d; }; class Boo { public: Boo() : fptr(nullptr) { std::cout << "Boo default construct..." << std::endl; } Boo(int i, double d):fptr(new Foo{i,d}) { } Boo(const Boo &rhs) :fptr(new Foo{rhs.fptr->i,rhs.fptr->d}) { } Foo *fptr; }; int main(int argc, char const *argv[]) { std::vector<Boo> vec(1); Boo b(42, 10.24); vec.push_back(b); return 0; } Env: Ubuntu 16.4 LTS with gcc 5.4 g++ -std=c++11 test.cpp -o test -g ./test If define move constructor,this will work good. I debuged it several hours but can not found what's wrong with it, maybe because some rules in c++ 11 that i did't know. Could somebody help me? Thanks!
The problem is that in the copy constructor of Boo you're dereferencing a nullptr. This is because when you wrote: std::vector<Boo> vec(1); //this creates a vector of size 1 using Boo's default constrcutor This is what happens due to the above statement: The above statement creates a vector named vec of size 1 using Boo's default constructor. This means that there is already 1 Boo object inside vec. Moreover since this Boo object was created using the default constructor, its fptr is set to nullptr. Now, when you wrote: vec.push_back(b);// this adds/push_back object b onto the vector vec so that now its size will be 2 Now, these are the important things that you have to note here: The vector vec has already 1 Boo object inside it which has its fptr as nullptr. Now you're adding one more element b into the vector, due to which reallocation may happen. And if/when this reallocation happens, the copy constructor of Boo will be used. And when this copy constructor is used to copy the already present Boo object, it dereferences its fptr. But since that fptr is nullptr and we know that dereferencing a nullptr is undefined behavior, so this may cause the program to segmentation fault as in your case. Solution First, before dereferencing fptr you should check it is a null pointer or not. Second, you must free the memory you allocated via new using delete. This can be done by adding a destructor for class Boo and using delete on fptr inside it. If you don't free this memory then you will have memory leak in your program. #include <iostream> #include <vector> struct Foo { int i; double d; }; class Boo { public: Boo() : fptr(nullptr) { std::cout << "Boo default construct..." << std::endl; } Boo(int i, double d):fptr(new Foo{i,d}) { std::cout <<"Boo parameterized const"<<std::endl; } Boo(const Boo &rhs) { std::cout <<"Boo copy const"<<std::endl; //add a check before dereferencing if(rhs.fptr!= nullptr) { fptr = new Foo{rhs.fptr->i,rhs.fptr->d}; std::cout<<"i: "<<rhs.fptr->i <<" d: "<<rhs.fptr->d<<std::endl; } else { std::cout<<"nullptr found"<<std::endl; } } Foo *fptr; //add destructor ~Boo() { std::cout<<"Boo destructor"<<std::endl; //for debugging check if we got a null pointer if(fptr!=nullptr) //just a check before deleting, you can remove this. This is for printing(debugging) when we get a nullptr { delete fptr; fptr = nullptr; std::cout<<"delete done"<<std::endl; } else { std::cout<<"null pointer found while delete"<<std::endl; } } }; int main(int argc, char const *argv[]) { std::vector<Boo> vec(1); Boo b(42, 10.24); vec.push_back(b); return 0; }
70,873,585
70,873,635
sqlite '=': cannot convert from 'const char [164]' to 'char *'
I am running the code example for sqlite from here to create a table in C++, here is the code: #include "../contrib/sqlite/sqlite3.h" static int callback(void* NotUsed, int argc, char** argv, char** azColName) { int i; for (i = 0; i < argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3* db; char* zErrMsg = 0; int rc; char* sql; /* Open database */ rc = sqlite3_open("test.db", &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stdout, "Opened database successfully\n"); } /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" \ // Error is here at the '=' "ID INT PRIMARY KEY NOT NULL," \ "NAME TEXT NOT NULL," \ "AGE INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Table created successfully\n"); } sqlite3_close(db); return 0; } But then I get some errors from visual studio 2022 that say: a value of type "const char *" cannot be assigned to an entity of type "char *" '=': cannot convert from 'const char [164]' to 'char *' Does anyone know how to fix this error?
The problem is your sql variable. It is a char* pointer, which is a pointer to non-const character data. But you are trying to assign it to point at a string literal, which is const character data (in this case a const char[164] array). Assigning a non-const character pointer to point at const character data is dangerous, as it allows read-only strings to be mutatable, which is undefined behavior. In C (which the example you are looking at was written for) and old versions of C++, such an assignment is legal (albeit not recommended), but in C++11 onward it is illegal. You need to change the declaration of sql to const char* instead (which is what sqlite3_exec() is expecting anyway).
70,873,632
70,873,827
Moving array elements over one position
I have a homework assignment where we're supposed to create a list of integers, and allow the user to INSERT an integer at a given position in the list. The list should essentially move all integers over one position in the array, then insert the integer that the user input at the index they chose. So let's say I have an array of {1, 2, 3, 4, 5} and I want to put 9 in index 1, the array should then be {1, 9, 2, 3, 4, 5}. I thought I figured out the solution with this function: void *INSERT(int count, int userNum, int index, int array[]){ //Accepts count of array, users number, users index, and array int tempIndex = index; index--; for(int counter = 0; counter < count; counter++) { array[tempIndex] = array[tempIndex-1]; tempIndex++; } array[index] = userNum; } Here is what I have in the main function: int index = 0; //Hold users index selection int userNum = 0; //Hold users number int n = 10; int a[n] = {1, 2, 3, 4, 5}; int *ptr = a; cout << "Enter a number to insert: "; cin >> userNum; cout << "Enter an index: "; cin >> index; INSERT(n, userNum, index, ptr);//call insert function (Accepts count of array, users number, users index, and array) int listNum = 1; for(int i = 0; i < n; i++) { cout << listNum << ". " << a[i] << "\n"; listNum++; } However, this is the output after printing the array: 1. 1 2. 9 3. 2 4. 2 5. 2 6. 2 7. 2 8. 2 9. 2 10. 2 I'm not sure where I'm going wrong here that could be causing this output. If I remove the -1 from the INSERT functions for loop like this(commented it out to make it more clear on what's being changed): void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array int x = i; i--; for(int r = 0; r < c; r++) { a[x] = a[x/*-1*/]; x++; } a[i] = n; } I get the following output with the above code, which is what I'd expect but not what I need. I can post the entire code if needed as well, but I think this explains where the problem is. Thanks in advance for the help 1. 1 2. 9 3. 3 4. 4 5. 5 6. 0 7. 0 8. 0 9. 0 10. 0
Based on your code, just change your insert function to this - Here we first shift the values to next index in the array and then perform insertion of respective element void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array for(int r = c-1; r >= i; r--) { a[r+1] = a[r]; } a[i] = n; }
70,873,688
70,875,434
How to define the operator= for a unique_ptr wrapper class?
I am trying to create a wrapper class for the std::unique_ptr, for now it just needs to support the basic operations for the unique_ptr, but in the future this would have more functionalities. template<typename T> class Unique { public: Unique(std::nullptr_t) { pointer = nullptr; } template<typename ...Args> Unique(Args&&... args) { pointer = std::make_unique<T>(std::forward<Args>(args)...); } T operator*() const { return *pointer.get(); } T* operator->() const { return pointer.get(); } // operator=() ? private: std::unique_ptr<T> pointer; }; Doing Unique<Foo> foo() works just fine, but the problem happens when I try to do Unique<Foo> bar = foo, a compiler error happens saying error: no matching function for call to ‘Foo::Foo(Unique\<Foo\>&)’ { return unique\_ptr<\_Tp>(new \_Tp(std::forward<\_Args>(\_\_args)...)); } How can I define a operator= to make this work?
Turns out, as @che.wang pointed out, I actually needed a Converting Assignment Constructor based on (2) from the unique_ptr reference like: template<typename U> Unique(Unique<U>&& other) { pointer = std::move(other.pointer); }
70,873,747
70,874,568
In this syntax, what is the actual type of auto?
In the C++17 for loop syntax for(auto [key, val]: students), what is auto replacing? If students was, for example std::map<int,char*>, what would be written if not auto? I don't understand what it even is taking the place of. [int,char*]?
type [a,b,c] is a structured binding, and those force you to use auto (possibly decorated with const and/or &/&&). But aside from that, auto expands to the same type it would expand to if [...] was replaced with a variable name. In for (auto elem : students) ... auto expands to std::pair<const int, char *>. In a structured binding it expands to the same type, but the resulting "variable" of this type is unnamed. Then, for each name in brackets, a reference (or something similar to a reference) is introduced, that points to one of the elements of that unnamed variable.
70,873,915
70,874,275
Modifying class variables using functions during a combat do while loop C++
Feel free to let me have it for being a noob here as I have only been programming for about a month in my spare time haha... but I made the terrible decision to try making an RPG, which I have since redacted while I keep learning the basics, and am now trying the most condensed form of an RPG-style combat system I could conceptualize, hoping I can expand on it later once I have learned more. THE PROBLEM: I have a very basic understanding of C++ functions and classes, and my goal for practice is to create a series of character classes with RPG-esk stats and pseudo-random modifiers which I can call and do calculations upon. To test the combat system functions, I wanted to write a simple loop with output statements. Two preexisting characters, the hero and the enemy, attack each other in turns until one's health drops to zero and the loop ends. Each attack is a simple base stat with a rand modifier, then with the later intention of adding an armor stat to mitigate some of the damage. The issue is I don't quite understand how to call and modify the values in the classes yet. The code I have so far (shown below) is providing me this error: "message": "initial value of reference to non-const must be an lvalue" I know where the problem is for the most part, but unable to figure out what is surely a simple fix to resolve the problem and continue with building out this (should be) straight forward looping fight sequence. I have tried looking up pointers, and pass by references and adding additional functions to calculate the modifiers, as well as moving the class information around, but frankly, I'm still too new to see what it is I need to do. Any and all help is appreciated, including just pointing me in the right direction with a hint so I can hunt down the solution on my own. I'm sure once I get a basic understanding of what's holding me up here, the rest I can muddle through. Thanks! CURRENT CODE #include <iostream> #include <ctime> #include <cstdlib> class hero { public: int playerAttackMod; int playerDefenceMod; int playerHealth; int playerDamage; int playerDefence; }; class enemy { public: int enemyAttackMod {rand() % 25 + 1}; int enemyDefenceMod {rand() % 5 + 1}; int enemyHealth {300}; int enemyDamage = 50 + enemyAttackMod; int enemyDefence = 8 + enemyDefenceMod; }; int main() { srand(time(0)); void damageCalc(); std::cout << "A hero and enemy meet and prepare to fight to the death!\n" << "Let's watch to see how it plays out!\n\n" << "The enemy strikes first!\n" << "***********************************************************************" << std::endl; while (hero().playerHealth >= 0 && enemy().enemyHealth >= 0) { std::cout << "Hero's Health: " << hero().playerHealth << std::endl; std::cout << "Enemy's Health: " << enemy().enemyHealth << std::endl; std::cout << "The enemy attacks and does " << enemy().enemyDamage << " damage!\n"; hero &playerHealth = hero().playerHealth - enemy().enemyDamage; //THIS APPEARS TO BE THE TROUBLE MAKER...BUT ITS PROBABLY A DEEPER ISSUE THAN THIS... } std::cout << "\nThe hero has died!\n"; }
There are a few potential issues with your code. First, in your while loop, every time you write hero() or enemy() you create a new instances of the classes hero and enemy, respectively. That is also leading to the compiler error you received. Apart from the error, there is an other issue with that. Every new instance is initialized with the default values that you provided. This means that neither hero nor enemy are loosing any health. In addition, since you dont have any variables for holding the new instances they are deleted once the command where you called hero()orenemy()` is finished. What you could do instead instead is to create variables for the hero and enemy before the loop: hero h; enemy e; while (h.playerHealth >= 0 && e.enemyHealth >= 0) { ... The next problem is the missing default arguments in the hero class. In C++ built in types like int have no default values (in most cases). Thus, the members of hero can have any arbitrary value. So you should either add some default values to the class definition, or you could initialize all members once you create an instance of the hero class. The next issue does arise from the changes I suggested earlier. If you create an instance of class enenmy the enemyAttackMod and enemyDefenceMod members get a random value. However, this value is not changed anymore. So you might removing the mods from the classes and add recalculate them in every loop iteration before adding them to your damage calculation. Unless of course if random but fixed mods is what you want. The last thing is more about names. If you have a class hero or enemy, you can simplify the member names from enemyHealth to just health. When accessing the member you would yous e.health which already indicates that you are dealing with the health of the enemy instance e. That makes your code shorter and potentially easier to read. But this last issue is more a matter of taste than anything else.
70,873,962
70,874,076
What is time complexity of "isalnum(char)" in c++?
isalnum(char) is a method which tells us, whether a given character is alphanumeric or not. What is the time complexity of this small function? I have written a small subroutine : bool check(string s,int i) { if((s[i]>='a' && s[i]<='z') || (s[i]>='0' && s[i]<='9') || (s[i]>='A' && s[i]<='Z')) { return true; } return false; } Is the above subroutine works same as isalnum(char) method? Are there time complexities same?
These functions are different, because isalnum takes int. If you ask about the actions they perform, they are also different. isalnum('\xdf'), default C locale, returns false isalnum('\xdf'), ISO-8859-1 locale, returns true check("\xdf", 0) always returns false. Time complexities in the both cases are similar, O(1). Your function may be faster, since it does not use locales.
70,874,864
70,875,779
Eigen::Vector declare with max entries at compile time?
Is there a way to declare an instance of Eigen::Vector while specifying the max. number of elements at compile time? For the case of Eigen::Matrix it is possible to do it via Eigen::Matrix<int,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor,128,128> myMat; but I don't seem to find a way to do it for Eigen::Vector. Thanks!
Eigen::Vector is just an alias template for an Eigen::Matrix of column size 1, without allowing to specifying an argument for the _MaxRows template parameter of the aliased Eigen::Matrix class template. Global matrix typedefs template<typename Type , int Size> using Eigen::Vector = Matrix< Type, Size, 1 > You could always setup your own custom alias that would allow forwarding an argument to _MaxRows: template<typename Type, int Size, int MaxRows> using MyMaxSizedVector = Eigen::Matrix< Type, Size, 1, Eigen::ColMajor, MaxRows>;
70,875,281
70,876,163
Automatically migrate JSON data to newest version of JSON schema
I have a service running on my linux machine that reads data stored in a .json file when the machine is booting. The service then validates the incoming JSON data and modifies specific system configurations according to the data. The service is written in C++ and for the validation im using https://github.com/pboettch/json-schema-validator. In development it was easy to modify the JSON schema and just adapt the data manually. I've started to use semantic versioning for my JSON schema and included it the following way: JSON schema: { "$id": "https://my-company.org/schemas/config/0.1.0/config.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", // Start of Schema definition } JSON data: { "$schema": "https://my-comapny.org/schemas/config/0.1.0/config.schema.json", // Rest of JSON data } With the addition of the version, I am able to check if a version mismatch exists before validating. What I am looking for is a way to automatically migrate the JSON data to match the newer schema version, if a version mismatch is identified. Is there any way to automatically achieve this, or is the only way to manually edit the JSON data to match the schema? Since I plan on releasing this as open source I would really like to include some form of automatic migration so I can just ask the user if he wants to migrate to conform to the newest schema version instead of throwing an error, if a version mismatch was identified.
What you're asking for is something which will need to make assumptions to work. This is an age old problem and similar for databases. You can have schema migrations generated with many simple changes, but this is not viable if you wish to translate existing data automatically too. Let's look at a basic example. You rename a field. How would a tool know you've renamed a field vs removed an old one and added a new one? It essentially, cannot. So, you need to write your migrations by hand. You could use JSON transformation tools like jq or fx to create migration scripts without writing it in code, which may or may not be preferable. (jq has a steeper learning curve but it's also very powerful.)
70,876,266
70,876,440
can't find overloaded method from inherited class template
This is the first time I am using class templates so please don't be to harsh if I made a simply mistake. I have a class template class A<class T>. It has a method init() that is pure virtual and therefore will be implemented separately in every derived class. What all these possible derived classes will have in common is an init(T* i_x) which basically does some general stuff and then calls the init(). Because this will be the same for every derived class I want to define it in the base class template already. But somehow my compiler doesn't find the right function. If I try to use the init(T* i_x) on an object of a derived class A_der I get the error: no matching function for call to 'A_der::init(B_der*) The classes used for the template parameter T will all be derived from another class B. Therefore the error message involves the class B_der which is derived from class B. I boiled the problem down to a small example, which should involve everything that is important for the problem. If I try to compile this example in Visual Studio (normally I work in STM32CubeIDE) I get the following error Severity Code Description Project File Line Suppression State Error C2660 'A_der::init': function does not take 1 arguments template_class-overload_inherited_method [...]\main.cpp 8 So somehow the only function the compiler finds at this point is init() but not the base class template method init(T* ). Can somebody please tell me why it is like that and what can I do to get the behaviour I want (without implementing a similar init(T* ) in every derived class of A? Here is my example code: base class template A - declaration - A.hpp template<class T> class A { protected: T* m_x; public: virtual void connect(T* i_x) final; virtual void init() = 0; virtual void init(T* i_x) final; }; base class template A - implementation - A.cpp #include "A.hpp" template<class T> void A<T>::connect(T* i_x) { //some checks m_x = i_x; //connects object of B to A } template<class T> void A<T>::init(T* i_x) { connect(i_x); init(); } derived class A_der #include "A.hpp" #include "B_der.hpp" #pragma once class A_der : public A<B_der> { void init() override; }; void A_der::init() { //Initialization which needs a B_der connected already } main.cpp #include "B_der.hpp" #include "A_der.hpp" int main(void) { B_der testB; A_der testA; testA.init(&testB); return 0; } For the sake of completeness: class B { }; class B_der : public B { }; EDIT - Solved Thanks a lot for the fast replies. The combination of the comments from @BoP and @Jarod42 solved the problem. I had to unhide the method with using A<B_der>::init (actually renaming might be the more elegant way) and move the implementation of A into A.hpp. I will offer the updated example which builds successfully with Visual Studio 2019 for me here: base class A template<class T> class A { protected: T* m_x; public: virtual void connect(T* i_x) final; virtual void init() = 0; virtual void init(T* i_x) final; }; template<class T> void A<T>::connect(T* i_x) { //some checks m_x = i_x; //connects object of B to A } template<class T> void A<T>::init(T* i_x) { connect(i_x); init(); } derivad class A_der A_der.hpp #include "A.hpp" #include "B_der.hpp" class A_der : public A<B_der> { public: void init() override; using A<B_der>::init; }; A_der.cpp #include "A_der.hpp" void A_der::init() { //Initialization which needs a B_der connected already } main.cpp #include "B_der.hpp" #include "A_der.hpp" int main(void) { B_der testB; A_der testA; testA.init(&testB); return 0; } for completeness B.hpp class B { }; B_der.hpp #include "B.hpp" class B_der : public B { }; I also forgot to make the methods of A_der public in the earlier example, this is corrected here. And I removed the #pragma onces in this example.
class A_der : public A<B_der> { void init() override; }; When you declare a function init in the derived class, it hides all things named init from the base class. This is just like when declaring something in an inner scope - it hides things with the same name from outer scopes. There are ways to import the hidden names, but an easy solution would be to just chose a different name, like init_base. Or, probably better, pass a parameter to the class constructor.
70,876,567
70,876,820
Any way to trick std::transform into operating on the iterator themselves?
So I wrote this code which won't compile. I think the reason is because std::transform, when given an iterator range such as this will operate on the type pointed to by the iterator, not the iterator itself. Is there any simple wrapper, standard lib tool, etc. to make this code work i.e. to store all the iterators of the original map into a new vector, with minimum changes required? Thanks! #include <map> #include <iostream> #include <vector> using MT = std::multimap<char, int>; using MTI = MT::iterator; int main() { MT m; m.emplace('a', 1); m.emplace('a', 2); m.emplace('a', 3); m.emplace('b', 101); std::vector<MTI> itrs; std::transform(m.begin(), m.end(), std::back_inserter(itrs), [](MTI itr){ return itr; }); } EDIT 1: Failed to compile with gcc11 and clang13, C++17/20 EDIT 2: The purpose of the question is mostly out of curiosity. I want to see what's a good way to manipulate existing standard algorithm to work on the level that I want. The sample code and problem are entirely made up for demonstration but they are not related to any real problem that requires a solution
Is there such a wrapper? Not in the standard. But it doesn't mean you can't write one, even fairly simply. template<typename It> struct PassIt : It { It& operator*() { return *this; } It const& operator*() const { return *this; } PassIt & operator++() { ++static_cast<It&>(*this); return *this; } PassIt operator++(int) const { return PassIt{static_cast<It&>(*this)++}; } }; template<typename It> PassIt(It) -> PassIt<It>; That is just an example1 of wrapper that is a iterator of the specified template parameter type. It delegates to its base for the bookkeeping, while ensuring the the return types conform to returning the wrapped iterator itself when dereferencing. You can use it in your example to simply copy the iterators std::copy(PassIt{m.begin()}, PassIt{m.end()}, std::back_inserter(itrs)); See it live (1) - It relies on std::iterator_traits deducing the correct things. As written in this example, it may not conform to all the requirements of the prescribed iterator type (in this case, we aimed at a forward iterator). If that happens, more boiler-plate will be required.
70,876,692
70,876,838
why do ranges algorithms take rvalue reference as argument
if I take for example the ranges::fill algorithm: https://en.cppreference.com/w/cpp/algorithm/ranges/fill the signature is: template< class T, ranges::output_range<const T&> R > constexpr ranges::borrowed_iterator_t<R> fill( R&& r, const T& value ); And an example use: #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; namespace ranges = std::ranges; ranges::fill(v, 10); } Why does ranges::fill take a rvalue reference as argument ( R&& r) ? I would have expected it to take a lvalue reference ( R& r) instead.
Since R is a template parameter, R&& is not an rvalue reference, it is a forwarding/universal reference. Forwarding references Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward. Forwarding references are either: function parameter of a function template declared as rvalue reference to cv-unqualified type template parameter of that same function template: template<class T> int f(T&& x) { // x is a forwarding reference return g(std::forward<T>(x)); // and so can be forwarded } int main() { int i; f(i); // argument is lvalue, calls f<int&>(int&), std::forward<int&>(x) is lvalue f(0); // argument is rvalue, calls f<int>(int&&), std::forward<int>(x) is rvalue } template<class T> int g(const T&& x); // x is not a forwarding reference: const T is not cv-unqualified template<class T> struct A { template<class U> A(T&& x, U&& y, int* p); // x is not a forwarding reference: T is not a // type template parameter of the constructor, // but y is a forwarding reference }; auto&& except when deduced from a brace-enclosed initializer list: auto&& vec = foo(); // foo() may be lvalue or rvalue, vec is a forwarding reference auto i = std::begin(vec); // works either way (*i)++; // works either way g(std::forward<decltype(vec)>(vec)); // forwards, preserving value category for (auto&& x: f()) { // x is a forwarding reference; this is the safest way to use range for loops } auto&& z = {1, 2, 3}; // *not* a forwarding reference (special case for initializer lists)
70,876,924
70,876,959
C++: Why are arrays on the stack allocated after "normal" ints for instance, regardless of ordering in the code?
Performing some tests on how c++ compilers (in my case g++ on linux) behave when allocating local variables on the stack. Take a look at this simple code: #include <iostream> int main() { int prev = 10; int myArr[5] = {4, 5, 7, 2, 1}; int next = 10; return 0; } All of these variables are allocated on the stack. One would think that that segment of the stack looks like this: prev myArr next But when inspecting the stack with gdb, it looks like this: 0x7fffffffd640: 0xf7dd1fc8 0x00007fff 0x0000000a 0x0000000a 0x7fffffffd650: 0x00000004 0x00000005 0x00000007 0x00000002 0x7fffffffd660: 0x00000001 0x00007fff 0x2cf9f100 0x09108235 As you can see from the 0x0000000a values, both int variables are allocated before the array. Why is this the case? Some kind of optimization putting the larger int-array after the smaller 4byte ints or am i missing something? Thanks in advance Best regards
One would think that that segment of the stack looks like this: prev myArr next This order is not guaranteed. Some kind of optimization putting the larger int-array after the smaller 4byte ints or am i missing something? Yes, the compiler may arrange the objects as it likes. Order of objects on the stack is not specified and may differ. A variable may not even be allocated on the stack at all when the compiler sees that it isnt necessary. For example this: int main() { int x = 42; return x; } is equivalent to int main() { return 42; } When optimizations are turned on the compiler should notice that and make use of the as-if-rule to produce optimized output.
70,876,966
70,877,510
Why is there an unnecessary or operation when inverting bytes?
I am really confused by this, however trivial it may be. Here's an example (which I tried on paper): uint16_t val = 32; //00000000 00100000 uint16_t swapped = val >> 8; //00100000 00000000 uint16_t swapped2 = val << 8; //00100000 00000000 uint16_t swapped3 = (val >> 8) | (val << 8); //00100000 00000000 I may be missing something... But as far as I know, they all have the same value, I was wondering maybe the operation in "swapped3" was a safeguard/good practice when doing the same for unsigned 32 bit values, but it wouldn't make sense. I've tried to search answers online, but all operations are either this or a play on it. Enlighten me, if possible, binary operations make my head spin.
As many has already stated in the comments, the >> and << operations are bitwise shifts, not bitwise rotations. See https://en.cppreference.com/w/cpp/language/operator_arithmetic. In the most recent standard (C++20) they've added the rotations as well: see rotr and rotl.
70,876,973
70,877,060
multiple initializations in for loop
I am trying to write a function to find the average of numbers at first i wrote code as double CPPLib::average_of_numbers(std::vector<int> &numbers){ double result = -1; if(numbers.size() != 0) { result = 0; for(int i=0;i< int(numbers.size());i++) { result += numbers[i]; std::cout << result << std::endl; } std::cout << result << std::endl; result = result/numbers.size(); std::cout << result << std::endl; } return result; } for the input {1,2,3,4,5} the above code works fine and prints 1 3 6 10 15 15 3 3 .but when i tried to include the result = 0 in "for" loop initialization i am getting result as -1 after for loop.as shown in the code double CPPLib::average_of_numbers(std::vector<int> &numbers){ double result = -1; if(numbers.size() != 0) { for(int i=0,result = 0;i< int(numbers.size());i++) { result += numbers[i]; std::cout << result << std::endl; } std::cout << result << std::endl; result = result/numbers.size(); std::cout << result << std::endl; } return result; } result is displayed as 1 3 6 10 15 -1 -0.2 -0.2 can you please let me know the reason for this. Thank you so much.
In your second example, you've actually declared two separate variables called result. The first is here at the top of your function. double result = -1; The other is here: for(int i=0,result = 0;i< int(numbers.size());i++) You've declared both a temporary int named result (in addition to i) who's lifetime and scope is within the for-loop. It overrides the outer result declared earlier. When the for-loop exits, references to result are back to the original variable declared earlier. Easiest fix is to do what you were doing in your first example. Explicitly set result=0 outside the loop.
70,876,975
70,877,051
Will there be a standard typelist?
Why isn't there a standard typelist in the C++ standard? I would think that something so useful for generic programming (as shown in reflection's ObjectSequence) would be a good candidate for standardization, instead of the myriad implementations around. Are there plans to add one?
N3416: Packaging Parameter Packs proposed a language typelist, but is dead in the water since a decade back. A parameter pack literal is a template-parameter-list (§14p1) surrounded by angle brackets, like <int, std::basic_ostream<char>, 7> To name a parameter list, we just typedef it, like typedef<signed char, short int, int, long int, long long int> signed_integral_types; cout << contains<signed_integral_types, int>::value; // Prints true P1858: Generalized pack declaration and usage is more likely to provide the functionality of a standard type list, as a language feature in particular contexts. The paper is still under EWG discussion. P0949: Adding support for type-based metaprogramming to the standard library proposed introducing template<class... T> struct mp_list {}; But the main scope of the paper is bringing many common Boost meta-programming library types into the standard, where a type list is an essential helper, but where e.g. std::tuple could likewise be used as opposed to a dedicated type. The fundamental data structure on which the proposed algorithms operate is the list, an instantiation of a class template whose parameters are all types. The library does not require or prefer a specific list type. While a canonical mp_list is supplied, its use is not mandatory; all operations and algorithms support other lists such as std::tuple, std::variant or even std::pair (when there is no need to add or remove elements). However, the author mentioned in Cpplang Slack that this paper was rejected.
70,877,544
70,878,433
std::atomic - behaviour of relaxed ordering
Can the following call to print result in outputting stale/unintended values? std::mutex g; std::atomic<int> seq; int g_s = 0; int i = 0, j = 0, k = 0; // ignore fact that these could easily made atomic // Thread 1 void do_work() // seldom called { // avoid over std::lock_guard<std::mutex> lock{g}; i++; j++; k++; seq.fetch_add(1, std::memory_order_relaxed); } // Thread 2 void consume_work() // spinning { const auto s = g_s; // avoid overhead of constantly acquiring lock g_s = seq.load(std::memory_order_relaxed); if (s != g_s) { // no lock guard print(i, j, k); } }
Even ignoring the staleness, this is causes a data race and UB. Thread 2 can read i,j,k while thread 1 is modifying them, you don't synchronize the access to those variables. If thread 2 doesn't respect the g, there's no point in locking it in thread 1.
70,877,650
70,878,895
simple code that compile in c++17 produce error with c++20
I have a strange error returned by gcc/clang When I switch from std=c++17 to std=c++20. struct Matrix2 { double ptr[9]; // defaults Matrix2() = default; // constructor Matrix2(const Matrix2&) = default; // copy constructor Matrix2(Matrix2&&) = default; // move constructor Matrix2& operator=(const Matrix2&) = default; // copy assignment operator Matrix2& operator=(Matrix2&&) = default; // move assignment operator ~Matrix2() = default; // destructor }; constexpr Matrix2 Id2() { return { 1.0 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 , 0.0 , 0.0 , 1.0 }; } int main () { auto a = Id2(); } with stdc++17, the code compile fine, but with stdc++20 this produce the following error : could not convert '{1.0e+0, 0.0, 0.0, 0.0, 1.0e+0, 0.0, 0.0, 0.0, 1.0e+0}' from '<brace-enclosed initializer list>' to 'Matrix2' https://godbolt.org/z/P4afYYn9d Does the standard now prohibit returning raw initializer_list ?? and what is the work around ?? Thx a lot
There was a change in the C++ standard between C++17 and C++20 for aggregate initialization. Have a look at aggregate initialization (cppreference) Look at the explanation section: since c++11, until c++20: no user-provided, inherited, or explicit constructors (explicitly defaulted or deleted constructors are allowed) since C++20: no user-declared or inherited constructors You have declared constructors in your class/struct, so as of C++20 you can't have this kind of initialization. You'd have to declare your own constructor with initialization list [edit: adding some detailed examples] Or remove all the defaulted constructors. You could also have a constructor from std::array: struct Matrix2 { std::array<double,9> ptr; // defaults Matrix2() = default; // constructor Matrix2(const Matrix2&) = default; // copy constructor Matrix2(Matrix2&&) = default; // move constructor Matrix2& operator=(const Matrix2&) = default; // copy assignment operator Matrix2& operator=(Matrix2&&) = default; // move assignment operator constexpr Matrix2(const std::array<double, 9> & arr) : ptr(arr) {} ~Matrix2() = default; // destructor }; constexpr Matrix2 Id2() { // not nice, requires extra brace. // not nice, potentially slower if the compiler misses // the opportunity to elide the copy of the array. return {{ 1.0 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 , 0.0 , 0.0 , 1.0 }}; } int main () { auto a = Id2(); } Or with initialization list: struct Matrix2 { double ptr[9]; // defaults Matrix2() = default; // constructor Matrix2(const Matrix2&) = default; // copy constructor Matrix2(Matrix2&&) = default; // move constructor Matrix2& operator=(const Matrix2&) = default; // copy assignment operator Matrix2& operator=(Matrix2&&) = default; // move assignment operator constexpr Matrix2(const std::initializer_list<double> & init) :ptr{} { // not nice, this is not as good as the validation // the compiler does for aggregate initialization. assert(std::size(init) <= std::size(ptr)); std::copy(std::begin(init), std::end(init), ptr); } ~Matrix2() = default; // destructor }; constexpr Matrix2 Id2() { return { 1.0 , 0.0 , 0.0 , 0.0 , 1.0 , 0.0 , 0.0 , 0.0 , 1.0 }; } int main () { auto a = Id2(); }
70,877,684
70,878,700
Boost::filesystem::directory_iterator causes linker error after upgrade to v1.78.0
I want to use boost::filesystem in my project, and until recently this was possible (v1.65.1). A few days ago, I had to upgrade my boost installation to 1.78.0 and followed the instructions on the site to build the library from source. I executed the following lines: wget https://boostorg.jfrog.io/artifactory/main/release/1.78.0/source/boost_1_78_0.tar.gz tar xzvf boost_1_78_0.tar.gz cd boost_1_78_0/ ./bootstrap.sh --prefix=/usr/ ./b2 sudo ./b2 install The test code from boost utilizes boost's filesystem functions. Compilation is fine, but the linker throws an error (see below). Code #include <iostream> #include <boost/filesystem.hpp> using std::cout; using namespace boost::filesystem; int main(int argc, char* argv[]) { if (argc < 2) { cout << "Usage: tut3 path\n"; return 1; } path p(argv[1]); try { if (exists(p)) { if (is_regular_file(p)) { cout << p << " size is " << file_size(p) << '\n'; } else if (is_directory(p)) { cout << p << " is a directory containing:\n"; for (directory_entry const& x : directory_iterator(p)) cout << " " << x.path() << '\n'; } else cout << p << " exists, but is not a regular file or directory\n"; } else cout << p << " does not exist\n"; } catch (filesystem_error& ex) { cout << ex.what() << '\n'; } return 0; } Compilation and linker commands (generated by eclipse) g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/main.d" -MT"src/main.d" -o "src/main.o" "../src/main.cpp" g++ -o "test" ./src/main.o -lboost_system -lboost_filesystem Error ./src/main.o: In function »boost::filesystem::directory_iterator::directory_iterator(boost::filesystem::path const&, boost::filesystem::directory_options)«: /usr/include/boost/filesystem/directory.hpp:326: Warning: undefined reference to »boost::filesystem::detail::directory_iterator_construct(boost::filesystem::directory_iterator&, boost::filesystem::path const&, unsigned int, boost::system::error_code*)« makefile:45: recipe for target 'test' failed collect2: error: ld returned 1 exit status make: *** [test] Error 1 "make all" terminated with exit code 2. Build might be incomplete. If I remove the line containing the boost::filesystem::directory_iterator the linking works. I am not sure how to fix this. I initially thought that the old version of boost might interfere, as it still resides within /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1, but when checking the version included in the file, it shows the newer version. What is happening here? SOLUTION In the end, I removed both the original installation as well as the new version and reinstalled the packet under /usr/local. A quick walkthrough to help somebody encountering the same problem: // remove the dirs under <prefix>/lib/libboost* and <prefix>/include/boost* first sudo apt purge -y libboost-all-dev libboost* sudo apt autoremove // then either install the package via the manager or copy the sources to /usr/local/ or another suitable place sudo apt install libboost-all-dev // option with aptitude
The includes are compile time. The shared libraries are linked at link time. You didn't explicitly tell the to find the headers, nor did you tell the compiler where to locate the libraries. This means that the standard locations are used. Depending on your package manager there may be symlinks like: /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1 /usr/lib/x86_64-linux-gnu/libboost_filesystem.so -> libboost_filesystem.so.1.65.1 It is generally a bad idea to overwrite parts of installed packages with your files. Not in the last place because e.g. such symlinks might not be updated, or if they are they might break a lot of dependencies that you have installed. In general, prefer to use a safe prefix (/usr/local e.g.) or build locally and indicate the include/library directories in your build tool, like Eclipse, or on the command line like: -I ~/custom/boost_1_77_0/ -L ~/custom/boost_1_77_0/stage/libs An advantage of choosing /usr/local is that many distros support it and might have it added to the runtime loader's path (see ldconfig).
70,878,173
70,883,057
What is "MAX" referring to in the intel intrinsics documentation?
Within the intel intrinsics guide some operations are defined using a term "MAX". An example is __m256 _mm256_mask_permutexvar_ps (__m256 src, __mmask8 k, __m256i idx, __m256 a), which is defined as FOR j := 0 to 7 i := j*32 id := idx[i+2:i]*32 IF k[j] dst[i+31:i] := a[id+31:id] ELSE dst[i+31:i] := 0 FI ENDFOR dst[MAX:256] := 0 . Please take note of the last line within this definition: dst[MAX:256] := 0. What is MAX referring to and is this line even adding any valuable information? If I had to make assumptions, then MAX probably means the amount of bits within the vector, which is 256 in case of _mm256. This however does not seem to change anything for the definition of the operation and might as well have been omitted. But why is it there then?
This pseudo-code only makes sense for assembly documentation, where it was copied from, not for intrinsics. (HTML scrape of Intel's vol.2 PDF documenting the corresponding vpermps asm instruction.) ... ENDFOR DEST[MAXVL-1:VL] ← 0 (The same asm doc entry covers VL = 128, 256, and 512-bit versions, the vector width of the instruction.) In asm, a YMM register is the low half of a ZMM register, and writing a YMM zeroes the upper bits out to the CPU's max supported vector width (just like writing EAX zero-extends into RAX). The intrinsic you picked is for the masked version, so it requires AVX-512 (EVEX encoding), thus VLMAX is at least 5121. If the mask is a constant all-ones, it could get optimized to the AVX2 VEX encoding, but both still zero high bits of the full register out to VLMAX. This is meaningless for intrinsics The intrinsics API just has __m256 and __m512 types; an __m256 is not implicitly the low half of an __m512. You can use _mm512_castps256_ps512 to get a __m512 with your __m256 as the low half, but the API documentation says "the upper 256 bits of the result are undefined". So if you use it on a function arg, it doesn't force it to vmovaps ymm7, ymm0 or something to zero-extend into a ZMM register in case the caller left high garbage. If you use _mm512_castps256_ps512 on a __m256 that came from an intrinsic in this function, it pretty much always will happen to compile with a zeroed high half whether it stayed in a reg or got stored/reloaded, but that's not guaranteed by the API. (If the compiler chose to combine a previous calculation with something else, using a 512-bit operation, you could plausibly end up with a non-zero high half.) If you want high zeros, there's no equivalent to _mm256_set_m128 (__m128 hi, __m128 lo), so you need some other explicit way. Footnote 1: Or with some hypothetical future extension, VLMAX aka MAXVL could be even wider. It's determined by the current value of XCR0. This documentation is telling you these instructions will still zero out to whatever that is. (I haven't looked into whether changing VLMAX is possible on a machine supporting AVX-512, or if it's read-only. IDK how the CPU would handle it if you can change it, like maybe not running 512-bit instructions at all. Mainstream OSes certainly don't do this even if it's possible with privileged operations.) SSE didn't have any defined mechanism for extension to wider vectors, and some existing code (notably Windows kernel drivers) manually saved/restored a few XMM registers for their own use. To support that, AVX decided that legacy SSE would leave the high part of YMM/ZMM registers unmodified. But to run existing machine code using non-VEX legacy SSE encodings efficiently, it needed expensive state transitions (Haswell and Ice Lake) and/or false dependencies (Skylake): Why is this SSE code 6 times slower without VZEROUPPER on Skylake? Intel wasn't going to make this mistake again, so they defined AVX as zeroing out to whatever vector width the CPU supports, and document it clearly in every AVX and AVX-512 instruction encoding. Thus VEX and EVEX can be mixed freely, even being useful to save machine-code size: What is the most efficient way to clear a single or a few ZMM registers on Knights Landing? What is the penalty of mixing EVEX and VEX encoded scheme? (none), with an answer discussing more details of why SSE/AVX penalties are a thing. https://software.intel.com/en-us/forums/intel-isa-extensions/topic/301853 Agner Fog's 2008 post on Intel's forums about AVX, when it was first announced, pointing out the problem created by the lack of foresight with SSE. Does vzeroall zero registers ymm16 to ymm31? - interestingly no; since they're not accessible via legacy SSE instructions, they can't be part of a dirty-uppers problem.
70,878,407
70,878,458
How can I template my print function on std::ostream?
So far, I have a function print: template < char Sep = ' ', class... Args > void print(Args&&... args) { ([](Args&& arg) { std::cout << arg << Sep; }(std::forward<Args>(args)), ...); std::cout << '\n'; } int main() { print("a", 'b', 3, 4.0, 5.0f, true); } I want to template it on std::ostream so that I can print to the buffer I want but I am struglling. Here is what I tried (I have put errors as comment in the code): //Error: a nontype parameter may not have class type template < std::ostream os, char Sep = ' ', class... Args > void print(Args&&... args){ /*omitted code */ os << arg << Sep; } int main() { print("a", 'b', 3, 4.0, 5.0f, true); } I though maybe I could use a class to work-around the problem: template < class Buffer > class Printer { public: void Set(Buffer* buff) { this->buff = buff; } //Error: the usage of 'Printer<std::ostream>::buff' requires the compiler //to capture this but the current default capture mode does not allow it template < char Sep = ' ', class... Args > void operator()(Args&&... args) { ([](Args&& arg) { (*buff) << arg << Sep; }(std::forward<Args>(args)), ...); std::cout << '\n'; } private: Buffer* buff; }; int main() { Printer<std::ostream> print; print.Set(&std::cout); print("a", 'b', 3, 4.0, 5.0f, true); }
Use an ordinary template argument and pass the stream as parameter to the function: #include <iostream> template <typename stream, char Sep = ' ', class... Args > void print(stream& out,Args&&... args) { ([&out](Args&& arg) { out << arg << Sep; }(std::forward<Args>(args)), ...); std::cout << '\n'; } int main() { print(std::cout,"a", 'b', 3, 4.0, 5.0f, true); } If only std::ostreams are ok you need not make it a template, but simply use an std::ostream& argument. The standard library makes use of inheritance only sparingly, but for streams there are base classes that can be used when you want to use standard streams. PS: As pointed out by MarekR you do not need the lambda. The function is simpler like this: #include <iostream> template <typename stream, char Sep = ' ', class... Args > stream& print(stream& out,Args&&... args) { return ((out << args << Sep) , ...) << '\n'; } int main() { print(std::cout,"a", 'b', 3, 4.0, 5.0f, true); }
70,878,852
70,879,179
Is using the overloading << operator as push_back a good idea?
I've been practicing with operator overloading in order to comprehend it better and I came across using the << operator with vectors like this: void operator<<(std::vector<int> &vector, int value){ vetor.push_back(value); } Now I know that this isn't really a good idea and that I should avoid doing this but I'd like to listen to someone more experienced in the subject in order to help me understand the << operator and the ostream class in a better way.
Now I know that this isn't really a good idea and that I should avoid doing this Your knowledge is correct. There are two issues with this: It's a bad idea to define operators that don't involve your own types. Technically, the standard doesn't guarantee that it won't add a global operator<<(std::vector<int> &, int) in future, which would break the forward compatibility of a program that defines such overload. Furthermore, library programmers with the same bad idea may potentially make the same decision, breaking the compatibility with your program. This makes such idea extra bad for library code. Unlike functions, operators don't have names that describe them so as a rule of thumb in order to keep programs understandable, operator overloads should ideally implement operations that are analogous to their built-in counterparts. There is precedent for violation of this rule of thumb in the standard library, such as character output stream insertion operator, and the range adaptor pipe operator. Such approach increases the number of different things one operator means, and it should not be taken lightly.
70,879,695
70,880,047
Fastest way to strip trailing zeroes from an unsigned int
Suppose we are trying to remove the trailing zeroes from some unsigned variable. uint64_t a = ... uint64_t last_bit = a & -a; // Two's complement trick: last_bit holds the trailing bit of a a /= last_bit; // Removing all trailing zeroes from a. I noticed that it's faster to manually count the bits and shift. (MSVC compiler with optimizations on) uint64_t a = ... uint64_t last_bit = a & -a; size_t last_bit_index = _BitScanForward64( last_bit ); a >>= last_bit_index Are there any further quick tricks that would make this even faster, assuming that the compiler intrinsic _BitScanForward64 is faster than any of the alternatives?
On x86, _tzcnt_u64 is a faster alterative of _BitScanForward64, if it is available (it is available with BMI instruction set). Also, you can directly use that on the input, you don't need to isolate lowest bit set, as pointed out by @AlanBirtles in a comment. Other than that, noting can be done for a single variable. For an array of them, there may be a SIMD solution.
70,880,512
70,899,769
Does reassignment of pointers acquired by reinterpret_cast from raw memory cause UB?
In our lecture we were discussing the inner possible implementation of std::list. The lecturer showed the approach where a dummy node is created to indicate the end of the list: struct Node { Node* prev; ... } Node* dummy = reinterpret_cast<Node*>(new int8_t[sizeof(Node)]); dummy->prev = ... /* last node */; They claimed that the last line might cause undefined behaviour. I cannot see why this could be unsafe. At the end of the day, we are just overwriting several bits without dereferencing the preseting. If this really was problem, wouldn't it have occured at the point of reinterpret_casting? So, does udefined behaviour actually take place here, and, if so, why?
First, for your second line Node* dummy = reinterpret_cast<Node*>(new int8_t[sizeof(Node)]); by itself. new returns a pointer to the first int8_t object in the array of int8_t objects it created. reinterpret_cast's behavior depends on the alignment of the address represented by the pointer. If it is suitably aligned for an object of type Node, then it will leave the pointer value unchanged (since there is definitively no Node object at the location which is pointer-interconvertible with the int8_t object). If it is not suitably aligned, the returned pointer value will be unspecified. Unspecified means that we won't know what the value will be, but it wont cause undefined behavior. Therefore, in any case, the second line and the cast by itself do not have undefined behavior. The line dummy->prev = ... /* last node */; requires that the object dummy points to is actually a Node object. Otherwise it has undefined behavior. As mentioned above, reinterpret_cast gives us either an unspecified value or a pointer to the int8_t object. This already is an issue, that I think at least requires a std::launder call. Even if the pointer returned from new is correctly aligned, then we still need to check whether a Node object is present. We certainly did not create any such object in any of the shown operations explicitly, but there is implicit object creation which may help out (at least since C++20, but I suppose this was supposed to be a defect report against older standard versions). Specifically, objects may be created implicitly inside an array of types unsigned char, std::byte and, with some limitations, char (CWG 2489) when the lifetime of the array is started. int8_t is usually signed char and I think is not allowed to be either of the three previously mentioned types (see e.g. this question). This removes the only possible way out of UB. So your third code line does have undefined behavior. Even if you remedy this by changing the type form int8_t to std::byte, there are other constraints on the details of Node to make the implicit object creation possible. It may also be necessary to add a std::launder call. All of this doesn't consider the alignment yet, because although new[] obtains memory with some alignment requirements, I think the standard mandates new[] itself to return a pointer with stronger alignment than required for the element type only for char, unsigned char and std::byte array new. Many of these issues can probably be avoided by using e.g. operator new directly, possibly with provided alignment request, and making sure that Node is an aggregate. In any case writing code like this is very risky because it is difficult to be sure that it isn't UB. It should be avoided when ever possible.
70,880,526
70,880,707
Passing uniform_int_distribution as parameter (with state)
I'm trying to write some code that will use random generators but allow you to seed it (for reproducability). The code looks something like the following (trying to create a snippet that can be run) #include <cstdio> #include <functional> #include <random> class CarterWegmanHash { private: unsigned int a_; unsigned int b_; public: // What should the signature of this be? CarterWegmanHash(int k, std::function<unsigned int()> unif_rand) { // Other stuff a_ = unif_rand(); b_ = unif_rand(); } unsigned int get_a() { return a_; } unsigned int get_b() { return b_; } }; int main() { // Construct our uniform generator int n = 8; std::random_device rd; auto unif_rand = std::bind( // uniform rand from [0, n - 1] std::uniform_int_distribution<unsigned int>(0, pow(2, n)), std::mt19937(rd())); for (int i = 0; i < 5; ++i) { // How do I call this? CarterWegmanHash h_k(n, unif_rand); printf("seeds for h_%d are %u, %u\n", i, h_k.get_a(), h_k.get_b()); } } I'd like each of the CarterWegmanHash objects to be able to have different seeds from unif_rand, but (not suprisingly), they're all the same. Passing by pointer gives me error: no matching function for call to ‘CarterWegmanHash::CarterWegmanHash, and passing by ref gives me cannot bind non-const lvalue reference of type ‘std::function<unsigned int()>&’ to an rvalue of type ‘std::function<unsigned int()>’ Is there a way to pass a random number generator like uniform_int_distribution so the state is maintained?
You can just create your distribution and mt19937 in main and capture them in a lambda: std::uniform_int_distribution<unsigned int> distribution(0, pow(2, n)); std::mt19937 mt(rd()); auto unif_rand = [&](){ return distribution(mt); }; Or with bind: auto unif_rand = std::bind(std::ref(distribution), std::ref(mt));
70,880,865
71,063,782
Crash in GStreamer qmlglsink pipeline dynamically rebind to different GstGLVideoItem
I've used one of existing qmlglsink examples to stream video feed from 4 IP Cameras. 4 Pipelines are created before engine load. for(int i = 0; i < maxCameras; ++i) { GstElement* pipeline = gst_pipeline_new (NULL); GstElement* src = gst_element_factory_make ("udpsrc", NULL); GstElement* parse = gst_element_factory_make ("jpegparse", NULL); GstElement* decoder = gst_element_factory_make ("jpegdec", NULL); GstElement* glcolorconvert = gst_element_factory_make ("glcolorconvert", NULL); GstElement* glupload = gst_element_factory_make ("glupload", NULL); GstElement *sink = gst_element_factory_make ("qmlglsink", NULL); g_assert (src && parse && decoder && glupload && glcolorconvert && sink); g_object_set (G_OBJECT (src), "port", startingPort + i, NULL); g_object_set (G_OBJECT (sink), "sync", FALSE, NULL); gst_bin_add_many (GST_BIN (pipeline), src, parse, decoder, glupload, glcolorconvert, sink, NULL); if (!gst_element_link_many ( src, parse, decoder, glupload, glcolorconvert, sink, NULL)) { qDebug() << "Linking GStreamer pipeline elements failed"; } sinks.insert(std::make_pair(QString::number(startingPort+i), sink)); pipelines.insert(std::make_pair(QString::number(startingPort+i), pipeline)); } In Qml sink is connected and processed with import QtQuick 2.15 import QtQuick.Layouts 1.15 import CustomProject 1.0 import org.freedesktop.gstreamer.GLVideoItem 1.0 Item { id: root signal clicked() required property int udpPort property var camConnect: undefined onUdpPortChanged: { setupConnection(); } onVisibleChanged: { if (visible) { setupConnection(); } else { camConnect = undefined } } GstGLVideoItem { id: videoItem anchors.fill: parent function connect() { CameraSinksFactory.connectSink(this, udpPort) } } MouseArea { anchors.fill: parent onClicked: { CameraSinksFactory.stopPipeline(udpPort) root.clicked() } } function setupConnection() { if (udpPort <= 0 || !root.visible) return; videoItem.connect() root.camConnect = CameraSinksFactory.getCamConnection(udpPort); root.camConnect.resolutionX =// - 15 root.width root.camConnect.resolutionY = root.height root.camConnect.bitrate = 15000000 root.camConnect.streaming = root.visible CameraSinksFactory.startPipeline(udpPort) } } Problem: Main screen display 4 (2x2 grid) items using Model (which provides udpPort as unique ID). When User clicks on one Item - feed from this camera should fill whole screen. In Examples they create GridLayout with 4/6 explicit items and just manipulate their visiblity (in effect clicked item is only one remaining and take whole screen). In my case - I'm using separate Item for full screen view. So I'm disabling streaming (CamConnection class communicating with Cameras and sending commands) and hide GridView. New GstGLVideoItem binds to qmlglsink in pipeline. Everything is OK, until I repeat click sequence (back to GridView and to fullview). Every time it ends with: Bail out! ERROR:../ext/qt/gstqsgtexture.cc:134:virtual void GstQSGTexture::bind(): code should not be reached ** (KMS:20495): CRITICAL **: 15:47:36.937: gst_video_frame_map_id: assertion 'info->width <= meta->width' failed ** ERROR:../ext/qt/gstqsgtexture.cc:134:virtual void GstQSGTexture::bind(): code should not be reached From plugins code analysis it's happening when INFO (image size read from CAPS) is bigger then size in metadata in provided buffer. Which is understandable - buffer is too small. I used GST_DEBUG=4/5/6/7 and logs confirm that autodetected caps are matching request in commands sent to camera. I can use example, but project assumes another panel with those cameras - so above problem will hit me in near future. How to make this whole setup working? How to rebind pipeline qmlglsink to new QML VideoItem safely?
Two possible solutions: set gst_element_set_state (pipeline, GST_STATE_NULL);, change sink widget to new item and start pipeline gst_element_set_state (pipeline, GST_STATE_PLAYING); use Qt 5 MediaPlayer with gst-pipeline as source. When visible set source and execute start(). When not visible reset source to empty (important) and execute stop(). In general - possible benefits from NOT creating pipeline each time are not worth hassle when we dynamically assign new QML Item to pipeline sink.
70,881,511
70,881,609
Is there a way to make a concept that can represent a template parameter pack?
With C++20, we can write a concept and use it like so: template<typename T> concept ClassType = std::is_class_v<T>; template<ClassType T> void foo(); Is there a way to achieve this same syntax when using template parameter packs? We could obviously do it with requires: template<typename T, typename... Ts> concept SameTypes = std::conjunction_v<std::is_same<T, Ts>...>; template<typename... Ts> requires SameTypes<Ts...> void foo(); But my question is if there is way to do it using the syntax where the concept takes the place of typename, inside the template brackets like in the first example. Is there?
Yes, you can do this, which is functional equivalence to your example: #include <concepts> template<class T, std::same_as<T>... Ts> void foo();
70,881,575
70,881,706
Boost with CMakeLists on Visual Studio
I'm trying to run some code with boost, but i can't include any boost file, like "boost/timer/timer.hpp". My CMakeLists contains cmake_minimum_required(VERSION 3.10) project(Converter) find_package(Boost) include_directories(${BOOST_INCLUDE_DIRS}) LINK_DIRECTORIES(${Boost_LIBRARIES}) add_executable(Converter converter.cpp) TARGET_LINK_LIBRARIES(Converter ${Boost_LIBRARIES}) message("boost lib: ${Boost_LIBRARY_DIRS}, inc: ${Boost_INCLUDE_DIR}") CMake answer My cpp file contains #include <iostream> #include <boost/timer/timer.hpp> using namespace std; int main() { cout << "Hello world!" << endl; return 0; } And when i am trying to build it, there is a error: "Cannot open include file 'boost/timer/timer.hpp'"
You are using a wrong non existing variable here. To set the include Boost directories to your project you need to use Boost_INCLUDE_DIRS, the case of the variable matters. And your link directories should be set to Boost_LIBRARY_DIRS. cmake_minimum_required(VERSION 3.10) project(Converter) find_package(Boost COMPONENTS timer) include_directories(${Boost_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) add_executable(Converter converter.cpp) target_link_libraries(Converter PUBLIC ${Boost_LIBRARIES}) message("boost lib: ${Boost_LIBRARY_DIRS}, inc: ${Boost_INCLUDE_DIR}") Your small project can be further simplified by using the imported targets Boost::headers as follows: cmake_minimum_required(VERSION 3.10) project(Converter) find_package(Boost COMPONENTS timer REQUIRED) add_executable(Converter converter.cpp) target_link_libraries(Converter PUBLIC Boost::headers Boost::timer) message("boost lib: ${Boost_LIBRARY_DIRS}, inc: ${Boost_INCLUDE_DIRS}")
70,881,883
70,882,035
(C++) Getter and setter in a class not working as intended
I am trying to write a simple code where the getter and setter is used. Here is the test_class.hpp file #ifndef TEST_CLASS_HPP #define TEST_CLASS_HPP class test_class { private: int num; public: test_class(int num); ~test_class(); int& get_num(); void set_num(int& num); }; #endif Here is the test_class.cpp file #include<iostream> #include"test_class.hpp" test_class::test_class(int num):num(num){}; test_class::~test_class(){}; int& test_class::get_num(){return num;} void test_class::set_num(int& num){num = num;} And here is the main function #include<iostream> #include"test_class.hpp" #include<random> int main(){ test_class obj_test(69); int count = 10; while (count > 0) { std::cout << obj_test.get_num() << " at count " << count << std::endl; auto new_change = obj_test.get_num() - count; obj_test.set_num(new_change); count--; } } Aim: As count goes from 10 to 1 in the while loop, the num variable value should also decrease. Observation: The value of num variable remains constant (initial value of 69) throughout the iteration. I played with lvalues and rvalues but I can't make it work as intended.
void test_class::set_num(int& num){num = num;} What exactly is happening here? You assign num to itself. This code does nothing. What you really want is void test_class::set_num(int& num){ this->num = num; } Btw you would avoid this kind of errors if you declared void test_class::set_num(const int& num) (or even without &) which you should do, since you don't modify num inside set_num function.
70,882,952
70,898,183
Can static member function without any argument access private attributes of a class?
I have following (simplified) ServerHandler.h file #include <WebServer.h> class ServerHandler { public: ServerHandler(); void createServer(); static void handlePage(); private: WebServer server; }; And ServerHandler.cpp file #include "ServerHandler.h" ServerHandler::ServerHandler() : server(80) {} void ServerHandler::createServer() { // this code does not work server.on("/page", handlePage); // lambda functions are proper to use server.on("/hey", [this]() { server.send(200, "text/plain", "Hello"); }); server.begin(); } void ServerHandler::handlePage () { server.send(200, "text/plain", "This is a page"); } In WebServer.h server.on() is defined as: typedef std::function<void(void)> THandlerFunction; void on(const Uri &uri, THandlerFunction handler); All I want is to write a free function/static method/member method etc for long server operations called as handlePage(). Problem is I cannot use a static function with argument like pageHandler(Server s&) because I cannot use this function in server.on("/page", pageHandler(s)); Additionally, I do not want to use lambda function as in the code becase my goal is to seperate long operations. Briefly, how to deal with server.on("/page", ?); ?
As I learn it is possible to use member functions thank to @hcheung, I researched how to do it and found. Requirement: typedef std::function<void(void)> THandlerFunction; void on(const Uri &uri, THandlerFunction handler); To use non-static member function I need to use binding. mServer.on("/control_servo", std::bind(&ServerHandler::handlePage, this));
70,882,960
70,883,147
Using Enum to represent days
I want to represent a Weekday (Monday to Friday) as an enum but am not sure how to represent the data in c++. I have done some reading and have my enum class: enum Day{MONDAY=0, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}; But I also need some sort of to_string method in order to print the days out when required. Currently I represent a Weekday in its own separate class as shown below: Weekday::Weekday(char day){ switch(day){ case 'M' : weekday = "Monday"; day_value = 0; break; case 'T': weekday = "Tuesday"; day_value = 1; break; case 'W': weekday = "Wednesday"; day_value = 2; break; case 'R': weekday = "Thursday"; day_value = 3; break; case 'F': weekday = "Friday"; day_value = 4; } } But I got a few looks when presenting my code to others so I was wondering if this is really the best way to do it. Someone suggested to just use a switch to compare days and avoid making a new class at all but I thought this is more organized and on the plus side if I ever need to add more functionality to a weekday its all already set up. I do have quite a few classes already for representing time in my program as well so maybe I am going a little crazy with the classes so I suppose I just need some guidance. Their reasons for not using classes were something about memory and efficiency so thus I have three questions: 1.) Is a whole new class for a weekday the best way to represent this data? 2.)If a class of some sort is the best way what about an enum? 3.) Using an enum, how can I represent the enum data as a readable string I can print to an output later? Sorry its a lot to unpack but I can't help but wonder if my way of making a class is truly the best way if there is a best way at all. Regardless, thanks for the help in advance! EDIT: the end goal here is to compare weekdays for example Monday comes before Tuesday so I assigned a value to the weekday and I would prefer not to use any imports
I usually use a table of structs: struct Enum_Entry { enum Weekday day; const char day_name[]; // or const char * day_name; }; and then I have a conversion table: Enum_Entry conversion_table[] = { {MONDAY, "Monday"}, //... {FRIDAY, "Friday"}, }; One nice thing about the above table is that the entries can be in any order. A less maintainable method is to use an array of names: static const char weekday_names[] = { "Monday", /*...*/, "Friday"}; The conversion method: std::cout << weekday_names[WEDNESDAY] << "\n"; Neither one is the best method, they each have their strengths and weaknesses.
70,883,061
70,883,167
How to determine the return type of a function in template
I am trying to write a class similar to std::function, just to learn how it works but I am having problem determining the return type of the function. I found this from one of the answers here on stack overflow. I am trying to do something similar but It does not work and I do not know why. template< class Fx > class function { public: function() = default; function(Fx* fx) { this->fx = fx; } template < class... A > ReturnType operator()(A... args) { //return ((*fx)(args), ...); ?? } private: template<class F> struct return_type; template< class R, class... A> struct return_type<R(*)(A...)> { using type = R; }; using ReturnType = return_type<Fx>::type; Fx* fx; }; int sum(int a, int b) { return a + b; }; int main() { function<int(int, int)> mysum{ sum }; mysum(10, 10); } It gives me an error on line using ReturnType = return_type<Fx>::type; saying incomplete type is not allowed. Why does it not pick the specialized one?
Since Fx is supposed to be a function type, not a function pointer type, so the specialization should be declared as: template< class R, class... A> struct return_type<R(A...)> { using type = R; }; Other issues: Change using ReturnType = return_type<Fx>::type; to using ReturnType = typename return_type<Fx>::type;. Move the declaration of ReturnType (and definition of return_type) before using it as the return type of operator(). Change return ((*fx)(args), ...); to return (*fx)(args...); in the operator(); i.e. all the arguments are supposed to be passed to fx instead of calling fx multiple times with each argument. LIVE BTW: Return type deduction (since C++14) is worthy of consideration too. E.g. template < class... A > auto operator()(A... args) { return (*fx)(args...); } LIVE
70,883,592
70,883,714
Using an array from main in a recursive function
As part of a problem, I need to create a recursive function on a string. Part of it is based on the nth element of Fibonacci. The thing is that I need to get n ( the number of elements ) as an input, and only then I can create the array. But I also need to create a recursive function that has to use the array. I thought of adding the array to the function as a parameter but I'm not sure if that would decrease the function's efficiency. So in case it would: Is there any way I can use that specific array in a function in c++? I calculate the array like this: #include <bits/stdc++.h> using namespace std; char IOI(int n,int k) { if (n<3) { return n; } if (k<=fibo[n-2]) { return IOI(n-2,k); } else { return IOI(n-1,k-fibo[n-2]); } } int main() { int n,k; cin >> n >> k; int fibo[n+1]; fibo[0] = 0; fibo[1] = 1; for (int i = 2; i<n; i++) { fibo[i] = fibo[i-1]+fibo[i-2]; } cout << IOI(n,k)
Is there any way I can use that specific array in a function in c++? Yes. Pass the array as an argument, using some form of indirection. Typically, this would be done using a parameter of type span. cin >> n >> k; int fibo[n+1]; This isn't allowed. The size of an array variable must be compile time constant in C++. In order to use an array with dynamic size, the array must be allocated dynamically. The most convenient solution is to use std::vector.
70,884,182
70,884,290
Tic-tac-toe using classes, compute victory condition
I was trying to make a program for Tic-tac-toe between 2 players, using a class. But my is_victory function is always returning false. Why so? //header file : tic_tac_toe.h class Game { public : Game(); void insert(int , char); void print() const; bool is_empty(int) const; bool is_victory() const; private : char *pntr; }; codefile: // codefile for the class tic_tac_toe.cpp #include"tic_tac_toe.h" #include<iostream> using namespace std; Game::Game() { pntr = new char[9] ; for(int i=0; i<9; i++) { pntr[i] = 48+i; } } void Game::insert(int location, char val) { pntr[location] = val; } void Game::print() const { for(int i=1; i<=9; i++) { cout<<pntr[i-1]<<"|"; if(i%3 == 0) cout<<endl; } } bool Game::is_empty(int location) const { if(pntr[location] == location+48 ) return true; else return false; } bool Game::is_victory() const { if(pntr[0] == pntr[1] == pntr[2]) return true; if(pntr[3] == pntr[4] == pntr[5]) return true; if(pntr[6] == pntr[7] == pntr[8]) return true; if(pntr[0] == pntr[3] == pntr[6]) return true; if(pntr[1] == pntr[4] == pntr[7]) return true; if(pntr[2] == pntr[5] == pntr[8]) return true; if(pntr[0] == pntr[4] == pntr[8]) return true; if(pntr[2] == pntr[4] == pntr[6]) return true; return false; } Main program : //tic_tac_toe_try1.cpp #include"tic_tac_toe.h" #include<iostream> using namespace std; int main() { char player1; char player2; Game gameobj; cout<<"choose between X or O"<<endl; cin>> player1; if(player1 == 'X') player2='O'; else player2 = 'X'; for(int i=0; i<4; i++) { int location; gameobj.print(); cout<<"enter location to enter "<< player1<<"between 0-8 as shown above : "; cin>> location; while(! (location>=0 && location<9) ) { cout<<"invalid location , please renter location between 0-8: "; cin>>location; } while(!gameobj.is_empty(location) ) { cout<<"invalid location , already filled please renter : "; cin>>location; } gameobj.insert(location, player1); gameobj.print(); if(gameobj.is_victory()) { cout<<"congrats player1 victorious"; return 0; } cout<<"enter location to enter "<< player2<<"between 0-8 as shown above : "; cin>> location; while(! (location>=0 && location<9) ) { cout<<"invalid location , please renter location between 0-8: "; cin>>location; } while(!gameobj.is_empty(location) ) { cout<<"invalid location , already filled please renter : "; cin>>location; } gameobj.insert(location, player2); if(gameobj.is_victory()) { cout<<"congrats player2 victorious"; return 0; } } return 0; } Sample trial in terminal of vsc : PS D:\c++> g++ tic_tac_toe.cpp tic_tac_toe_try1.cpp PS D:\c++> ./a.exe choose between X or O X 0|1|2| 3|4|5| 6|7|8| enter location to enter Xbetween 0-8 as shown above : 0 X|1|2| 3|4|5| 6|7|8| enter location to enter Obetween 0-8 as shown above : 3 X|1|2| O|4|5| 6|7|8| enter location to enter Xbetween 0-8 as shown above : 2 X|1|X| O|4|5| 6|7|8| enter location to enter Obetween 0-8 as shown above : 4 X|1|X| O|O|5| 6|7|8| enter location to enter Xbetween 0-8 as shown above : 1 X|X|X| O|O|5| 6|7|8| enter location to enter Obetween 0-8 as shown above : As above even after getting 3 X's in 0,1,2 pntr's is_victory still doesn't give true. I also tried checking the values of pntr[0], pntr[1], pntr[2] by manually printing them and the value of expression (pntr[0] == pntr[1] == pntr[2]) while the earlier all print X, but the comparison results in 0.
if(pntr[0] == pntr[1] == pntr[2]) return true; The condition A == B == C will be evaluated as (A == B) == C. The expression (A == B) will result in false (0) or true (1), and from the initialization of pntr we can see that C will never be equal to 0 nor 1. Therefore, the expression as a whole always evaluates to false. What you probably meant to do is, e.g., this: if(pntr[0] == pntr[1] && pntr[1] == pntr[2]) return true;
70,884,233
70,884,660
OpenGL get currently bound vertex buffer and index buffer
I'm currently working with OpenGL in C++, and I'm trying to debug by identifying what the currently bound vertex buffer and index buffer are. I have three functions. GLint getBoundVAO() { GLint id = 0; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &id); return id; }; GLint getBoundVBO() { GLint id = 0; // ??? return id; }; GLint getBoundIBO() { GLint id = 0; // ??? return id; }; How would I go about getting the vertex buffer and index buffer in a similar way to how I am getting the VAO? I've looked at the OpenGL page https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGet.xhtml and am not seeing a value which will allow me to get the index or vertex buffers.
See the "Parameters" section here. The symbolic constants used for binding the buffers match the ones used for glGet* (but with a _BINDING suffix). For the vertex buffer object, use: glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &id); For the index buffer, use: glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &id);
70,884,432
70,885,515
How to get UniquePtr<EnumMember> on the Rust side? (CXX crate)
Using the cxx crate: https://crates.io/crates/cxx I have the following struct on Rust: #[cxx::bridge] pub(crate) mod ffi { enum SizeType { BYTE, WORD, DWORD, QWORD, } unsafe extern "C++" { //... } } which is also mapped on C++. How do I get UniquePtr<SizeType> on Rust? Do I have to write a C++ function to get it? If I do, there's no point in having the struct on the Rust side. I tried let byte_ptr = UniquePtr::new(SizeType::BYTE); but it does not work.
Try adding: impl UniquePtr<SizeType> {} See https://github.com/dtolnay/cxx/blob/a95eca61029b458998c1c5463481307af5643ba5/macro/src/expand.rs#L1408 and https://github.com/dtolnay/cxx/blob/a95eca61029b458998c1c5463481307af5643ba5/tests/ui/impl_trait_for_type.stderr.
70,884,494
70,907,955
QML wrapped TableView element behaves different from non-wrapped one
I'm having some troubles getting the QML type TableView to behave correctly when wrapping it inside another item. The problem is that creating a reuseable type basically forces one to use an Item wrapper to have the *HeaderView types in the same .qml file. Here is the rather simple code, a test-model for some data can be taken from the official TableView documentation. import QtQuick import QtQuick.Controls import QtQuick.Layouts import TableModel Window { width: 600 height: 480 visible: true // This item wrapper changes TableView behavior Item { width: 600 height: 250 // -------------------------------------------- TableView { id: tableView anchors.fill: parent topMargin: horizontalHeader.implicitHeight leftMargin: verticalHeader.implicitWidth columnSpacing: 1 rowSpacing: 1 clip: true model: TableModel {} delegate: Rectangle { implicitWidth: 150 implicitHeight: 25 Text { text: display } } } HorizontalHeaderView { id: horizontalHeader syncView: tableView } VerticalHeaderView { id: verticalHeader syncView: tableView } // -------------------------------------------- } // -------------------------------------------- } Without the Item wrapper (see comments in code) my TableView looks as expected: But once wrapped inside an Item the horizontal and vertical headers get placed over the actual table. For some odd reason this displacement is only relevant for the very first rendering of the table. Once I drag the data from the table around a little (I guess activating the "Flickable" inherited type?) the data suddenly snaps into position and is displayed correctly outside of the headers.
Apparently it wasn't a good idea to use anchors.fill: parent when trying to attach the *HeaderViews. Once I got rid of that line and simply anchored all views to each other (horizontal to top, vertical to left) it works. Item { implicitWidth: 600 implicitHeight: 250 TableView { id: tableView implicitWidth: parent.implicitWidth implicitHeight: parent.implicitHeight anchors.top: horizontalHeader.bottom anchors.left: verticalHeader.right columnSpacing: 1 rowSpacing: 1 clip: true model: TableModel {} delegate: Rectangle { implicitWidth: 150 implicitHeight: 25 Text { text: display } } } HorizontalHeaderView { id: horizontalHeader anchors.left: verticalHeader.right clip: true syncView: tableView } VerticalHeaderView { id: verticalHeader anchors.top: horizontalHeader.bottom clip: true syncView: tableView } } Note thougt that in the official Qt docs using anchors inside layouts is explicitly listed as "Don'ts". My guess is that they mean don't use anchors between layout elements or parents of the layout, not don't anchor two elements inside a single layout cell.
70,884,514
70,885,149
clang-format indentation of class fields and methods, opening curly braces for functions and enums
My clang-format produces code like this: enum class SomeEnum{ VAL1, VAL2, VAL3 }; class SomeClass { public: void someMethod(); private: int m_field; }; void someFunc() { // ... } But I want it to be like this: enum class SomeEnum { VAL1, VAL2, VAL3 }; class SomeClass { public: void someMethod(); private: int m_field; }; void someFunc() { // ... } So I need enums to not be reduced to one line like this, for class methods and fields to have an additional level of indentation after access specifiers, and for the opening curly brace of my functions to be one space after ')' and not in another line Here is my .clang-format file AccessModifierOffset: '0' AlignAfterOpenBracket: DontAlign AlignConsecutiveAssignments: 'true' AlignEscapedNewlines: Left AlignTrailingComments: 'true' AllowAllArgumentsOnNextLine: 'false' AllowAllConstructorInitializersOnNextLine: 'true' AllowShortBlocksOnASingleLine: 'true' AllowShortCaseLabelsOnASingleLine: 'true' AllowShortFunctionsOnASingleLine: Inline AllowShortIfStatementsOnASingleLine: Never AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: 'false' AlwaysBreakTemplateDeclarations: 'Yes' BreakBeforeBraces: Stroustrup ColumnLimit: '120' CompactNamespaces: 'false' Cpp11BracedListStyle: 'true' DerivePointerAlignment: 'true' FixNamespaceComments: 'true' IndentCaseLabels: 'true' IndentWidth: '4' KeepEmptyLinesAtTheStartOfBlocks: 'false' Language: Cpp MaxEmptyLinesToKeep: '2' NamespaceIndentation: All SortIncludes: 'true' SortUsingDeclarations: 'true' SpaceAfterCStyleCast: 'false' SpaceAfterLogicalNot: 'false' SpaceAfterTemplateKeyword: 'false' SpaceBeforeAssignmentOperators: 'true' SpaceBeforeCtorInitializerColon: 'true' SpaceBeforeInheritanceColon: 'true' SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: 'true' SpaceInEmptyParentheses: 'false' SpacesInAngles: 'false' SpacesInCStyleCastParentheses: 'false' SpacesInSquareBrackets: 'false' TabWidth: '4' UseTab: ForContinuationAndIndentation
AllowShortEnumsOnASingleLine: false # is available since clang-format 12. IndentAccessModifiers: true # is available since clang-format 13. BraceWrapping: AfterFunction: false
70,884,737
70,887,379
Microsoft Bond deserialization without knowing underlying schema
I am looking at some network requests that are happening on my machine, and I recognize some as using the Microsoft Bond data serialization format. I want to deserialize the content of the request, but I do not have the schema that was used to create its content. I know that with the ProtoBuf compiler, there is a way to output the content of a ProtoBuf-based binary file without the schema with something like: protoc --decode_raw < data.proto Is something similar available for Microsoft Bond? I am happy to write C#/C++ code to get that done, but curious if that is even possible. For reference, the protocol is Compact Binary.
Thanks to some insights from Christopher Warrington, I was able to piece together the methodology through which a Bond-encoded Compact Binary content piece can be "unpacked" into its component pieces: var ib = new Bond.IO.Unsafe.InputBuffer(File.ReadAllBytes("response_data.bin")); var cbr = new CompactBinaryReader<Bond.IO.Unsafe.InputBuffer>(ib, 2); cbr.ReadStructBegin(); BondDataType dt = BondDataType.BT_BOOL; ushort id = 0; while (dt != BondDataType.BT_STOP) { cbr.ReadFieldBegin(out dt, out id); Console.WriteLine(dt + " " + id); if (dt == BondDataType.BT_STRING) { var stringValue = cbr.ReadString(); Console.WriteLine(stringValue); } else if (dt == BondDataType.BT_LIST) { BondDataType listContent = BondDataType.BT_BOOL; int counter = 0; cbr.ReadContainerBegin(out counter, out listContent); Console.WriteLine("Inside container: " + listContent); if (listContent == BondDataType.BT_STRUCT) { BondDataType structDt = BondDataType.BT_BOOL; cbr.ReadStructBegin(); while(structDt != BondDataType.BT_STOP) { cbr.ReadFieldBegin(out structDt, out id); Console.WriteLine(structDt + " " + id); if (structDt == BondDataType.BT_STRING) { var stringValue = cbr.ReadString(); Console.WriteLine(stringValue); } else { if (structDt != BondDataType.BT_STOP) { cbr.Skip(structDt); } } } cbr.ReadStructEnd(); } cbr.ReadContainerEnd(); } else { if (dt != BondDataType.BT_STOP) { cbr.Skip(dt); } } cbr.ReadFieldEnd(); } This is non-production code (you can spot many issues and lack of nested parsing) but it shows the approach through which one can get the contents.
70,884,905
70,885,043
QSqlQuery is not binding values
I am performing queries against a MySQL database, and use code similar to below throughout my app. But for some reason the update below says 0 rows affected, when it should be 1. On digging deeper I discovered my bindValue commands don't seem to have any effect. QSqlQuery* query = new QSqlQuery(m_db) query->prepare(QString("UPDATE companies SET " "NAME=:name, " "ISUSER=:isuser, " "ISVAR=:isvar, " "ISOEM=:isoem, " "CONTACT=:contact, " "EMAIL=:email, " "COMMENTS=:comments " "WHERE ID=:id " "LIMIT 1")); query->bindValue(":name",rowData.name); query->bindValue(":isuser",rowData.isEndUser); query->bindValue(":isvar",rowData.isVAR); query->bindValue(":isoem",rowData.isOEM); query->bindValue(":contact",rowData.contact); query->bindValue(":email",rowData.email); query->bindValue(":comments",rowData.comments); query->bindValue(":id",id); bool queryOk = query->exec(); if (queryOk) { qDebug() << query->executedQuery(); qDebug() << query->lastQuery(); qDebug() << query->lastError().text(); qDebug() << rowsAffected; There must be something different/wrong in the code above causing the output below: "UPDATE companies SET NAME=:name, ISUSER=:isuser, ISVAR=:isvar, ISOEM=:iSOEM, CONTACT=:contact, EMAIL=:email, COMMENTS=:comments WHERE ID=:id LIMIT 1" "UPDATE companies SET NAME=:name, ISUSER=:isuser, ISVAR=:isvar, ISOEM=:iSOEM, CONTACT=:contact, EMAIL=:email, COMMENTS=:comments WHERE ID=:id LIMIT 1" "" 0 But I can't see the problem, and the query returns no errors. Yet the query string seems to contain the variable names not substituted.
QSqlQuery::executedQuery() won't show you the bound values, because the idea of bound values is that they never become part of the query itself (which completely eliminates the problem of escaping them). What you see is the actual query submitted to the database. The bound values are submitted to the database alongside the query string (very much same like with QSqlQuery). As for the rowsAffected being zero, I don't see it being initialized or updated by the code in your example, which is likely why it says 0. you probably want to use query->numRowsAffected() instead. Finally (not related to any of your questions), you don't need to allocate the QSqlQuery on heap (unless you really need the query to outlive the scope in which it is created) and you can simply allocate it on stack. Fewer dynamic allocations == fewer chances of memory leaks :-)
70,885,405
70,886,084
C++ client socket sends original file and file size, Java client always get 8 bytes more. Even after force limiting to -8 bytes file is unreadable
For a while, I am troubled with this issue. Using a snippet of C++ code, which I found here, and in my opinion should do a good job actually sending exact amount of data, I guess the problem is in the Java code or something unknown. Also, when sending simple "Hello World" data, transfer is done correctly. I would be grateful is somebody could solve it, or give a valuable advice. I am running Windows 10 with jdk1.8.0_221 and Visual Studio 2022. I understand there could be a need to send filesize as a string and aknowledge flag in return in future, but for simplicity the C++ client is sending only one file with known amount of data. Here is the Java side: while(!Terminate) { byte[] bytes = new byte[1];//code was different for a real buffer //...still +8 bytes while (in.available() > 0) { in.read(bytes); out.write(bytes); out.flush(); } } out.close(); 8 bytes again after I tried this: int filesize = 15670; int cnt = 0; while (cnt<filesize) { out.write(in.read()); out.flush(); cnt++; } It makes me think 8 bytes are added while saving. The C++ code: int SendBuffer(SOCKET s, const char* buffer, int bufferSize, int chunkSize = 4 * 1024) { int l = -1; int i = 0; while (i < bufferSize) { int l = send(s, &buffer[i], __min(chunkSize, bufferSize - i), 0); //int l = send(s, &buffer[i], bufferSize , MSG_DONTROUTE); int j = 0; std::cout << i << std::endl; while (l < 0) { Beep(433, 1000); j++; std::cout << "shiban l" << l << std::endl; l = send(s, &buffer[i], __min(chunkSize, bufferSize - i), 0); } // this is an error i += l; } return i; } int64_t SendFile(SOCKET s, const std::string fileName, int chunkSize) { const int64_t fileSize = GetFileSize(fileName); if (fileSize < 0) { return -1; } std::ifstream file(fileName, std::ifstream::binary); if (file.fail()) { return -1; } if (SendBuffer(s, reinterpret_cast<const char*>(&fileSize), sizeof(fileSize)) != sizeof(fileSize)) { return -2; } char* buffer = new char[chunkSize]; bool errored = false; int64_t i = fileSize; auto bytes_sent = 0; while (i > 0) { const int64_t ssize = __min(i, (int64_t)chunkSize); if (!file.read(buffer, ssize)) { errored = true; break; } const int l = SendBuffer(s, buffer, (int)ssize); bytes_sent += l; int bi = 0; if (l < 0) { std::cout <<" err :"<< l<<std::endl; errored = true; break; } i -= l; } delete[] buffer; file.close(); std::cout << "bytes_sent:" << bytes_sent << std::endl; return errored ? -3 : fileSize; }
The C++ code is sending the file size before sending the file data (good), but is not doing adequate error handling (bad), and it is NOT sending the file size in an platform-agnostic format (bad). Not that it matters, because the Java code shown is NOT even attempting to read the file size before reading the file data (very bad), nor is it paying attention to the return value of in.read() to know how many bytes are actually received. But even if it were, the C++ code is sending the size as an 8-byte integer (needed for large files > 2GB), but the Java code is using a 4-byte integer instead (bad). The C++ is also using a 4-byte integer for bytes_sent in SendFile(). Try something more like this: BufferedInputStream bis = new BufferedInputStream(in); DataInputStream dis = new DataInputStream(bis); long filesize = dis.readLong(); if (filesize > 0) { byte[] bytes = new byte[4*1024]; do { int chunkSize = (int) Math.min(filesize, (long) bytes.length); dis.readFully(bytes, 0, chunkSize); out.write(bytes, 0, chunkSize); out.flush(); filesize -= chunkSize; } while (filesize > 0); } out.close(); bool SendBuffer(SOCKET s, const char* buffer, int bufferSize) { while (bufferSize > 0) { int numSent = send(s, buffer, bufferSize, 0/*MSG_DONTROUTE*/); if (numSent < 0) { Beep(433, 1000); return false; } } return true; } int64_t SendFile(SOCKET s, const std::string fileName, int chunkSize) { const int64_t fileSize = GetFileSize(fileName); if (fileSize < 0) { return -1; } std::ifstream file(fileName, std::ifstream::binary); if (file.fail()) { return -1; } const int64_t tmp = htonll(fileSize); // see https://stackoverflow.com/questions/3022552/ if (!SendBuffer(s, reinterpret_cast<const char*>(&tmp), sizeof(tmp))) { return -2; } std::vector<char> buffer(chunkSize); bool errored = false; int64_t bytes_sent = 0; while (fileSize > 0) { int ssize = static_cast<int>(std::min<int64_t>(fileSize, chunkSize)); if (!file.read(buffer.data(), ssize)) { errored = true; break; } if (!SendBuffer(s, buffer.data(), ssize)) { errored = true; break; } fileSize -= ssize; } file.close(); if (errored) { std::cout << "err" << std::endl; return -3; } std::cout << "bytes_sent:" << bytes_sent << std::endl; return bytes_sent; }
70,885,587
70,890,955
What happens when I read a file into a string
For a small program, seen here here, I found out that with gcc-libstdc++ and clang++ - libc++ reading file contents into a string works as intended with std::string itself: std::string filecontents; { std::ifstream t(file); std::stringstream buffer; buffer << t.rdbuf(); filecontents = buffer.str(); } Later on I modify the string. E.g. ending_it = std::find(ending_it, filecontents.end(), '$'); *ending_it = '\\'; auto ending_pos = static_cast<size_t>(std::distance(filecontents.begin(), ending_it)); filecontents.insert(ending_pos + 1, ")"); This worked even if the file included non-ascii characters like a greek lambda. I never searched for these unicode characters, but they were in the string. Later on I output the string to std::cout. Is this guaranteed to work in C++17 (and beyond)? The question is: What are the conditions, under which I can read file contents into std::string via std::ifstream, work on the string like above and expect things to work correctly. As far as I know, std::string uses char, which has only 1 byte. Therefore it surprised me that the method worked with non-ascii chars in the file.
Thanks @user4581301 and @PeteBecker for their helpful comments making me understand the problem. The question stems from a wrong mental model of std::string, or more fundamentally a wrong model of char. This is nicely explained here and here. I implicitly thought, that a char holds a "character" in a more colloquial sense and therefore knows of its encoding. Instead a char really only holds a single byte (in c++, in c its defined slightly differently). Therefore it is always well-defined to read a file into a string, as a string is first and foremost only an array of bytes. This also means that reading a file in an encoding where a "character" can span multiple bytes results in those characters spanning multiple indices in the std::string. This can be seen, when outputting a single char from the string. Luckily whenever the file is ascii-encoded or utf8-encoded, the byte representation of an ascii character can only ever appear when encoding that character. This means that searching the string of the file for an ascii-character will exactly find these characters and nothing else. Therefore the above operations of searching for '$' and inserting a substring after an index that points to an ascii character will not corrupt the characters in the string. Outputting the string to a terminal then just hands over the bytes to be interpreted by the terminal. If the terminal knows utf8, it will interprete the bytes accordingly.
70,886,218
71,176,625
Torchscript/C++ jit::trace model - Accessing layers parameters
I have a model I trained in python, traced using torch.jit.trace, and load into C++ using torch::jit::load. Is there a way to access the last layer to pull the value for the models required output depth (for example, if it is a Conv2D layer going from 16 -> 2, I want to predefine a tensor for a depth [b,d->2,x,y] of 2)?
Not the most elegant way of solving this, but the most straightforward was just passing a dummy tensor through and accessing the shape. Another way I did try was accessing the parameter list and looking for "softmax", unfortunately I couldn't guarantee everyones model will spell it the same way when searching for this. If someone else has a good answer for this feel free to share, but this will have to do for now.
70,886,369
70,887,400
How to efficiently scan 2 bit masks alternating each iteration
Given are 2 bitmasks, that should be accessed alternating (0,1,0,1...). I try to get a runtime efficient solution, but find no better way then following example. uint32_t mask[2] { ... }; uint8_t mask_index = 0; uint32_t f = _tzcnt_u32(mask[mask_index]); while (f < 32) { // element adding to result vector removed, since not relevant for question itself mask[0] >>= f + 1; mask[1] >>= f + 1; mask_index ^= 1; f = _tzcnt_u32(mask[mask_index]); } ASM output (MSVC, x64) seems blown up pretty much. inc r9 add r9,rcx mov eax,esi mov qword ptr [rdi+rax*8],r9 inc esi lea rax,[rcx+1] shrx r11d,r11d,eax mov dword ptr [rbp],r11d shrx r8d,r8d,eax mov dword ptr [rbp+4],r8d xor r10b,1 movsx rax,r10b tzcnt ecx,dword ptr [rbp+rax*4] mov ecx,ecx cmp rcx,20h jb main+240h (07FF632862FD0h) cmp r9,20h jb main+230h (07FF632862FC0h) Has someone an advice? (This is is a followup to Solve loop data dependency with SIMD - finding transitions between -1 and +1 in an int8_t array of sgn values using SIMD to create the bitmasks) Update I wonder if a potential solution could make use of SIMD by loading chunks of both bit streams into a register (AVX2 in my case) like this: |m0[0]|m1[0]|m0[1]|m1[1]|m0[2]|m1[2]|m0[n+1]|m1[n+1]| or 1 register with chunks per stream |m0[0]|m0[1]|m0[2]|m0[n+1]| |m1[0]|m1[1]|m1[2]|m1[n+1]| or split the stream in chunks of same size and deal with as many lanes fit into the register at once. Let's assume we have 256*10 elements which might end up in 10 iterations like this: |m0[0]|m0[256]|m0[512]|...| |m1[0]|m1[256]|m1[512]|...| and deal with the join separately Not sure if this might be a way to achieve more iterations per cycle and limit the need of horizontal bitscans, shift/clear op's and avoid branches.
This is quite hard to optimize this loop. The main issue is that each iteration of the loop is dependent of the previous one and even instructions in the loops are dependent. This creates a long nearly sequential chain of instruction to be executed. As a result the processor cannot execute this efficiently. In addition, some instructions in this chain have a quite high latency: tzcnt has a 3-cycle latency on Intel processors and L1 load/store have a 3 cycle latency. One solution is work directly with registers instead of an array with indirect accesses so to reduce the length of the chain and especially instruction with the highest latency. This can be done by unrolling the loop twice and splitting the problem in two different ones: uint32_t m0 = mask[0]; uint32_t m1 = mask[1]; uint8_t mask_index = 0; if(mask_index == 0) { uint32_t f = _tzcnt_u32(m0); while (f < 32) { m1 >>= f + 1; m0 >>= f + 1; f = _tzcnt_u32(m1); if(f >= 32) break; m0 >>= f + 1; m1 >>= f + 1; f = _tzcnt_u32(m0); } } else { uint32_t f = _tzcnt_u32(m1); while (f < 32) { m0 >>= f + 1; m1 >>= f + 1; f = _tzcnt_u32(m1); if(f >= 32) break; m0 >>= f + 1; m1 >>= f + 1; f = _tzcnt_u32(m0); } } // If mask is needed, m0 and m1 need to be stored back in mask. This should be a bit faster, especially because a smaller critical path but also because the two shifts can be executed in parallel. Here is the resulting assembly code: $loop: inc ecx shr edx, cl shr eax, cl tzcnt ecx, edx cmp ecx, 32 jae SHORT $end_loop inc ecx shr eax, cl shr edx, cl tzcnt ecx, eax cmp ecx, 32 jb SHORT $loop Note that modern x86 processors can fuse the instructions cmp+jae and cmp+jb and the branch prediction can assume the loop will continue so it just miss-predict the last conditional jump. On Intel processors, the critical path is composed of a 1-cycle latency inc, a 1-cycle latency shr, a 3-cycle latency tzcnt resulting in a 5-cycle per round (1 round = 1 iteration of the initial loop). On AMD Zen-like processors, it is 1+1+2=4 cycles which is very good. Optimizing this further appears to be very challenging. One possible optimization could be to use a lookup table so to compute the lower bits of m0 and m1 in bigger steps. However, a lookup table fetch has a 3-cycle latency, may cause expensive cache misses in practice, takes more memory and make the code significantly more complex since the number of trailing 0 bits can be quite big (eg. 28 bits). Thus, I am not sure this is a good idea although it certainly worth trying.
70,886,928
70,901,168
Default empty usage of methods of uninstantiated class
In my system I have many callbacks which contains calling for method of classes, that are not instantiated according to some configurations values, and when they are not initalized I want the calling to them to do nothing, instead of rasing a seg fault. For example I have some InitManager class that in it's constructor we have: if (config.is_connected) { std::shared<CloudClient> cloud_client = std::make_shared<CLoudCLient>(); } And in the InitManager I have a callback of some event coming from another process, which includes the following: ... cloud_client->saveData(); ... cloud_client->notifyUser(); ... So my current solution is before every method use to do: ... if (cloud_client) { cloud_client->saveData(); } ... if (cloud_client) { cloud_client->notifyUser(); } ... It keeps my wanted behaviour. The problem is that whenever another developer adds a new method, or uses an old one he might not check if the cloud_client exists, and we will figure it out only by tests when checking with that specific configuration. And in addition my solution makes the code less redable because it contain many if conditions. If anyone have some design solution which will enable me to do: cloud_client->notifyUser(); without the if condition every time and just do nothing when cloud client does not exists. Or even just make every use of this class's methods fail in compilation if developer didn't use the `if (cloud_client)` it will be great!
Thank you, OP, for editing your question. You have done a good job, the issue is now clear. I would suggest a 'wrapper' class for CloudClient - let's call it CloudClientWrapper, which holds a pointer to a CloudClient instance (which might be nullptr) as a member variable. CloudClientWrapper can then be responsible for testing whether that variable is nullptr, which means that callers don't need to worry about it. To prevent external code from calling CloudClient methods directly, declare them private and make CloudClientWrapper a friend of CloudClient. So, something like this: class CloudClient { friend class CloudClientWrapper; private: void Foo (); void Bar (); // ... }; class CloudClientWrapper { public: CloudClientWrapper (CloudClient *client) : m_client (client) { } void Foo () { if (m_client) m_client->Foo (); } void Bar () { if (m_client) m_client->Bar (); } // .... private: CloudClient *m_client; }; Your methods can take parameters and have return types, of course. CouldClientWrapper just needs to pass them on. It might be a lot of boilerplate, but I don't see a better way. Implementing CloudClientWrapper entirely in a header file might have some performance advantages, by the way. It makes it easy for the compiler to inline the code. There is such a thing as link time optimisation (LTO), which aims to do the same thing, but, in my experience, it slows down link times and generates a bunch of huge intermediate build products (I have given up on it).
70,887,004
70,888,738
How to check the CRC of the function in C++
Is it possible to count the CRC of code in the memory of the function in the runtime? I have a function that compares user's password with the secret password. If I check the CRC of all commands in function, I will be able to understand if the code of the function was overwritten in disassembler. For now, I've tried using the Boost::crc but I'm not sure, how can I pass the function into the crc_32_type object. This is not working (at least, returns a new result every time I run the program): void myFunction() {...}; auto GetCrc32() -> decltype(boost::crc_32_type().checksum()){ std::function<void()> func = myFunction; boost::crc_32_type result; result.process_bytes(&func, sizeof(func)); return result.checksum(); }
No, there is no portable way to find or access the compiled function code during execution. If code can be modified maliciously, then the code checking the code can also be modified maliciously to not detect changes, making the exercise entirely pointless. Lastly, a CRC is easily spoofed, so the code could easily be modified in a way that leaves the CRC unchanged. None of what you're trying to do makes any sense.
70,887,045
70,888,141
Difference between _mm256_extractf32x4_ps and _mm256_extractf128_ps
The intel documentation for _mm256_extractf32x4_ps and _mm256_extractf128_ps read very similar. I could only spot two differences: _mm256_extractf128_ps takes a const int as parameter, _mm256_extractf32x4_ps takes an int. This should not make any difference. _mm256_extractf128_ps requires AVX flags, while _mm256_extractf32x4_ps requires AVX512F + AVX512VL, making the former seemingly more portable across CPUs. What justifies the existence of _mm256_extractf32x4_ps?
Right, the int arg has to become an immediate in both cases, so it needs to be a compile-time constant after constant propagation. And yeah, there's no reason to use the no-masking version of the C intrinsic for the AVX-512VL version in C; it only really makes sense to have _mm256_mask_extractf32x4_ps and _mm256_maskz_extractf32x4_ps. In asm you might want the AVX-512 version because an EVEX encoding is necessary to access ymm16..31, and only VEXTRACTF32X4 has an EVEX encoding. But this is IMO something your C compiler should be able to take care of for you, whichever intrinsic you write. If your compiler optimize intrinsics at all, it will know you're compiling with AVX-512 enabled and will use whatever shuffle allows it work with the registers it picked during register allocation. (e.g. clang has a very aggressive shuffle optimizer, often using different instructions or turning shuffles into cheaper blends when possible. Or sometimes defeating efforts to write smarter code than the shuffle optimizer comes up with). But some compilers (notably MSVC) don't optimize intrinsics, not even doing constant-propagation through them. I think Intel ICC is also like this. (I haven't looked at ICX, their newer clang/LLVM-based compiler.) This model makes it possible to use AVX-512 intrinsics without telling the compiler that it can use AVX-512 instructions on its own. In that case, compiling _mm256_extractf128_ps to VEXTRACTF32X4 to allow usage of YMM16..31 might be a problem (especially if there weren't other AVX-512VL instructions in the same block, or that will definitely execute if this one did).
70,887,350
70,887,630
Why second spin in Spinlock gives performance boost?
Here is a basic Spinlock implemented with std::atomic_flag. The author of the book claims that second while in the lock() boosts performance. class Spinlock { std::atomic_flag flag{}; public: void lock() { while (flag.test_and_set(std::memory_order_acquire)) { while (flag.test(std::memory_order_acquire)); //Spin here } } void unlock() { flag.clear(std::memory_order_release); } }; The reason we use test() in an extra inner loop is performance: test() doesn't invalidate cache line, whereas test_and_set() does. Can someone please elaborate on this quote? Test is still a read operation and need to be read from memory right?
Reading a memory address does not clear the cache line. Writing does. So in a modern computer, there is RAM, and there are multiple layers of cache "around" the CPU (they are called L1, L2 and L3 cache, but the important part is that they are layers, and the CPU is at the middle). In a multi-core system, often the outer layers are shared; the innermost layer is usually not, and is specific to a given CPU. Clearing the cache line means informing every other cache holding this memory "the data you own may be stale, throw it out". Test and set writes true and atomically returns the old value. It clears the cache line, because it writes. Test does not write. If you have another thread unsynchronized with this one, it reading the cache of this memory doesn't have to be poked. The outer loop writes true, and exits if it replaced false. The inner loop waits until there is a false visible, then falls to outer loop. The inner loop need not clear every other cpu's cache status of the value of the atomic flag, but the outer has to (as it could change the false to true). As spinning could go on for a while, avoiding continuous cache clearing seems like a good idea.
70,887,967
70,888,044
Pointer confusion causing "no matching function call for std::vector"?
I have a C++ class that has a datamember: private: std::vector<std::vector<int>> *edges; Then in my constructor, I do the following: //rows and columns are dynamically set in constructor edges = new vector<vector<int> >(rows*columns, vector<int>()); edges[0].push_back(1); When running my program, I get error: no matching function for call to std::vector<std::vector<int> >::push_back(int) edges[0].push_back(1); ^ I just know this has to do with pointers/references but I'm not experienced enough with C++ to figure it out and this error message feels so vague. Anybody know whats wrong here with these two lines? EDIT1: I also tried changing the datamember to an object (not a pointer) and doing this but now my program is just stalling for (int i = 0; i < (rows*columns); i++) { vector<int> neighbors; edges.push_back(neighbors); } EDIT2: I also tried using paxdiablo's answer but now this line is throwing a bad_alloc edges = new vector<vector<int> >(rows*columns, vector<int>());
Here's an example of loading a 2d vector: std::vector<std::vector<int>> board; for (int row = 0; row < 4; ++row) { std::vector<int> row; for (int column = 0; column < 4; ++column) { row.push_back((row * 4) + column); } board.push_back(row); } The above code initializes a 2d array, 4x4, with a unique number for each slot/square. The inner loop initializes a "row" vector. After the "row" vector is initialized, it is "push_back" to the "board" vector.
70,889,063
70,916,588
Should Lippincott functions be declared noexcept?
EDIT: Another way to ask this question, in perspective, is to ask: Should Lippincott functions "catch all"? Should Lippincott functions be declared noexcept?, does it matter? After all, a version of this function in which all exceptions are captured, by definition cannot produce an exception. However, in all the examples I see online, the noexcept is never there and I was wondering if I was missing something. Example case: foo_Result lippincott() noexcept??? { try { throw; } catch (const MyException1&) { return FOO_ERROR1; } catch (const MyException2&) { return FOO_ERROR2; } catch (...) { return FOO_UNKNOWN; } } foo_Result foo_dothing() { try { foo::DoThing(); return FOO_OK; } catch (...) { return lippincott(); } }
Not all catch (...) executions come from a C++ exception. It is typically advisable to rethrow the exception in any catch-all block. This would imply that lippincott should not be noexcept and also just not have the catch-all block. Specifically, in the ABI commonly used for C++ outside of Windows, forced unwinding may execute catch-all blocks: A catch-all block may be executed during forced unwinding. For instance, a longjmp may execute code in a catch(...) during stack unwinding. However, if this happens, unwinding will proceed at the end of the catch-all block, whether or not there is an explicit rethrow. In particular, with GCC on Linux, the blocks are executed, and if not rethrown, the application is terminated. Forced unwinding can happen even in code you completely control on POSIX if you ever call cancellation points (e.g. read). Aside from this, it's not uncommon for a library to execute user code (e.g. think qsort). You also usually don't want to suppress those exceptions. Therefore, the best generic option is to be transparent in catch-all blocks. Perform the cleanup you need. Then always rethrow. So your function would look something like: foo_Result lippincott() { try { throw; } catch (const MyException1&) { return FOO_ERROR1; } catch (const MyException2&) { return FOO_ERROR2; } catch (const FooBaseException&) { return FOO_UNKNOWN; } } GCC does allow catching forced unwinds, so if you really wanted a catch-all and the other consideration is discarded (e.g. no user callbacks), you can first catch abi::__forced_unwind and rethrow.
70,889,426
70,894,566
Windows Explorer integration look like in SolidWorks PDM
I looking for information about integration to Win Explorer in generally and about add custom column in particular. I'm already found some about Cloud Sync Engines, but it's only for Win 10 and newer, when i need to support Win7. I found some about Property Handlers, but it's can't be used for all file types at once. I'm also read a little-bit about Developing with Windows Explorer. And something about Folder View, but in "legacy" section. I also found Idiots Guide to Writing Shell Extension , but i think is legacy too, and some features not working anymore. I also saw this panel: And i heard that can be implemented with IDeskBand. Bar like that can be enough for me for use instead of column. But i'm not sure is really can be implemented with information at this link or it's more complicated and need something else? It's my first question. I also was experience to use SolidWorks PDM where we can see some awesome integration with a variety of custom elements. And custom tools for search: And my question number 2, is: Have someone information about how it's all realized? How make it? In particular: 3. How they implement custom columns? 4. How to add fully custom panel? (On picture it's panel with tabs in down-side) 5. Anyone test SW PDM on latest Windows versions? All of that features is works in latest Win? P.S. Images take from SD PDM sites, and footnotes with numbers mean nothing.
Shell file browsers are composed of two parts, the browser (Tool bar, address bar, details pane and navigation tree) and the view (file list). There is very little you can customize in the browser. The view however can be anything you want when you implement a name space extension. To do this you must create a DLL that you register in the registry. This DLL must implement the IPersistFolder, IShellFolder and IShellView interfaces. Details can be found here. The root of your NSE can be in a special location like the Desktop or in My Computer or it can be any folder on the file system (one is registry based, the other uses the GUID file extension trick or desktop.ini). Support for custom column handlers were removed in Vista. The other shell extension types still work but they do not give you control over the view itself.
70,889,823
70,890,222
C++ std::find_if on iterator in reverse order
In the following code, is there an elegant way to find it_end? #include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <type_traits> template <class Iterator, class U = typename std::iterator_traits<Iterator>::value_type> void process(Iterator begin, Iterator end) { // first nonzero auto it_begin = std::find_if(begin, end, [](U val){return val != 0;}); // end of nonzero values int n = std::distance(begin, end); int index = n-1; for(int i=n-1; i>=0; --i) { if(*(begin+i) == 0) { index = i; } else { break; } } auto it_end = begin; std::advance(it_end, index); // ******* is there a way to use std::find_if or similar function to get it_end? ******* for(auto it=it_begin; it!=it_end; ++it) { // a whole bunch of things // ... std::cout << *it << std::endl; } } int main() { std::vector<int> v{0,0,1,2,3,0,0}; process(v.begin(), v.end()); }
use std::reverse_iterator. #include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <type_traits> #include <list> template <class Iterator, class U = typename std::iterator_traits<Iterator>::value_type> void process(Iterator begin, Iterator end) { // first nonzero auto it_begin = std::find_if(begin, end, [](U val){return val != 0;}); if (it_begin == end) return; // all value is zeros. // reverser iterator auto r_begin = std::reverse_iterator(end); auto r_end = std::reverse_iterator(it_begin); auto r_find = std::find_if(r_begin, r_end, [](U val) { return val != 0; }); auto it_end = r_find.base(); for(auto it = it_begin; it != it_end; ++it) { std::cout << *it << std::endl; } } int main() { std::list<int> v{0,0,0,2,0,3,4}; process(v.begin(), v.end()); }
70,890,463
70,917,303
Count of total Numbers With 3 set Bits only in a range
I recently come across a question , Question statement is like this : For given value of L and R, We have to find the count of number X, which have only three-set bits in it's binary representation such that "L ≤ X ≤ R". Expected Time Complexity: O(log(63^3)) Expected Auxiliary Space: O(1) Link - https://practice.geeksforgeeks.org/problems/akku-and-binary-numbers0902/0/ I have tried this solution but it is showing to optimize more , any suggestion how I can optimize it long long solve(long long l, long long r){ long long count = 0,ctr=0; for(long long j=l; j<=r; j++){ count = 0; for(int i=31; i>=0; i--) { if(j & (1<<i)) count++; if(count>3) break; // If counts more than 3 set bits then break it } if(count==3) ctr++; } return ctr; }
The idea behind the code is fairly simple. We generate binary numbers by taking set bits. In this question three set bits have been asked, so we will make three variables and run three while loops. For example, numbers are asked --> 11 to 19 we take i = 1 j = 2, k = 4 and start the loops. We make temp as OR of - i j and k. For example when representing in binary 1 = 0001 2 = 0010 4 = 0100 OR = 0111 --> 7 , Hence if the number is in the range [l,r] the count is increased. Code by --> https://auth.geeksforgeeks.org/user/628826/practice/ long long solve(long long l, long long r){ long long i = 1; long long cnt = 0; while (i < r) { long long j = i << 1; while (j < r) { long long k = j << 1; while (k < r) { long long tmp = i | j | k; //cout<<i<<" "<<j<<" "<<k<<" "<<tmp<<endl; if (l <= tmp && tmp <= r) ++ cnt; k <<= 1; } j <<= 1; } i <<= 1; } return cnt; }
70,890,728
70,891,490
Does fully specialized template function violate ODR with a regular function?
I just realized this snippet compiles safely without any warnings on g++ and clang. (given --std=c++14 --Wall) #include <iostream> template <typename T> void foo(const T& a, const T& b) { std::cout << "1. Template version called.\n"; } template <> void foo(const int& a, const int& b) { std::cout << "2. Template specialized version called.\n"; } void foo(const int& a, const int& b) { std::cout << "3. Regular function version called.\n"; } int main() { // Prints: 3. Regular function version called. foo(4, 2); } But I am not sure if, according to the standards, the 2. Template specialized version and 3. Regular function version violates ODR or not. So, does this violate ODR? If not, is it guaranteed that foo(4,2) always calls the 3. Regular function version? Or is it compiler dependent?
Short answer: No it does not violate ODR and yes it is guaranteed to call the regular function, as long as you use an C++ standard compliant compiler. When calling foo, the compiler first makes a list of candidate functions, by looking up the name foo. On of the candidates is the regular function. It also goes through template type deduction and eventually finds your specialization to be a second candidate for overload resolution. After that the compiler produces a set of viable candidates by matching the number of arguments and testing if there is an implicit conversion between the arguments and the parameters you provided. Both the candidates (the regular function and the specialized template) pass this stage and are viable. Then, the compiler decides which of the viable candidates is the best, by following a set of rules which are described e.g. here. Normally it would take the candidate whose parameter types match the argument types best (rule 1.-3. as in the linked page). However because your parameter types are exactly the same, it goes to rule 4, which says that non-templated functions take precedence over template-specalizations. So the regular functions is picked! Now to come to your question regarding the ODR violation: The compiler assings the template a different symbol than the regular function. If you compile the program from above and look at the exported (mangled) symbols, you will see something like void foo<int>(int const&, int const&) foo(int const&, int const&) So both functions are exported and could also be called (according to the same rules as described above) from other translation units. Note One additional note on function template specialization. There are reasons to prefer overloading functions to specialized function templates. If providing a specialization where two or more templates could be the "parent", you can run into strange effects, where declaration order affects the actual outcome. You can find a more information on this topic and an example in the answer to this question.
70,890,802
70,890,851
how to allocate memory int pointer array inside a function and delete the allocated memory in main.cpp
I am trying to allocate memory to a pointer to an array using a non-template type argument. But, I am getting a run time error at delete ptr in the main function. #include <iostream> using namespace std; template<typename T, int SIZE> void createArray(T** arrPtr) { *arrPtr = new T[SIZE]; for (int i = 0; i < SIZE; i++) (*arrPtr[i]) = i + 1; } int main() { constexpr int size = 3; int* ptr = nullptr; createArray<int, size>(&ptr); if (ptr == nullptr) return -1; for (int i = 0; i < size; i++) std::cout << *(ptr++) << " "; delete ptr; ptr = nullptr; return 0; }
Within the function instead of this statement (*arrPtr[i]) = i + 1; you need to write (*arrPtr )[i] = i + 1; And in this for loop the original pointer ptr is being changed. for (int i = 0; i < size; i++) std::cout << *(ptr++) << " "; As a result in this statement delete ptr; there is used an invalid address of the allocated dynamically memory. Change the loop for example like for ( const int *p = ptr; p != ptr + size; ) std::cout << *p++ << " ";
70,890,848
70,900,975
Singleton with read-only and write access
I have a class T and want a single global object of that class given by accessor functions like T const& read_singleton() and T& modify_singleton(). The object should be instantiated at first use of one of these functions by the default constructor of T and the usage of the functions should be thread-safe. What is a (good) design pattern to achieve this?
It's easy enough to write these functions: T& modify_singleton() { T static t{}; return t; } T const& read_singleton() { return modify_singleton(); } This is the Meyers singleton pattern and can also be implemented as static functions of T, in case you have control over its implementation and want to make its constructor/destructor and such private. The initialisation of variable t will be thread-safe. However, what happens when multiple threads obtain a T& is outside the control of modify_singleton. You will have to coordinate modifications to the object, either with a global mutex or by designing its class to be thread-safe. If you cannot modify class T, you could also provide a thread-safe interface through a wrapper class.
70,892,070
70,893,017
Check if vector have no cube values of another element
I have the following algorithm, can somebody help me solve this? I just need an explanation. "A vector a[] with n integer elements is cube-repetition-free if no element is the cube of another element, i.e., there are no indices i,j such that a[i] = a[j]3 . Propose an O(n*log(n))-time algorithm in order to decide whether a vector is cube-repetition-free."
O(n) solution: Add each element v[i] of the vector to a hash set. For each element v[i] check whether v[i] * v[i] * v[i] is in the set. O(n*logn) solution: Sort the vector v. Pointers start = 0 and end = 1. While end < n do the following: if v[start] * v[start] * v[start] equals v[end] then the vector is not cube-repetition-free. if v[start] * v[start] * v[start] < v[end] then increment start. Otherwise increment end.
70,892,352
70,896,742
CEF - Get html in std::string
Can someone please suggest an example for CEF - how to load an HTML page and put it in std::string? I looked at the documentation of the CEF, but unfortunately I could not figure out how to do it.
Here's the function you can use: https://bitbucket.org/chromiumembedded/cef/src/7b0bb931b19cb192b1a0cb1838e639a4ad9fb6e3/include/cef_frame.h#lines-123 #include "include/cef_frame.h" /// // Retrieve this frame's HTML source as a string sent to the specified // visitor. /// /*--cef()--*/ virtual void GetSource(CefRefPtr<CefStringVisitor> visitor) = 0;
70,892,584
70,915,762
av_seek_frame seek only every 12th frames
I use ffmpeg video player in my graphic aps. Now I need to implement correct way to start video with specific frame (not only with first). I found good example here and at first thought, that it works for me perfectly: bool seek(uint64_t frame) { int64_t timeBase = (static_cast<int64_t>(_pContext->time_base.num) * AV_TIME_BASE) / static_cast<int64_t>(_pContext->time_base.den); auto seekTarget = static_cast<int64_t>(frame) * timeBase; if( av_seek_frame(_pFile, -1, seekTarget, AVSEEK_FLAG_ANY) < 0) return false; avcodec_flush_buffers( _pContext ); return true; } However, lately I noticed that it seeks only every 12th frame: seek(10); //gives 0 frame seek(12); //gives 12 frame seek(20); //gives 12 frame seek(80); //gives 72 frame I guess I calculate timeBase incorrectly, but actually I can't find inforamation how to do it in correct way. There are plenty of code examples, but I've tried many of them and it didn't work at all. It's even weired, that I found too many different ways to calculate the same variable. P.S. It would be great if someone explain me the meaning of timeBase value, or share good explanation.
You need to seek to the previous key frame and decode until you have the frame that you want. You can't seek to ANY frame as the decoder will not decode properly the requested frame. You can find a detailed discussion and code here
70,893,366
70,896,068
ambiguous overload with ostream
I'm stuck with this why trying to overlap ostream of std::array in c++. (error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'const char [2]') here is my script: #include <bits/stdc++.h> using namespace std; template<typename T> ostream& operator <<(ostream& out, T& arr) { bool pre = false; for(auto& i : arr) { if(pre) out << ' '; pre = true; out << i; } return out; } signed main() { array<int, 4> a = {123, 123, 12, 12}; cout << a << "\n"; return 0; }
This forces the overload to take only std::array, which should solve your ambiguous overload problem: template<typename T, std::size_t N> ostream& operator <<(ostream& out, const std::array<T, N> &arr) { bool pre = false; for(auto& i : arr) { if(pre) out << ' '; pre = true; out << i; } return out; }
70,893,993
70,896,507
Compile error when using QUERY like in documentaion described
I'm following the documentation and got an error during compilation following example: https://oatpp.io/docs/components/api-controller/#query-parameters-mapping Visual Studio 2017 is complaining about C2839:invalid return type 'type' for overloaded 'operator ->' and C2232 '->' : left operand has 'class-key' type, use '.' when I try to use age like mentioned in the example. ENDPOINT("GET", "/users", getUsers, QUERY(Int32, age)) { OATPP_LOGD("Test", "age=%d", age->getValue()); return createResponse(Status::CODE_200, "OK"); } What's wrong with the usage/example?
Documentation is outdated, solution is: OATPP_LOGD("Test", "age=%d", *age);