question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
63,036,350
63,036,697
Compiler optimization when using const bool to remove debug information
I have a class with a debug function named log(std::string s) I am working on a small embedded system, therefore I want to remove unnecessary strings from the binary. I could use #define to achieve what I want, but I think it is a bad practice. Using -Os optimization I though I could use a const bool like so: #include ...
You are using std::string. The compiler is not smart enough to see through all the std::string machinery, and I doubt it is even allowed to eliminate the std::string construction. Since the string literal is used to initialise the std::string, the literal cannot be eliminated either. If you want to save a few bytes, pe...
63,036,383
63,038,822
Cython unsigned char uuid_t[16] representaion
I have structure declarations in my code: cdef extern from "uuid/uuid.h": ctypedef unsigned char uuid_t[16] cdef extern from "fr_common.h": ctypedef uuid_t fr_id_t ctypedef struct fr_event_t: fr_id_t id size_t action fr_id_t object_id long long ts Here I have cython class whe...
The error message is a bug in Cython an makes it pretty hard to diagnose. However, what you're trying to do doesn't make a lot of sense to me. __init__ and __cinit__ are fundamentally Python methods and their arguments must be Python objects All constructor arguments will be passed as Python objects. This implies that...
63,036,624
63,057,409
How to enable C++17 code generation in VS2019 CUDA project
I am moving some code from VS2017 on one pc to another pc with VS2019. Everything is fine excepted that I cannot use std::filesystem. In my former code, I was using C++14 and had std::experimental::filesystem. In the new code, I want to move to C++17 so I changed to std::filesystem (as shown in my code below). The weir...
Using CUDA 11, the nvcc compiler-driver is capable of supporting usage of certain C++17 language features. Currently, in VS2019, this doesn't appear to be the default behavior. The following method should work to enable C++17 support when compiling a cuda project in VS2019: go to Project..Properties..Configuration Pro...
63,036,733
63,036,782
segmentation fault (core dumped) using structures and pointers
this is the first time I am asking a question here, so here is the context: The project on which I work to is confidential and quite complex, however, it is a mix of C C++ and PostgreSQL, it is all I can say. Neverthless, here is a minimum WORKING example (that actually compile fine) but throws an error after generatio...
You must allocate objects to be accessed and assign their pointers before dereferencing pointers. int main () { IndexTuple itup; itup = new IndexTupleData; // allocate object and assign its pointer (*itup).t_info = 1; cout << ((*itup).t_info) << endl; delete itup; // delete allocated object...
63,036,824
63,112,859
Why the program suddenly closes when I hover the cursor in area from 0 to 100 on x axis in allegro
I'm new in allegro and trying to make a small, very basic painting program. I want this program to stop painting when in the area from A(0, 0) to B(100, 600) on 800x600 plane. When I hover my cursor in this area the program suddenly closes itself. Here is the code: #include <allegro5/allegro.h> #include <allegr...
Let's look at what ALLEGRO_EVENT event is, via the docs: An ALLEGRO_EVENT is a union of all builtin event structures, i.e. it is an object large enough to hold the data of any event type. All events have the following fields in common: type (ALLEGRO_EVENT_TYPE) Indicates the type of event. [...] By examining the type ...
63,037,471
63,037,507
Command Line Argument adding an extra parameter
I am trying to explore command line argument in C++ in Visual Studio 2010. It is working fine but it is adding one extra parameter at args[0] any reason why? Here is the snapshot of how I am setting my arguments the main method is as follows int main(int argc, char *argv[]) { cout<< endl << "total args passed in t...
The first entry in the list is the program name; that's how it's designed to work.
63,037,587
63,037,941
Using extern array in class method -> undefined reference
Can someone please explain me why #include <iostream> namespace helper1 { void syncAPI(); }; void helper1::syncAPI() { extern int *arrayOfIntPointers[]; std::cout << *arrayOfIntPointers[0] << std::endl; } int *arrayOfIntPointers[5]; int main() { int *newInt = new int; *newInt = 1; helper1::...
The declaration extern int *arrayOfIntPointers[]; is still inside the namespace, even though it's an extern declaration. So it declares helper1::arrayOfIntPointers. The definition int *arrayOfIntPointers[5]; is outside a namespace, so it defines arrayOfIntPointers in the "global" namespace - a different object. To fix ...
63,037,709
63,042,115
Cmake issue: 'FreeImage.h' file not found
Error message: 'FreeImage.h' file not found CmakeList (I'm on MAC): cmake_minimum_required(VERSION 3.10) set(PROJECT_NAME KinectFusion) project(${PROJECT_NAME}) set (CMAKE_CXX_STANDARD 14) set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) add_definitions(-DPROJECT_DIR="${PROJECT_SOURCE_DIR}") se...
After find_package(FreeImage REQUIRED) insert include_directories(${FREEIMAGE_INCLUDE_DIRS}) or include_directories(${FreeImage_INCLUDE_DIR}) (depending on which FindFreeImage.cmake module you're using) and it should work. Alternatively use include_directories(/usr/local/include) find_package(<pkg-name> REQUIRED) jus...
63,038,244
63,039,231
Vulkan; Get list of uniforms & attribs from SPIR-V shader
Looking for a Vulkan alternative for this; In OpenGL is there a way to get a list of all uniforms & attribs used by a shader program?
Vulkan, as a general rule, does not have querying APIs for any information you have provided to the API. If you give something to the API, and you need to know something about that data, then you're expected to remember what it was. SPIR-V contains all of the definitions of the various resources and interfaces used by ...
63,038,287
63,038,565
Why can a mutex lock twice without unlock in C++?
int main(){ std::mutex mut; mut.lock(); cout<<"1111\n"; mut.lock(); cout<<"2222\n"; return 0; } Why does this code work and output 2222? Shouldn't it block at the second lock()? In the mutex source code, the operation lock throws an exception. Shouldn't it block a...
It cannot. Your code has undefined behavior. From cppreference: If lock is called by a thread that already owns the mutex, the behavior is undefined: for example, the program may deadlock. An implementation that can detect the invalid usage is encouraged to throw a std::system_error with error condition resource_deadl...
63,038,472
63,050,466
QTableWidget check right mouse even cell pressed
I am a beginer with QT. I want to display menu ( copy, paste, clear) when right-click mouse btuton on QTableWidget. In mainwindow i can use mousePressEvent(QMouseEvent* event), but in QTableWidget i can't do that.
One way is to have widgets show a context menu from the list of actions you set on the widget. See QWidget::addAction() and the related functions. Set the widgets contextMenuPolicy to Qt::ActionsContextMenu to use this approach. You can also handle the menu manually by modifying the contextMenuPolicy to be Qt::CustomCo...
63,038,561
63,038,844
Replacement to getch based code block in cpp
I stumbled upon a code from 2016 written in the Turbo C++ IDE in windows It was to accept passwords char pass; for (length = 0;;) { pass=getch(); if (pass == 13) { break; } if ((pass >= 'A' && pass <= 'Z') || (pass >= 'a' && pass <= 'z') || (pass >= '0' && pas...
There is no standard replacement in C++. Linux (and similar systems such as BSD), there is a legacy function getpass whose use is not recommended. I mention it because the documentation of that function in glibc suggests following: This precise set of operations may not suit all possible situations. In this case, it i...
63,038,655
63,038,879
Why won't std::uniform_real_distribution generate proper floating values?
I'm trying to print random float(32-bit) values. I tried using uniform_real_distribution for this purpose. I wrote the following code, int main() { std::random_device rd{}; std::mt19937 gen{rd()}; std::uniform_real_distribution<float> dist(-1e18,1e18); float random_val = dist(gen); printf("%.20f\n", random...
float is usually IEEE Single-precision floating-point format, which works like scientific notation, which has 1 sign bit, 8 exponent bits, and 23+1 fraction bits. So 817395979383734272.0 is stored as 1.41795599 * 2^59 in memory. That fractional part is only ~8 decimal digits, because that's all the precision it can squ...
63,039,080
63,039,160
Parsing and slicing char[] in C++
I have the following code: char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; int iResult = recv(this->ClientSocket, recvbuf, recvbuflen, 0); if (iResult > 0) { printf("Message received: %s\n", recvbuf); std::string recvbuf = recvbuf; printf("Message as string: %s\n", recvbuf); std::string ...
Firstly, it seems the buffer is not null-terminated, so you should use basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() ); to initialize string with specifying size. Secondly, the string initialization cannot access the buffer because the name collides. Th...
63,039,113
63,039,541
Passing a parameter of type int(*)[] in C++
The following program compiles in gcc but not g++: void foo(int (*x)[]) { // do something } int main() { int x[3]; foo(&x); // g++ error: cannot convert ‘int (*)[3]’ to ‘int (*)[]’ return 0; } I am trying to use a library written in ANSI C, so I have no contr...
The following program compiles ... not g++: This is because g++ compiles in the C++ language. And the shown program is ill-formed in the C++ language. In particular, the problem is that the function parameter is a pointer to an array of unknown bound, but the passed argument is a pointer to an array of length 3. And ...
63,039,288
63,039,631
what does __getstate_manages_dict__ do?
I've been working on multiprocessing and C++ extensions and I don't quite get the __getstate_manages_dict__ function (I know how to use it, but I'm not really sure how it works). The boost/Python documentation for pickle support says this: The author of a Boost.Python extension class might provide a __getstate__ metho...
I know how to use it, but I'm not really sure how it works It's a boolean value that is False by default. The point is to signal to Boost that the __getstate__/__setstate__ implementation handles the class' __dict__ attribute, so that the information won't be lost in the pickling process. The idea is that Boost::Pyth...
63,039,295
63,039,474
Operator overloading with template question
I'm unable to recognize the following forms of operator overloading, specifically with the template parameter involved. I found this while reading an article on nullptr. I do not see these forms on cppreference overloading page either. Can anyone explain these forms of overloading and what they are doing? Thanks stru...
Starting simpler: struct A { operator int() {return 3;} }; void function() { A aobject; int value = aobject; //uses A::operator int() //value is now 3 } operator int is a curious member function that allows the struct to be converted to an int. It's very curious in that it's the only case in C++ that ...
63,039,674
63,039,949
count frequencies of all elements in array without using another array or changing the elements of the given array
Hello so the catch of this problem is you shouldn't use another array or function and do not change the elements of the given array or sort them and we don't know the interval of the elements and side note i shouldn't show the numbers twice for example if we have a[10]={1,2,1,3,1,5,2,4,3,1} it should print out : 1 --- ...
See the code below. I made the array a constant for brevity. You can just copy-paste in your code that reads it from the user input. The trick is to check for each i that this is the first time that a[i] is found. If it has been found before, then it has already been counted on that previous iteration, and can be skipp...
63,039,771
63,049,143
How to handle tuples and single tokens differently in C++ preprocessing?
I want to define a INITIALIZE(...) that achieves the following struct MyStruct { std::string a; bool b; char c; double d; INITIALIZE(a, (b, true), (c, '$'), d); }; gets expanded to struct MyStruct { std::string a; bool b; char c; double d; void init() { a = get_value<st...
This is almost doable, you need an extra pair of parens around things initialized by default. #define INIT_1(x) x = get_value<decltype(x)>(); #define INIT_2(x, y) x = y; #define INIT_ONE(...) BOOST_PP_CAT(INIT_, \ BOOST_PP_VARIADIC_SIZE(__VA_ARGS__))(__VA_ARGS__) #define INIT_ONE_X(r, dat...
63,039,814
63,058,814
Directory of pybind11 module
I am writing a python module, that is going to be a library, using pybind11. At some point in my C++ code, I need to know the absolute path of my .so/.dll module (I need that to access to some files in a subdirectory inside the package containing my module). I tried to access to the __file__ attribute in this way: name...
If you're running solely from C++, this should work assuming your module is named example and can be found on the pythonpath. #include <pybind11/embed.h> namespace py = pybind11; void getModulePath() { py::scoped_interpreter guard{}; // start the interpreter and keep it alive py::object example = py::module::imp...
63,040,079
63,040,300
Integer user input in Qt
I am writing a GUI application in Qt. I need to get from the user a set of integers which will be loaded in an array. What might be the go to way to do this visually. This may seem easy but I don't have much experience in GUI applications. I'm thinking of using a lineEdit but that takes text as input and I'm not sure h...
Probably a good start point is something like a list view or table view or list widget: https://doc.qt.io/archives/qt-4.8/qlistview.html https://doc.qt.io/archives/qt-4.8/qtableview.html https://doc.qt.io/qt-5/qlistwidget.html Couple this with an QLineEdit as an entry mechanism. User types in a number - hits enter (l...
63,040,310
63,040,338
How to get the second last element of a set in C++?
Ex; We write for(int i=0;i<(somethin_length)-1;i++) How to do so using set?
If you have a set, just decrement the end iterator twice. // Check that we have at least two elements first; if we don't have at least // two then proceeding would cause undefined behavior. if (some_set.size() >= 2) { auto it = some_set.end(); --it; --it; // *it now refers to the second-to-last value }...
63,040,763
63,040,923
How to return all of the data in a COLORREF to the caller in C#
I'm trying to write a .dll and then call this .dll in C#. I followed this article: https://blog.quickbird.uk/calling-c-from-net-core-759563bab75d Now, I have the problem of how to return all of the data in a COLORREF to the caller in C#, and then to be able to distinguish the values. This is the source from the .dll: #...
COLORREF is just an alias for DWORD, which is indeed UInt32 in C#. So, your code looks fine, as far as calling your getColor() function in C#. Though, I would suggest making the function return CLR_INVALID (0xFFFFFFFF) on failure rather than returning 0 (Black), especially since GetPixel() returns CLR_INVALID on failu...
63,040,982
63,054,918
Error after implementing 'curl': E1696 cannot open source file "curl/curl.h"
The title says it all. I'm using VS 2019 since as far as I can understand, curl is more used on VS 2019 rather than VS Code (correct me if I'm wrong). So my project has this structure: ── myproject ├── myproject │ ├── src │ │ ├── main.cpp │ ├── myproject.vcxproj │ ├── myproject.vcxproj.fil...
(Thanks to @drescherjm) All you have to do is ensure you have applied the change in step #2 for all the configurations and platforms (go to the project 'myproject' -> (Right Click) -> Properties -> C/C++ -> General -> Additional Include Directories; in the top of the window, set 'Configurations' to "All Configurations"...
63,041,100
63,041,144
For a c++ set, what is set.size()&1?
here is the code and it returns "IGNORE HIM!" when the size is odd #include <set> std::set<char> s; int main(){ char c; while(std::cin>>c)s.insert(c); std::cout<<(s.size()&1?"IGNORE HIM!":"CHAT WITH HER!"); return 0; }
You've already noticed the pattern, i.e. set.size()&1 is true when the size is odd. Doing a bitwise-and (&) on a number will set all the bits to 0, except for the last bit, if it's 1. The last bit is only 1 when the number is odd. e.g. 101100 // even & 000001 = 000000 // false 101101 // odd & 000001 = 000001 ...
63,041,219
63,041,260
How to accept user input as the length of a vector in C++
How do i use userinput to determine the length of a vector? When using std::cin the size of the vector is always set to one despite what number i input. Any help would be appreciated. int main() { std::cout << "How many students do you want to enter?\n"; int numOfStudents{}; std::cin >> numOfStudents; ...
On this line: std::vector results{ std::size_t(numOfStudents) }; You have not specified the value_type of the vector, so the compiler is forced to do class-template-argument-deduction (CTAD) to figure out the type of results. It sees a single size_t variable in the brace-initializer, and decides that results is a std:...
63,041,350
63,041,707
Why return by reference while overloading = operator?
I know there's plenty of questions on this already, so please bear with me on this one. So I found this question, and I had a doubt about a modification of this. class Blah { public: Blah(); Blah(int x, int y); int x; int y; Blah operator =(Blah rhs); }; Blah::Blah() {} Blah::Blah(int xp, int yp) { ...
There is no strict right and wrong here. You can do weird things with operator overloads and sometimes it is appropriate. However, there is rarely a good reason to return a new instance from operator=. The return value is to enable chaining. Your test for chaining is incomplete. Your line: b3 = b4 = b2 = b1; is the sa...
63,041,408
63,815,698
unordered_map excess calls to hash function
The following code results with unexplained calls to the hash function: namespace foo { using Position = tuple <int, int, int>; std::ostream& operator<<(std::ostream& out, const Position& pos) noexcept{ return out << get<0>(pos) << ", " << get<1>(pos) << ", " << get<2>(pos); } struct hashF...
As others pointed out, an unordered map, which is just a form of a hash table, is in libstdc++ implemented basically just as a single ("global") linked list. Plus, there is an array of buckets that point into this list. What is important is that the pointer stored in bucket[i] does not point to the first node that belo...
63,041,628
63,041,963
does std::is_same has an impact on the performance of the code?
Does is_same has any impact on the code performance? I am using it multiple times in my code to check whether i have to use std::less or std::greater and depending on them i have to retrieve specific values. Is my test sufficient to prove that std::is_same does not really impact the performance of the code in my case? ...
std:is_same is a compile time check it is implemented with two different template footprints. One with 1 Type and 1 with 2 Types. std::is_same<T, T> //If the compiler resolves to this it is the same type; std::is_same<T, U> //If the compiler resolves to this it is 2 types; The implementation returns a type that then ...
63,041,912
63,042,068
Moving pointer to vector of vectors to specific position
I have a maze vector of vector of ints and a pointer line to that vector declared as follows. I also have a pointer to line that identifies each element in particular. std::vector<std::vector<int>> maze; auto * line = new std::vector<std::vector<int>>(maze); //pointer to maze to hold line position auto * co...
It is unclear to me how the pointer line works. This line auto * line = new std::vector<std::vector<int>>(maze); creates a fresh new instance of std::vector<std::vector<int>>, copying the contents of maze into that new instance, and then stores a pointer to the new instance in line. line is not a pointer to maze! T...
63,042,172
63,042,240
Assigning pointer to member function
I'm following up on an earlier question, however my question pertains to type issues. How do I assign a pointer to member function C::f() to the m pointer? Does the member function need to be static? #include <iostream> using namespace std; struct nullpt_t { template<class T> inline operator T*() const { retur...
All you have to do is take a pointer to the member function and assign it: m = &C::f; This only applies to non-static functions. Static functions have no instance associated with them, so you can take a standard function pointer to them. (Pointer-to-member is special because you have to supply an instance to dereferen...
63,042,183
63,042,331
I keep getting the error invalid use of incomplete type 'struct familyFinace' how do I fix this?
I am trying to append a node but I keep getting the error incomplete type 'struct familyFinace' how do I fix this? #include <iostream> #include <iomanip> #include <fstream> #include <familyFinance> using namespace std; struct familyFinance{ int acctNos; float Balance; familyFinance *nextNodeP...
invalid use of incomplete type 'struct familyFinace' how do I fix this? Include the header for familyFinance before using the type. The compiler needs to see how the type is declared before you can use it.
63,042,358
63,062,891
How do I import a class in a .py file from C++ using boost/python?
EDIT : Looks like I've messed up the solution from the second post, but it's still giving me an error after I corrected it. Edit : I tried importing using a full path but it gave me a relative import error. I made another post about it here the directories looks like this: project |__ utilities | |__ foo.py ...
I figured out a workaround: since Python modules are also PyObjects, I can load the module in Python and pass it to C++ as a variable. Here's the code: The C++ file: boost::python::object mod; void set_global(boost::python::object foo_module){ mod = foo_module; // this is for testing boost::python::object t...
63,042,690
63,042,739
any clear explanation of this?
I'm trying to learn C++ vectors.. Here is the code: #include <iostream> #include <vector> using namespace std; int main(){ vector <int> vec; for(int i=0; i<=10; i++){ vec.push_back(i); } for(auto i=vec.begin(); i!=vec.end();i++){ cout<<*i<<" "; } } Can anybody tell m...
for(auto i=vec.begin(); i!=vec.end();i++){ cout<<*i<<" "; } This is just the iterators in C++. begin() function is used to return an iterator pointing to the first element of the vector. Similarly, end() function is used to return an iterator pointing past the last element of the vector. auto just deduces the...
63,043,291
63,043,420
std::stack implementation on different containers what is the actual difference?
when implementing an std::stack there are a few options, for example: // stack with default underlying deque std::stack< int > intDequeStack; // stack with underlying vector std::stack< int, std::vector< int > > intVectorStack; // stack with underlying list std::stack< int, std::list< int > > int...
The stack inherits the performance characteristics of the underlying container. std::vector is a bad choice for a stack that can vary in maximum size. Each push on the stack can potentially require a large reallocation in the vector. Vectors also never shrink unless explicitly requested to, so if the stack grows lar...
63,043,746
63,043,806
ADL and friend functions of templated types
I am attempting to use templates to automatically generate a large number of operators for me. They are very similar to the following code, which does not compile: struct A { int value = 1; }; struct B { int value = 2; }; template<typename ParamA, typename ParamB> struct C { C(int v) : value(v) {} ...
Something like this would work: // Struct definitions for A & B ... struct C { C(int v) : value(v) {} int value; }; template <typename ParamA, typename ParamB> C operator+(const ParamA& a, const ParamB& b) { return C(a.value + b.value); } I remove the friend declaration from inside the C struct b...
63,043,787
63,044,147
Can't initialiaze m_days[month][day]= an object
class App { public: App(); void someFunction(); private: QList<QList<Date *> > m_days; }; void App::someFunction() { Date * a; a = new Date; qDebug() << "A"; m_days[0][0]= a; // [month][day] qDebug() << "B"; Output is: A It crashes right away. It crashes on the line of qDebug "A".I canno...
m_days is not a fixed array, it is a dynamic list. m_days is initially empty, and you are not adding any elements to it, so using its operator[] to access non-existant elements is undefined behavior. Also, you have a syntax error on your declaration of m_days. It is missing an > on the outer template. Try this instea...
63,043,796
63,056,259
glReadPixels from back buffer. Problem with float precision
I'm trying to get color for my color picker, but I get a float value, that differ from value I stored. For example I set 0.5, but I take 0.498039 (this is the real numbers). I don't build any FBO and read color from GL_BACK directly: glReadBuffer(GL_BACK); glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, &color); How can I ...
The precision is limited by the precision of the frambuffer (back buffer). This precision cannot be set individually and is (most likely) limited to 8 bit per channel. Actually the Default framebuffer is generated once, when the OpenGL window and OpenGL Context is generated. Thus it makes no sense to read the read the ...
63,044,002
63,044,065
When I compile my code I get a message what does it mean
When I compile my code, I get the following error messages. What do they mean? Should I be worried? If so, how do I go about fixing this? /tmp/ccK2PEEC.o: In function 'main': HW2Program.cpp:(.text+0x166): undefined reference to 'spitThemOut(familyFinance)' collect2: error: ld returned 1 exit status Here is my code: #...
Your declaration differs from definition. In the declaration argument should be of structure pointer type. void spitThemOut(struct familyFinance * );
63,044,122
63,044,180
Do pointers to const vector member variable elements remain stable after the object is moved?
Consider the following C++ code: class B { ... } class A { public: // Requires vec.size() >= 1 A(std::vector<B> vec) : vec_(vec), b_(&vec_[0]) {} const std::vector<B> vec_; const B* b_; } If I std::move an object of type A, or even copy it, will my pointer b_ to the the B object remain stable and va...
Your code won't compile because you are using Class not class and because std::vector<B> can't be initialized with a data of type B. See std::vector ctors. Now, the constant data can't be moved. If you used something like A a1 = std::move(a) and a were a constant, the copy ctor would be invoked instead of the move ctor...
63,044,219
63,049,807
Inversion Checker using Insertion Sort
I need to output a group of letters that are that are out of order with respect to the number of inversions of each other. For example, the sequence “AACEDGG” has only 1 inversion (E and D) while the sequence “ZWQM” has 6 inversions. I don't actually have to sort it out but I have to output them based on the number of...
Here you access the dna array out-of-bounds: for(j=0;j < n; j++){ for(k=j+1; k <= n; k++){ // when k == n you have undefined behavior if(dna[i][j] > dna[i][k]) it should be: for(j=0;j < n-1; j++){ for(k=j+1; k < n; k++){ if(dna[i][j] > dna[i][k]) An alternative approach using misc. stan...
63,044,295
63,045,345
C++ Unexpected Array Overflow
About 50 minutes ago I started working on a project where I convert a string with roman numerals to an integer. I am having an issue where there is an "array overflow", and I've been troubleshooting for 30 minutes, and am getting kind of frustrated because I can't find a solution. The error that is shown is as follows ...
Your code can be cleaned up a bit: int Roman_To_Decimal(const std::string& roman_number) { static const char roman_letters[] = {'M','D','C','L','X','V','I'}; static const int values[] = {1000, 500, 100, 50, 10, 5, 1}; const unsigned int string_length = roman_number.length(); int decimal_value = 0; ...
63,044,297
63,044,640
In what range does caml_hash_varian return values?
The subchapter "20.3.6 Polymorphic variants" describes how to identify polymorphic variant value in C (*It contains a mistake: should be caml_hash_variant instead of hash_variant) I want to use those hash values as error codes in C++ directly. Something like that archive.mli: ... type t = ... type err = [`File_not_fou...
Immediate values in the usual OCaml implementation have the low bit set, and the variant hash is an immediate value. So if you're looking at variant hash values in C++ you can be sure that the value 0 will never be returned by caml_hash_variant. If you look at the code, the final value is generated either by Val_int() ...
63,044,454
63,056,079
Use ngspice library in WebAssembly
I would need some help with using ngspice as a library in a webassembly (wasm) project. I installed emsdk and newest version of emcc (1.39.20) and downloaded the source of ngspice version 32. To my greatest surprise, I was able to compile ngspice to wasm target by following this guide: emconfigure ./configure --with-n...
I was able to compile the library and my example code after making several changes to the ngspice source. The patch and a guide on how to compile ngspice to wasm, can be found here. (The issue leading to the error shown in my question was with the example code, not returning anything from functions that by signature sh...
63,044,530
63,046,054
C++ friend function reference to global enum from inside namespace
The following friend declaration for FriendlyAccess compiles under C++98 (gcc 4.4.7): typedef enum MyError { SUCCESS = 0, FAILURE = 1 } MyError; MyError FriendlyAccess(); namespace outer { class ClassA { public: friend MyError ::FriendlyAccess(); // enum MyError is not a class or namespace protected: ...
The friend statement takes a function declaration or definition. When removing the ::, you end up declaring another FriendlyAccess function, this time from inside the outer namespace. That works if you put the FriendlyAccess definition inside the workspace too (then your initial declaration in the global namespace is u...
63,044,630
63,063,603
Qt: how to force QTabBar to fill whole layout?
I have a custom QTabWidget which holds a custom QTabBar. I want to expand the area of the QTabBar (the red area) all the way to the right side of the window without enlarging the tabs themselves. I have already tried settings the QTabBar's horizontal size policy to QSizePolicy::Ignored or QSizePolicy::Expanding, but t...
setDocumentMode(true) is what I was looking for.
63,044,894
63,045,201
Is it legal to prefix explicit access to a conversion function template with the 'template' keyword?
Consider the following program: struct A { template <typename T> operator T() { return T{}; } }; int main() { (void) A{}.operator int(); // (A) (void) A{}.template operator int(); // (B) } (A) is accepted by both GCC and Clang, whereas (B) is accepted only by GCC but rejected by Clang with th...
GCC is wrong to accept the program: a conversion function template name (conversion-function-id) is not a template-id This is CWG Defect Report 96, which has, as of GCC 10, has not yet been addressed. The related bug GCC ticket 55588 mentions that it is being implemented for GCC 11. As is covered in the answer to Is i...
63,045,165
63,045,579
Matrix Division in GLM
I'm experimenting with OpenGL currently and I've come upon a situation where I want to find the 4x4 matrix x where x * mat1 = mat2 (column major order, i think. where x * mat1 means apply the transformations in mat1, then x.). Naturally, I thought that the solution might be x = mat2 / mat1, so I tried it with glm. And ...
There is no such thing as matrix division. However, scalar division is simply multiplying by the inverse of the scalar value. As such, one could (and GLM does) define "matrix division" to be the same thing: multiplying by the inverse. So your mat2 / mat1 is really mat2 * glm::inverse(mat1). As for commutativity, let's ...
63,045,448
63,046,913
Unbounded Knapsack and Classical Knapsack Comparison
I have read two distinct problem 0-1 Knapsack Problem and Unbounded Knapsack Problem on the internet. I found that these two problems are both solved by Dynamic Programming but in two different way. If 0-1 Knapsack Problem is solved by using two dimension array, Unbounded Knapsack Problem only utilizes one dimension ar...
Table approach is simpler to explain and debug, that is why algorithm decriptions usually show such way. Note that for 0-1 Knapsack Problem we must exclude possibility to reuse item twice. So at every step of outer loop we update previous best results using current item. But we use only the last row of table (look at i...
63,045,621
63,045,705
while loop fundamentals thirteens.cpp
I don't understand why the output starts from 13 in the following program. I want to understand the change of value in counter and why it outputs 13 first. #include <iostream> using namespace std; int main() { int counter = 0; while (counter < 100) { counter++; if (counter % 13 == 0 ){ ...
There are two operators for integer division... '/' gives you the number of times the right hand operand goes into the left hand operand '%' gives you the remainder when the right hand operand can no longer go into the left hand operand You are using modulus division '%'. Your first time through the loop: right hand i...
63,046,383
63,048,028
Texture for Torus is not applying properly
I'm creating a open GL program with 6 Torus. When I applied the texture it's displaying with one color. Even though it's not in a single color. I'm getting images from array. Other textures (skybox, planet, HUD) are applying properly except Torus textures. I tried to apply light source as well but no luck. Can somebody...
In short: glutSolidTorus() just doesn't emit texture coordinates for the torus but only coordinates and per-vertex normals. The long story: Out of curiosity, I googled a bit, and I believe I found the explanation to OPs observation Other textures (skybox, planet, HUD) are applying properly except Torus textures. Firs...
63,046,397
63,046,598
Why does this usage of C++17 if constexpr fail?
I am trying to use C++17 if constexpr for conditional compilation, but it does not behave the way I expect. For example, with the code below, C++ still compiles the code defined by the macro X2, #include <map> #include <string> #include <iostream> #include <type_traits> #define X1 pp("x") #define X2 pp("x", "x") void...
This is not possible outside the template! From cppreference.com Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive: void f() { if constexpr(false) { int i = 0; int *p = i; // Error even though in discarded statement ...
63,046,619
63,046,932
How to provide default implementations in C++ 20 using concepts?
I am experimenting the possibility of using concepts introduced in C++20 as static interfaces. So far, I am doing well except that I am unable to figure out a way to provide a "default implementation" for a concept. For example, I have a concept named ByteBuffer, and it is stated like this: template <typename T> concep...
Concepts are not base classes. In fact, concepts have no explicit or implicit relation to any of their template arguments. Concepts do precisely one thing: verify whether a particular set of template parameters is appropriate to use when instantiating a particular template. That's all. Concepts contain a sequence of ex...
63,048,059
63,048,764
Swap() in STL algorithm C++
Why swap() in STL algorithm don't take address of a variable and passing variable work just fine but in C++ call by value don't change actual value but call by address changes actual parameter?
std::swap is actually a template function. So if you look at the way std::swap is being called: template< class T > void swap( T& a, T& b ) noexcept It means despite that you seem to be passing the parameter's by value, the template would actually deduce the types to the corresponding address of the parameter. For ins...
63,048,250
63,500,584
boost::filesystem::exists() fails when specifying relative path from a file
Suppose I have the following function defined and used to check whether a required file is available based on the path provided to it. bool check_my_file_exists( const std::wstring& my_root_file ) { const std::wstring file_path = L"..\\..\\require_file.txt"; const std::wstring relative_path_to_required_file = ...
There is nothing wrong with boost::filesystem::exists() function here. According to your example require_file.txt exists in "D:\\my_files\\this_folder\\that_folder\\..\\..\\require_file.txt" where in terms of absolute path it is "D:\\my_files\\require_file.txt", please keep this actual location in mind for further expl...
63,048,903
63,048,937
Dynamic Memory Allocation using malloc
# include<stdio.h> # include<stdlib.h> void fun(int *a) { a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(p); *p = 6; printf("%d\n",*p); return(0); } Why is the above code not valid ? And why does it give a segmentation fault?
Because a is passed by-value itself, then any modification on itself in the function has nothing to do with the argument. You can change it to pass-by-reference as void fun(int *&a) { a = (int*)malloc(sizeof(int)); } BTW: In C++ better to use new (and delete), or don't use raw pointers from the beginning.
63,049,046
63,050,001
Order of operations for bitwise operators (a & (a=1) strange behavior)?
I was messing around with some c++ code after learning that you cannot increment booleans in the standard. I thought incrementing booleans would be useful because I like compacting functions if I can and unsigned char b = 0; //type doesn't really matter assuming no overflow while (...) { if (b++) //do something ...
There is no "strange behavior" here. The & operator, in your case is a bitwise arithmetic operator. These operator are commutative, so both operand must be evaluated before computing the resulting value. As mentioned earlier, this is considered as undefined behavior, as the standard does not prevent computing + loading...
63,049,304
63,053,860
How to correctly catch the Rcpp exceptions?
I have created a function shown below: #include <Rcpp.h> //[[Rcpp::export]] void fun(SEXP num = R_NilValue){ if(!Rf_isNull(num)){ try{ int NUM = Rcpp::as<int>(num); }catch(...){ Rcpp::stop("Exception occured!"); } } } This fu...
Your example is not complete as you did not tell us how you build and called the function. "In general" you do not need to anything as R does it for you. Simplest example: R> cppFunction("int doubleMe(int x) { return x + x; }") R> doubleMe(21) [1] 42 R> doubleMe("this won't work") Error in doubleMe("this won't work") ...
63,049,714
63,049,842
++i and i+1 passed to function giving different results in c++
#include <stdio.h> int noOfTriplet(int arr[], int n, int product, int count, int m){ if(count == 3 && product == m) return 1; else if(count == 3 || n==0) return 0; // using count+1 here gives answer 3 while passing ++count gives answer 1 why return noOfTriplet(arr, n-1, product*arr[n-1], count + 1,...
In return noOfTriplet(arr, n-1, product*arr[n-1], count + 1, m) + noOfTriplet(arr, n-1, product, count, m); you are using count twice. When you are changing to return noOfTriplet(arr, n-1, product*arr[n-1], ++count, m) + noOfTriplet(arr, n-1, product, count, m); then the compiler might evaluate noOfTriplet(arr, n-1, ...
63,050,033
63,102,769
Pointer Events WxWidgets WebView
I'm currently integrating a web based map engine (OpenLayers) with wxWidgets webView, the map currently expects pointer events but the the webView only triggers mouse events, I wanted to ask if the wxWebView supports pointer events and if yes how to enable them. I also tried using Pointer Events Polyfill but the webVie...
Solve the problem by using the latest wxWidgets release (3.1.4) that comes with the wxWebView with the Edge Chromium backend
63,050,157
63,050,455
Sequence containers - why all containers do not all methods
I was learning C++ Sequence containers by referring below information - https://en.cppreference.com/w/cpp/container [Member function table - functions present in C++03 ,- functions present since C++11, - functions present since C++17, - functions present since C++20] available at the end of the page. What I am unable t...
forward_list does not supports size() std::forward_list is designed for maximum space efficiency, so the size is not kept as an extra member (it is in std::list). To determine the size one would have to walk the list, O(N). vectors does not support emplace_front() To insert at the front, the std::vector would first...
63,050,228
63,050,566
Move constructor with protection for non-default-constructible class
Let's imagine I have a non-default-constructible class like so : class A { public: int k; A() = delete; A(int _k): k{_k}{}; A(A const& o) = delete; A& operator=(A const& o) = delete; A(A&& o) = default; A& operator=(A&& o) = default; }; Then, I have ...
You could do the locking in a helper function: class C { A a; std::mutex m; // using a standard mutex instead A A_mover(C&& other) { std::lock_guard<std::mutex> lock(other.m); return std::move(other.a); // move into a temporary while locked } public: C() = delete; C(int _k)...
63,050,377
63,053,361
Converting std::span with dynamic extent to std::span with static extent
I used to work with gsl::span from the Guidelines Support Library for some time. With gsl::span, is was possible to define a function taking a static extent and calling it with a gsl::span of dynamic extent, e.g. void f(gsl::span<int, 5> s) { } ... std::vector<int> v(100); f(gsl::make_span(v).subspan(42, 5)); // Wor...
Is there any reason for this difference? P1976 goes through this at length. Fixed-extent spans have explicit constructors on purpose to try to alleviate undefined behavior, so std::span<int> (the type of std::span(v).subspan(42, 5)) is not convertible to std::span<int, 5>. Is there any recommended way to convert a s...
63,050,845
63,051,232
Using set in c++ standard template library (STL)
Sets are the collection. There is a function in set isinsert(). It's return type : it returns the iterator pointing to the inserted element in the collection. I write a code and its working : #include<bits/stdc++.h> using namespace std; int main(){ set<int> s; s.insert (1); s.insert (4); s.insert (2); s.insert (5)...
When you use the syntax: auto itr = s.insert(5); The return type of s.insert() with the parameter 5 gives a type of: std::pair<std::set<int>::iterator, bool> But there's no such known overloaded conversion from that type to std::set<int>::iterator in the syntax: itr = s.insert(itr, 4); // error! _______________^^^___...
63,051,100
63,055,945
C++ Atomic compare_exchange_weak
Something happened when I used this feature that Was hard for me to understand Code: #include<iostream> #include<atomic> int main() { std::atomic_size_t example; size_t expect = 1000; example.store(100, std::memory_order_release); //Now example.load() is 100; auto result = example.compare_exchange_w...
It is called an exchange for a reason. Calling example.compare_exchange_weak(expected, value); roughly corresponds to the following piece of code done atomically: if (expected==example){ example = value; return true; } else { expected = example; return false; } In your first call, the else branch is ta...
63,051,254
63,072,092
Ray-triangle intersection. It work with two directions
I don't know why, but ray-triangle intersection algorithm (Möller-Trumbore and Watertight) works with 2 directions. from origin to end - how it must work from end to origin - the problem white cross - an unnecessary intersection screenshot I tried to use 3 component vectors, so I have removed all W values from code. Ra...
Unit distance on ray of intercept The last value calculated T is the unit distance on the ray from the ray origin. Where T == 0.0f is at the origin, T == 1.0f is at the ray end, T > 1.0f are past the ray end and T < 0.0f are before the ray origin. Thus you need to check T to make sure that the intercept is on the corr...
63,051,282
63,052,168
CMake: What do CMake build types (DCMAKE_BUILD_TYPE) do?
I am using CMake (within CLion IDE but that should not matter for this discussion). Up until now I have been using things like set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2") or set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2") to set compiler options for GCC. I assume CMake passes these on directly to the compiler. However, CMa...
What does -DCMAKE_BUILD_TYPE="Release" (and other release types) do (as exactly as one can tell not knowing the system where the build happens)? It enables certain compiler options defined in the core CMake modules, which are specific to the target system. The documentation doesn't exactly explain what each of the ...
63,051,440
63,052,308
How to test a command line options parser using GTest
I am developing a command line options processor for my app. I have decided to use GTest to test it. It's implementation has been shown below in brief: int main(int argv, char **argv) { if (!ProcessOptions(argc, argv) { return 1; } // Some more code here return 0; } int ProcessOptions...
Have you considered a value-parameterized test? They sound perfect for your situation: Value-parameterized tests allow you to test your code with different parameters without writing multiple copies of the same test. This is useful in a number of situations, for example: You have a piece of code whose behavior is aff...
63,051,615
63,051,791
class const attribute initialization
I have a class with a member attribute which I only set once at construction and is read-only thereafter. This attribute is not identical across all instances of this class. I would therefore like to define this attribute as const T. I cannot assign a value to the attribute within the constructor's body but may only in...
You can probably make the initialisation neater by hiving it off into a function. It sounds like the logic is probably too long to be tidily written inside a lambda, so you could just use a static member function (or free function) for this task. Foo::Foo(Bar args) : constMember(makeMyConstMember(args)) {} Failing ...
63,052,177
63,052,210
What is wrong with this use of std::unique_ptr that gives invalid pointer error?
Here is the code: https://onlinegdb.com/BksirkDxw I copy the same code here: #include <iostream> #include <memory> using namespace std; class cA{ public: cA(){} ~cA(){} }; int main() { std::unique_ptr<cA> qq(new cA[200]); cout << "OK" << endl; return 0; } Result: OK ...
Your code has undefined behavior. You're specifying the std::unique_ptr as containing single object, but you're initializing it with an array. You should specify the template argument as array; otherwise std::unique_ptr would try to call delete but not delete[] to destroy the object and deallocate the memory. std::uniq...
63,052,234
63,054,186
How to count the occurence of a word in multiple texts?
I have a Binary tree that stores all the words with their occurence in a text. Word as key and number of occurence as value If i have multiple texts, do I create multiple trees ? Also, I want to count the idf (inverse document frequency - how many times that word appears in all the texts). How can I achieve this ?
If I understood your problem correctly, you will need a tree for each file to be able to know how many occurences of a word you have in each one. Then, for the second part i can't understand if you need the total number of occurences of a word or the number of files that contain that word. In each case you just need to...
63,052,236
63,055,219
Operator overloading on an enum nested in a class
The problem Given the following piece of code : template <typename T> struct dummy { enum enumenum { a = 1, b = 2, c = 4 }; }; int main() { // I want this line to expands as : // dummy<double>::enumenum a = operator~(dummy<double>::a); auto a = ~dummy<double>::a; } How do you overload operators on enu...
This compiles, but does not link! Compile but doesn't link because you declare a non-template operator (it's inside a template struct but isn't a template function) friend enumenum operator~(enumenum a); and you define a template one template <typename T> typename dummy<T>::enumenum operator~(typename dummy<T>::enu...
63,052,260
63,052,495
getting junk value while display object
i am trying to implement a class with copy and swap idiom but while printing the object i am getting junk value. i am using copy-ctor to make use of copy before i make use of assignment. following is code snippet: class EmpTasks { private: size_t m_size; char* name; public: EmpTasks(char* name, int si...
this has occurred because you haven't initialized your var name, hence you can use something like what follows in your ctor EmpTasks(char* name, int size = 0) : m_size(size), name( m_size ? new char[m_size] : nullptr ){ for(size_t i{}; i< m_size; ++i) this -> name[i] = name[i]; } Another ...
63,052,523
63,134,322
Missing layer in TFLite model after conversion
So I trained a model using tensorflow and python and now I'm trying to use it in a C++ program. I use this code to convert my model to tflite (I don't have any error during the conversion) : model.load_weights('training_weights.h5', by_name=True) model.save('saved_model/model') converter = tf.lite.TFLiteConverter.from...
I think I found the reason why it doesn't work. As you can see in the last layer I use the operator : K.squeeze(x, axis=2) which seems to not be supported yet with a specified axis ("tf.squeeze — As long as axis is not provided.", last-accessed:28 July 2020, link). That is why I don't have the same output in C++ as in ...
63,053,240
63,053,484
Adding objects with defined operator doesn't work as I expect
The output is equal 20. Why the return value isn't 30? class Myclass { public: int result; Myclass() { result = 10; } Myclass operator+ (Myclass& obj) { Myclass tempObj; tempObj.result += obj.result; return tempObj; } }; int main() { Myclass obj1, obj2, obj3; cout << (...
Within the operator Myclass operator+ (Myclass& obj) { Myclass tempObj; tempObj.result += obj.result; return tempObj; } there is created local object tempObj the data member result of which is always initialized by 10. So though the temporary object created by the sub-expression obj1 + obj2 has the data m...
63,053,429
63,053,500
How to assign multiple values to an array?
I can declare and initialize an array like this: int dest_linesize[4] = { 4 , 0 , 0 , 0 }; I can always assign values to the individual members of the array by: dest_linesize[0] = 5; But can I assign multiple values with something like this? dest_linesize = { 4 , 3 , 1 , 0 };
With C-style array? No, they are not reassignable. With C++ std::array? Sure #include <array> int main() { std::array<int, 4> dest_linesize = {4 , 0 , 0 , 0 }; dest_linesize[0] = 5; for(int n:dest_linesize) { std::cout << n << " "; } std::cout << "\n"; dest_linesize = { 4 , 3 , 1 , 0 }...
63,053,432
63,053,953
Why am I getting Segmentation fault in my code?
Node* findMax(Node* root){ Node* m=root; while(m!=NULL && m->right!=NULL){ m=m->right; } return m; } // Returns the root of the modified BST after deleting the node with value X Node *deleteNode(Node *root, int X) { Node *temp; if(!root)re...
In this part if(root->left==NULL){ root=root->right; } if(root->right==NULL){ root=root->left; } When root->left == NULL is true, root=root->right; is executed. Thanks to condition of previous if statemen...
63,053,566
63,053,787
Why do some people define objects as pointers?
I'm currently learning C++ and I can't wrap my head around why one would define an object of a class as a pointer (i.e. Car *c = new Car; as opposed to Car c;) for no apparent reason? Take for example: #include <iostream> class Car { public: void accelerate() { std::cout << "Accelerating!.\n"; } }; int main() {...
why one would define an object of a class as a pointer One shouldn't. Pointers are generally to be avoided as much as possible. However, they are necessary when you are doing polymorphism. In that case, use the smart pointers shared_ptr, unique_ptr instead of a raw pointer. The following is a bad example of using poi...
63,053,588
63,053,734
QStringListModel * as a parameter of a signal giving me the error "...attempting to reference deleted function"?
I wrote this small test programm so I understand QT's Signals & Slots, aswell as Multithreading, better. mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QString> #include <QStringListModel> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow...
Your heremodel signal is declared to return a QStringListModel by value... QStringListModel heremodel(QStringListModel*); Hence the error as QObject is non-copyable. Change the signal signature to... void heremodel(QStringListModel*);
63,053,711
63,629,025
How to pass arguments to ASTFrontendAction
Is there a way I can pass constructor arguments to classes inheriting from clang::ASTFrontendAction in programs based on libtooling? All examples I have found online look something like this: int main() { ClangTool Tool(...); return Tool.run(newFrontendActionFactory<SomeFrontendAction>().get()); } But what if...
I found this answer while looking for an answer to this question. You should create your own version of newFrontEndActionFactory. The original code for newFrontEndActionFactory is: template <typename T> std::unique_ptr<FrontendActionFactory> newFrontendActionFactory() { class SimpleFrontendActionFactory : public Fron...
63,054,060
63,055,181
How to make sure only 1 thread is running? C++
I have an app that plays a game for me, and it required me to make a thread which constantly scans my health and moves the character to a spot, if I go under that health. When the game is finished, it starts a new one, and then it creates a new thread which scans for health. Total of 2, of the same thread. How can I ma...
You could use named mutex on Windows: CreateMutexA(0, 0, "unique_mutext_name"); if(GetLastError() == ERROR_ALREADY_EXISTS) // already exist? return -1; // quit // program code
63,054,071
63,055,480
How to measure elapsed time without being affected by changes in system time
I want to measure elapsed time in seconds. With std::chrono::steady_clock I do it. However it suffers from system time changes. Wasn't steady_clock supposed to not being affected by changes in system time? How can I do that? Here is the code: #include <iostream> #include <chrono> #include <time.h> std::chrono::steady_...
You can file a bug with your vendor. From the standard: Objects of class steady_­clock represent clocks for which values of time_­point never decrease as physical time advances and for which values of time_­point advance at a steady rate relative to real time. That is, the clock may not be adjusted. If you can find a...
63,054,102
63,054,273
Is it possible to use std::char_traits<char> in constant expressions before GCC 8?
According to the GCC 8 Release Note, it is now possible to use std::char_traits<char> and std::char_traits<wchar_t> in constant expressions: Improved experimental support for C++17, including the following features: std::char_traits and std::char_traits<wchar_t> are usable in constant expressions. What I underst...
This improvement was backported from mainline. It is available in the gcc 7 line from 7.3 onwards.
63,054,280
63,054,770
Inheriting from libuv handles
The libuv handles have a void* data field to carry around any context information (pretty standard pattern for callbacks in C-land). However, since I'm working in C++-land, I would like to use inheritance to directly store context in the handle. The main advantage is in storing multiple context items which IIUC require...
If you are the one allocating the handles yourself and then passing them to libuv, there is nothing stopping you from inheriting them. You are allowed to allocate them however you want. You could make them a member of your class, but you could also make them a base of your class. The compiler isn't allowed to change th...
63,054,808
63,054,894
To count the article in the sentence?In this program last if statement not working "a" and "an"
//header #include <bits/stdc++.h> using namespace std; int main(int argc, char** argv) { string s,s1=" "; int i,j,flag=0,flag1=0,count=0; getline(cin,s); for(i=0;i<s.length();i++){ if(s[i]==' '){ flag=i; for(j=flag1;j<flag;j++){ s1=s1+s[j]; ...
Your s1 is initialized to a whitespace character and it is preventing it from matching with the strings in the if statement, none of which don't have whitespace characters. Remove the extra two whitespaces and initialize s1 to empty strings.
63,054,971
63,055,248
Which compilers support arrays with a size fixed at runtime and which compilers don't?
I've been always using arrays whose size are asked in the input by the user like: int main(){ int n; cin>>n; int arr[n]; } I never faced any problem with this method but now I've read a lot of articles saying that this syntax is not supported by C++ as C++ needs array size at compile time or arrays must b...
I clicked through most of the compilers available at https://godbolt.org/ and it seems that only the Microsoft Visual Studio compiler rejects it. GCC and Clang on several platforms are fine with this code. Note that it is only an additional support, both compiler can decide to stop accepting the code, as it is non stan...
63,055,147
63,055,311
Emulating mkdir -p with the C++ standard library
This question: mkdir c++ function tells us how to create a directory programmatically in C++, introducing us to std::filesystem::create - which acts similarly to the mkdir command in Unix shells. However, this does not seem to allow for recursively creating the entire path: mkdir -p /path/to/nonexisting/dir/and/then/so...
What you are looking for is std::filesystem::create_directories() for which you can find more detailed information in the reference.
63,055,163
63,082,180
How to append multiple elements to a repeatedField in Protocol buffers?
Given a message message My_msg{ repeated double my_arr = 1; } How can one append elements into the field? There is an answer for copying/moving already allocated full arrays by overwriting the current contents, but what if there is already some data in the filed, which needs to be kept as it is? Is using the below c...
I don't think your sample code would build. My_msg::mutable_my_arr() returns a pointer to a RepeatedField (not the first element of an array). Trying to index it would segfault at best. In terms or performance, if you have your data in an std::vector you will always need to copy - so you could just try to make that fas...
63,055,565
63,056,778
C++ virtual "file" stream
I have an object that writes binary data to a file. Sometimes it needs to seek to the beginning and re-write some data, to update a header of instance. I now need to avoid file i/o, so I am looking for something equivalent to a "virtual" file stream that I could seek around with. Right now I am using a vector, but I sw...
You could use std::stringstream: NOTE: Read and write position seekg and seekp is independent for std:stringstream, but are interchangeable for file streams. In other words, there is only one pointer maintained for files. #include <sstream> #include <iostream> struct Header { int flag1; char flag2; }; // Also...
63,055,685
63,055,765
What is the meaning of this syntax in the method declaration
I encountered this method and I'm not sure how to interpret it: const char(*get_foo(int par))[38] { return foo; } the par parameter is not used in the function... And foo is defined as: static const char bar[] = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static const char(*foo)[38] = &bar; get_foo, foo, and bar are...
This is a function that takes an int and returns a pointer-to-array containing 38 const char types. It's not clear why the par parameter is not used, that would be a question for the original author. A function like this should be read: const char(*get_foo(int par))[38] ^~~~~~~~~~~~~~~~ (1) ^~~~~~~~~~~~ ...
63,055,964
63,105,767
Building GCC as an ARM cross compiler with multilib support
I want to build GCC from source as a cross compiler for ARM bare-metal targets. Specifically, I need support for the architectures armv4t and armv5te with softfp for both of them since they lack a proper FPU. The (relevant) flags I used are --with-cpu=arm946e-s --with-mode=arm --with-float=soft --enable-interwork --ena...
TL-DR; There is no need. Use a wrapper and link to the desired standard libraries. For soft and hard float, both the gcc libraries and generated code are effected. For a system with armv4 and armv5, the same compiler will always be able to generate the same code. Moreover, the generated objects are the same ABI. Ie...
63,056,272
63,075,368
calculating the Gamma function for negative real values (C++, Boost)
The following infinite serious require the calculation of factorial for non-integer, negative, real numbers: (it is a way to calculate the circumference of an ellipse, a and b are the semi-major and semi minor axis and h is defined as: h = (a-b)^2/(a+b)^2) The factorial function can be extended to negative values via ...
I understand what's going wrong. The boost::math::factorial function takes an unsigned integer by definition: template <class T> inline T factorial(unsigned i) { return factorial<T>(i, policies::policy<>()); } This means that if you call it with a double, it will get implicitly converted to unsigned. That's not wha...
63,056,301
63,077,129
How to solve " a missing vtable usually means the first non-inline virtual member function has no definition."
I was trying to see how virtual functions are compiled and it seem I cannot compile a trivial example to a dylib on macOS. I've been through countless permutations of this code and SO answers but I cannot get this trivial example compile (or rather link) with: clang -dynamiclib -o test.dylib test.cc here is the code: ...
The NOTE is a red herring, I'm afraid. vtable for __cxxabiv1::__class_type_info is a symbol in the C++ standard library, not in your code (std::type_info is a polymorphic class), so this error actually means that you need to link against the C++ standard library. The simplest way to do this is to change clang to clang+...
63,056,374
63,056,447
Overwriting the class object using istream overloading
Here I'm trying to overwrite the inventory objects, but when I run the second std::cout it print the old value again, I want it to write the inputted value. #include <iostream> #include <string> class inventory { private: std::string item; int onhand; double cost; public: inventory(std::string i, int o...
The problem you're facing is, that you pass your inventory obj by value What you want is passing it as reference like so: friend std::istream& operator>>(std::istream& stream, inventory &entity)
63,056,658
63,056,859
Add vector with CUDA C++ : don't get the expected result
I recently started CUDA programming. I followed tutorials and guides about it, and made a first program copied from the original example ( here pg. 25 ), which basically use the GPU to add two vectors. I can compile it but the result I get isn't the one I expected. Here is my code : #include <iostream> #include <random...
As said in the comment, the problem was on the cudeMemcpy(d_a, &a, size, cudaMemcpyHostToDevice) The ampersand was not supposed to be here.
63,057,054
63,057,356
Find Rcpp function in a R package
I want to print the C code of the bh function in the R package frailtysurv. So I typed: > frailtySurv:::bh function (d_, R_star, K_, Y_, N_, N_dot, beta, theta, frailty, weights, abstol, reltol, maxit) { .Call("_frailtySurv_bh", PACKAGE = "frailtySurv", d_, R_star, K_, Y_, N_, N_dot, beta, theta, fra...
The _frailtySurv_bh function is defined in the RcppExports.cpp file, which is defined here, and looks like this: RcppExport SEXP _frailtySurv_bh(SEXP d_SEXP, SEXP R_starSEXP, SEXP K_SEXP, SEXP Y_SEXP, SEXP N_SEXP, SEXP N_dotSEXP, SEXP betaSEXP, SEXP thetaSEXP, SEXP frailtySEXP, SEXP weightsSEXP, SEXP abstolSEXP, SEXP r...
63,057,156
63,057,345
Language supported in Visual studio for C++ __cplusplus is showing as C++98
I'm trying to run C++11 in my project. I add the compiler flag /std:c++11 to the compiler, but when I check the version and print it out, it shows as C++98. This is in Visual Studio 2019. This is what I'm using to print the language, and it shows as C++98: if (__cplusplus == 201703L) std::cout << "C++17\n"; else if (__...
/Zc:__cplusplus is required to turn on proper versioning for the __cplusplus macro. Note, however, that The compiler does not support standards switches for C++98, C++03, or C++11. So it will only work with /std:c++14 and later. As was mentioned by Ted Lyngmo, there's also the _MSVC_LANG marco (this does not require th...
63,057,910
63,058,126
How can I get a Unicode character from a number?
I'm new to C++, so sorry if this is obvious. How can I get a character from a number? I have the following code: for (int i = 0; i < 500; i++) { cout << i; } It's supposed to get the first 500 characters in the Unicode dictionary. I know that in javascript, it is String.fromCodePoint(i). What's the C++ equivalent?...
Use wchar_t instead for (wchar_t i = 0; i < 500; i++) { wcout << i; } You can also use char16_t and char32_t if you're using C++11 or newer However you still need a capable terminal and also need to set the correct codepage to get the expected output. On Linux it's quite straight forward but if you're using (an ol...
63,057,956
63,058,257
How do I fix this undeclared identifier? (C++)
I'm writing a VST in C++ currently, and I ran into an issue. I've been surfing the web and StackOverflow for a while now and I'm stuck. Two files are giving me the issue, SynthesizerTwo.h and SynthesizerTwo.cpp. The error I get is: 'kNumPrograms': undeclared identifier [in SynthesizerTwo.h] I have a const int called ...
This is what your SynthesizerTwo.cpp file looks like after the pre-processor has included the files, with most cut out: class SynthesizerTwo : public IPlug { ... double mFrequency; void SynthesizerTwo::CreatePresets() { MakeDefaultPreset((char*)"-", kNumPrograms); //This is what gives me the error } ...
63,057,988
63,058,022
c++ printing out incorrect binary after shifting << 32 times
The code below should be printing out 32 0s, then 011, then 0s till the 64 bit from right to left #include <iostream> #include <bitset> #include <stdint.h> using namespace std; int main() { int a = 0b011; long long b = (a << 32); std::cout << bitset<64>(b).to_string(); } but its giving this: main.cpp:8:20: wa...
It seems the shifting is done in 32-bit because both of a and 32 are 32-bit long. Cast to long long before shifting to fix. long long b = ((long long)a << 32);