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
61,645,850
61,653,161
How do I create a colormap in VTK?
I created a simple unstructured square in VTK: x = [0,10,0,10] y = [0, 0, 10, 10] z = [0,0,0,0] data = np.asarray([x,y,z]).T for i in range(0, len(x)): points.InsertPoint(i, data[i]) quad = [2,3,1,0] ugrid.InsertNextCell(vtk.VTK_QUAD, 4, quad) ugrid.SetPoints(points) Say I wanted to create a colormap of the temper...
You should add your data array and set it as the scalars (= default array to use in VTK, particularly for coloring) temperature = vtk.vtkIntArray() temperature.SetName("Temp") temp = [00,20,40,60] for t in temp: temperature.InsertNextValue(t) ugrid.GetPointData().SetScalars(temperature) Then in the rendering part...
61,646,142
61,648,462
C++ Boost::thread invoking a c function - Facing compilation error
Have to invoke a C static function as part of my boost worker thread function.The C static function works as part of other C++ code however, it fails to compile while being part of a worker thread function. Following is the list of headers included in my C++ header file. #include <boost/bind.hpp> #include <boost/threa...
During the discussion in the post comments we found that C2146 error occurred because BSTR typedef definition is required in your C header. Including of Windows.h before the C header leads to conflict due to double include of WinSock.h by both Windows.h and boost/asio.hpp. However BSTR is the only thing your library ne...
61,646,166
61,646,279
How to resolve "fpclassify': ambiguous call to overloaded function
I am as new to C++ as someone can be. I have been given the task of installing a simulation, but I keep running into error codes. I was able to resolve most of them, but there is one I am not sure how to tackle. The error code is C2668, and its description is: "fpclassify': ambiguous call to overloaded function Proje...
You probably fed std::fpclassify an integer somehow. Visual Studio has an issue with the integer overloads for the <cmath> functions that manifests itself like in your case instead of casting the integer to a double in accordance with: c.math.syn#2.2: […] if any argument of arithmetic type corresponding to a double pa...
61,646,282
61,646,542
No matching function call on constuctor
I am new to C++ and try to publish sensor data from an ARM chipset over UART with ROSserial_stm32 framework. Original sources came from a demonstration code written in C which gather data and send it over UART in a "string format". My aim is to replace those string sendings to ROS sensor_msgs frame format. To achieve i...
Issue 1 When you don't initialize member variables (and base classes) using initializer list in a constructor, they are default initialized. I.e. ROSserial::ROSserial(void) { this->lps22hb_air_temperature_t_ = new sensor_msgs::Temperature(); } is equivalent to ROSserial::ROSserial(void) : nh(), ...
61,646,362
61,646,597
Retrieving index of vector using std::upper_bound, index out of bounds
I am attempting to retrieve a vector's index based on it's value using std::upper_bound. For some reason though, the following code sets tmpKey equal to 2 vs my expected value of 1. Does anything stick out as being horribly wrong? int main() { float time = 30.0000000; std::vector<float> positionKeyTimes = { 0.0...
std::upper_bound Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found. There's no element greater than 30 in your vector, so the end iterator is returned. To get your expected value you could use std::lower_bound instead, which R...
61,646,445
61,646,903
Get io_context reference from a socket in Boost 1.73+ Asio
How can I get boost::asio::io_context reference from a socket? Previously there were socket::get_io_service and then socket::get_io_context member functions, however now they both are deprecated. I've found the only way to do this in Boost 1.73+: boost::asio::ip::tcp::socket socket(...); // ... boost::asio::io_context&...
You would probably want to get the executor, which might be something other than the io_context. There's a get_executor() call to do it directly: boost::asio::io_context io; boost::asio::ip::tcp::socket s(io); auto ex = s.get_executor(); The executor will allow you to do most things you were probably using the io_cont...
61,646,510
61,647,646
How does the CPU "cast" a floating point x87 (i think) value?
I just wanted to know how the CPU "Cast" a floating point number. I mean, i suppouse that when when we use a "float" or "double" in C/C++ the compiler is using the x87 unit, or am i wrong? (i couldn't find the answer) So, if this is the case and the floating point numbers are not emulated how does the compiler cast it?...
I mean, i suppouse that when when we use a "float" or "double" in C/C++ the compiler is using the x87 unit, or am i wrong? On modern Intel processors, the compiler is likely to use the SSE/AVX registers. The FPU is often not in regular use. I just wanted to know how the CPU "Cast" a floating point number. Convertin...
61,646,576
61,647,430
Create a human-readable timestamp and store in string in C++
I would like to create filenames with timestamps in them based on when the program was run, i.e. logfile_2020-04-21_18:11:10.txt logfile_2020-04-22_18:13:43.txt ... I can get the timestamp (I think) with std::chrono::steady_clock::time_point timestamp = std::chrono::steady_clock::now(); but I don't know how to conver...
What you're asking for is not defined. Your timestamp is coming from a "steady" clock which guarantees monotonic time but is not related to wall clock time and thus cannot be converted into a human-readable timestamp (think about what happens if you adjust your system time -1 min, a monotonic clock can never be adjuste...
61,646,618
61,665,877
can't use filesystem in g++ / msys2 on windows
So, I am writing C++ code on my windows 10 machine. I generally use cmake (3.17.2) and minGW (g++ 9.3.0) I found out about "filesystem" and decided to use it, but kept getting the error that it was undefined. Apparently "filesystem" wasn't implemented on minGW until version 9 and at the time, I was using version 8. So,...
File system is a general term in computing which can mean different things in different contexts. The MSYS2 package you found named filesystem is just a basic package for MSYS2 that installs a bunch of files and folders inside MSYS2. Like any other MSYS2 package, you can investigate filesystem to see exactly what it i...
61,646,834
61,660,546
Cross compiling libtorrent for raspberry pi 3 model B
I've been trying to cross compile jlibtorrent for the raspberry pi which uses boost build for compiling. I am using the officially provided cross compiler with the following config.jam: import os ; using gcc : arm : arm-linux-gnueabihf-g++ : <cxxflags>-fPIC <cxxflags>-std=c++14 <cxxflags>-fno-strict-aliasi...
Thanks to @Arvid I managed to compile it using the current stable branch for libtorrent (RC_1_2) and the following jam file, which you can find here. import os ; using gcc : arm : arm-linux-gnueabihf-g++ : <cxxflags>-fPIC <cxxflags>-std=c++11 <cxxflags>-fno-strict-aliasing <cxxflags>-fvisibility=hidden...
61,646,912
63,832,669
Using SOIL.lib with GCC - Error adding symbols: File format not recognised
I've been recently trying to transfer my Visual Studio OpenGL project to VS Code, using GCC via mingw-x64 on Windows 10. I've been making steady progress working this all out as I am fairly new to c++ programming, and I've been running into an error that I can't solve. When building with the following command: C:\Lib\m...
*.lib: error adding symbols: File format not recognized. is the issue which is caused by your linker. The reason behind this is the library is belongs to other architecture rather than you are intended it to be. That means you are using mingw64\bin\g++.exe compiler(mingw64 architecture) and the library SOIL.lib is buil...
61,647,450
61,647,579
Finding multiples of five in a vector using a function
Write a function called findMultipleOfFives that takes a vector of integers as parameter (passed as constant reference) . Your function should return true if every number in the vector is a multiple of the number 5. The function should return false otherwise. For example, for a given vector variable, vector all_values...
First, you are trying to modify the vector while you are looping through it. You don't need to do that, nor do the instructions ask you to do that. Second, the instructions ask you to return a boolean, not a string. Third, your function is not looping through the whole vector. std::vector has a size() member to get t...
61,647,767
61,647,878
Why is c++ prematurely destroying my string variable?
This error is one of the most mysterious I've gotten in probably years. I've been trying things back and forth for hours now and can't understand it. In the code below, I am trying to dynamically decide which derived class to instantiate. I use the function parameter particle_type in order to determine that. But since ...
You are setting p to point at temporary objects that are destroyed immediately after the assignment, thus leaving p dangling. You need to use new instead: Particle* p; if (particle_type == "Featherr") { //This is never called because of the extra "r" I put, so ignore this block p = new FeatherParticle(particle_nam...
61,647,817
61,648,185
which amongst these two cases would result in memory leak
using delete: int** a=new int*; **a=5; delete a; using delete[]: int** a=new int*; **a=5; delete[] a; To find out, I tried doing this- int** a=new int*; **a=5; int* b=new int; b=*(a); delete[] a; cout<<"*b: "<<*b; getting an output- 5 but I suspect that integer stored in b might have been deleted but not changed (no...
int** a=new int*; **a=5; delete a; This is wrong, because you allocate an int* and don't point it to an int afterwards. Accessing the int* itself via *a is OK, but accessing an int via the extra * is not OK. This is Undefined Behavior. You need to add that additional int, eg: int** a=new int*; *a = new int; // <-...
61,647,873
61,648,114
shrinking namespace to base
Is there a way to "shrink a namespace"? e.g. std::chrono::milliseconds to std::milliseconds by the namespace alone? i.e. namespace std = std::chrono (please disregard the fact that this is modifying std. this is just an example I think everyone can understand)
Add your own alias to std::chrono, external to std: namespace chrono = std::chrono; And then use chrono::milliseconds. It's possible to collapse layers of namespaces by adding an internal namespace alias. The standard library does this: namespace std { namespace ranges::views { /* views stuff */ } namespace ...
61,647,984
61,653,361
Displaying RTSP stream with OpenCV and gstreamer
I have purchased an IP camera which I am trying to connect to using RTSP. The RTSP connection URL is rtsp://admin:@192.168.0.27/channel=1&stream=0.554. I am using OpenCV to open and display the stream: #include <opencv2/opencv.hpp> int main() { cv::VideoCapture cap; if (!cap.open("rtsp://admin:@192.168.0.27/chan...
This may be due to packet loss of the network transmission. You can give it a try to modify the URL to use the rtspt:// protocol. This will try to establish a TCP transmission which should prevent packet loss on your receiving side.
61,648,274
61,648,512
Hiding C++ symbols with -fvisibility=hidden
I have a C++ library with a C API, and I have set the -fvisibility=hidden compiler flag, and then I have set __attribute__ ((visibility ("default"))) on C API methods. However, I still see visible C++ symbols. When I create a debian package for my library, I get the following symbols file Why are these symbols still v...
You should run your symbols file through c++filt which converts the "mangled" symbol names to what is readable [in the c++ sense]. If you do, you'll find that two thirds of the symbols are std::whatever, and not your symbols. So, they are being pulled in because of the STL. You may not be able to control them. The othe...
61,648,277
61,648,399
c++ pointers used as pseudo-arrays. Assigning number to multiple consecutive positions of the memory without array
It's more of a conversation topic that a question. Look at the following code for calculating the nth Fibonacci number and print out all of them up to the nth(namespace std pressumed and the following is in the main): int n=20; int *a=new int; //notice NO size declaration a[0]=1; a[1]=1; for(int i=2; i<n;i++){ a[i]...
So should it work? No. Accessing any index other than a[0] produces undefined behavior, since it's outside the allocated memory. Does it work for you? It might appear to work in some cases. When you have undefined behavior, anything can happen; there's no requirement that the error be detected (see Why don't I get...
61,648,454
61,648,832
"Debug Assertion Failed" when MFC button control EnableWindow method is used in class constructor
I am using Visual Studio 2019 and building a C++ desktop application. I have a dialog class inherited from CDialogEx. In this class I have a few buttons, i.e. CButton as members. When I use the EnableWindow method in the class constructor, it reports: Debug Assertion Failed! Program C:\WINDOWS\SYSTEM32\mfc140ud.dll F...
There is a difference between a C++ class and the actual creation of the dialog window and its controls. The constructor is for class related items, not window related items. For example, if you want to initialize member variables, then the constructor would be the place for it. But at construction, no dialog windo...
61,648,514
61,648,564
program crash in accessing struct elements
struct a has int b, and pointer to struct as its elements. And program crashes without printing results. struct a{ int b{5}; a* next=new a; a(){ next->b=3; } }; int main(){ a a1; cout<<a1.b<<endl; cout<<(*(a1.next)).b<<endl; return 0; } I expected output to be: 5 3
a* next=new a; Your a struct has a member called next, which gets default-initialized by new. Every instance of a that your program creates will have a class member called next, which gets initialized by new. That's how classes and default class member initializers work. This member is, like I said, is another struct ...
61,648,567
61,648,749
Operator Precedence in Conditional Operator
So I was experimenting with some templates recently, and this was the code that I stumbled upon: template <typename T> int someFunction(T someParameter) { return std::is_same<T, bool>::value ? 1 : 0 + std::is_same<T, char>::value ? 2 : 0 + std::is_same<T, int>::value ? 3 : 0; } So it's ba...
Yes, operator+ has higher precedence than condition operator, so return std::is_same<T, bool>::value ? 1 : 0 + std::is_same<T, char>::value ? 2 : 0 + std::is_same<T, int>::value ? 3 : 0; is interpreted as return std::is_same<T, bool>::value ? 1 : ( 0 + std::is_same<T, char>::value ) ? 2 ...
61,648,581
61,648,692
Conditional Specialization
Suppose I have the following: template<std::size_t> struct s; template<> struct s<sizeof(int)> { /*...*/ }; template<> struct s<sizeof(long)> { /*...*/ }; // will not compile as it already exists. How do I implement a check to differentiate the two instantiations conditionally? I only want to implement the latter if ...
You can have both the specialisations take an (unconstrained) std::size_t, and only enable the specialization if it == sizeof(int) or == sizeof(long) && sizeof(long) != sizeof(int): #include <type_traits> #include <cstddef> template<std::size_t, typename = void> struct s; template<std::size_t N> struct s<N, std::enab...
61,648,593
61,692,704
what are lookup rules when a name occured before function's declarator-id?
#include <iostream> typedef int Name; Name func(int){ return 0; } int main(){ } Consider the above code, I can't find a bullet in [basic.lookup.unqual] that can interpret how to lookup Name for definition of func. I will cite some potential rules here: A name used in global scope, outside of any function, class ...
I think that Name is within the function(definition), bullet 1 isn't satisfied. Bullet 1 didn't say "function(definition)". It said "outside of any function". It doesn't specify declaration or definition; merely "outside of any function". Since being inside or outside of a "function" is not a defined concept, it must...
61,648,612
61,652,298
Recursive functions with || operator?
So I was tinkering with || and && operators with return. I developed an understanding by comparing int as for example return 1 || 0; return 0 || 0; that the program returns 1 or 0 in case of an int function and true or false in case of bool functions after comparing values. Now I was writing a code to find path sum to ...
operator || and operator && does short circuit, so might doesn't evaluate second operand depending of the first one. bool b = f() || g(); is mostly equivalent to bool b = f(); if (b == false) b = g(); bool b = f() && g(); is mostly equivalent to bool b = f(); if (b == true) b = g();
61,648,829
61,649,031
Is there an ideomatic way to avoid this use of Naked New?
In my application, I need to set callbacks whose sole responsibility is to update the state associated with a completed event in a separate object so that it can be queried later. However, because of how the API is designed, I can't guarantee that the other object will still be owned by the time the event completes, so...
Within the lambda, there's a clear improvement possible by simply using a unique_ptr: auto callback = [](cl_event event, cl_int, void* ptr) { std::unique_ptr<std::weak_ptr<render_future::shared_state>> ptr_ptr{ static_cast<std::weak_ptr<render_future::shared_state>*>(ptr)}; if(auto shared_ptr = ptr_ptr->lock())...
61,649,100
61,651,741
C++ Information from csv gets unorganised in the array[][]
I am new in C++, actually learning to do the assignments from the Masters I am studying. Firstly in my code, I need to read each row and column from a csv file and store it in an array[][]. My CSV file is(columns A1, A2, B1, B2): 46842 test 46825 test2 My code atm is: #include <iostream> #include <fstream> #include <s...
You made some mistakes that need to be fixed. You used std::getline to read until the next comma. It will do exactly that, even if a new line starts. So it will continue tor read until it finds the next comma. This will explain the output of cell 0.1: test 46825 It shows "test", then the new line and then 46825. So, ...
61,649,105
61,649,128
Will "while( bool a && bool b )" check both a and b even if a proves to be false?
There are some cases which i'll have to loop through an array/vector looking for an element that satisfies a condition that involves the element's value.In the past i'd go for a simple for loop together with an if statement, but lately i saw a piece of code that seems more simple.To be precise: I used to do it like thi...
Yes, operator|| performs short-circuit evaluation. Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands That means for while( i ...
61,649,642
61,649,704
I cannot seem to find the appropriate way to declare char a[] and char b[]
#include <iostream> using namespace::std; int main(){ void dost(char a[], char b[]); void man(void); { char s1[] = "TBTBABLJ"; char s2[] = "IBSVOB"; dost(s1, s2); cout << s2 << endl; } void dost(char a[], char b[]); { b[3] = b[1]; b[2] = a[4]; b[0] = a[0]; } } How would I declare a ...
You have braces and semicolons in the wrong place. The proper layout for this code could be: #include <iostream> using namespace std; void dost(char a[], char b[]); int main() { char s1[] = "TBTBABLJ"; char s2[] = "IBSVOB"; dost(s1, s2); cout << s2 << endl; } void dost(char a[], char b[]) { ...
61,649,695
61,650,033
How come the answer is 5?
I was browsing through Medium, and found this simple prroblem statement: int i = 4; int j = i++; int k = ++j; cout << i << j << k << endl; //output:= i= 5, j=5, k= 5 how is that possible? Like if we are placing the i as 4, but output is 5?
Post increment operation (i++) is always assign, then increment Pre increment operation (++j) is always increment, then assign So in your second line, i is first assigned to j, then i increases. So j has the original i value. In your last statement, j is incremented first and then assigned to k.
61,649,833
62,017,994
Performance of SpatialConvolution implementation in tensorflow
I realized a SpatialConvolution function by referring the implementation of tensorflow (use eigen). The implementation in tensorflow is located at SpatialConvolution and I also find one related reply about the implementation : https://stackoverflow.com/a/58955289/7587433 My implementation is as follows: (since my data ...
After digging into the code, we found tensorflow realized custom eigen kernels based on MKL. With the implementations in eigen_contraction_kernel.h/.cpp and eigen_spatial_convolutions.h, We can get the same performance with tensorflow.
61,650,002
61,652,681
fstream::read() read empty if input size too big
I have tried to read a file by using istream& read (char* s, streamsize n). I have read the description at: http://www.cplusplus.com/reference/istream/istream/read/ saying If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the arr...
ifs.read(buffer, UINT32_MAX); The second parameter to fstream::read is std::streamsize, which is defined as (emphasis mine)... ...a signed integral type... I therefore guess (as I don't have a Windows environment to test on at this point) that you're working on a machine where std::streamsize is 32bit, and you're lo...
61,650,313
61,650,517
is this not using boolean operators in c++?
I have some code which is incorrect because i have not used boolean operators However i thought the boolean operators in c++ were && and || here is the question: Enhance your search algorithm so that a query may contain Boolean operators – AND and OR. For instance, a query “word1 AND word2” means to find all the i...
EDIT: the function foundWordInBoth is a boolean function and there is no error with the code. i showed my teacher my code and he said no that way is too easy you need to use boolean operators, which is why im confused Your code seems fine to me. Probably your teacher wants you to use the bitwise boolean operators...
61,650,649
61,664,684
Write gtest to verify the class is null
I have few lines of code like below: int class1::function() { std::unique_ptr<namespace::class2> devObjPtr(new namespace::class2); if (devObjPtr == nullptr) { return 0; } return 1; } This function is present in another class in the same namespace. How can I test that piece of code using gtest or gmock?
If you're only interested in controlling the output of class1::function(), then you could use gMock like this: class mock_class1 : public class1 { public: MOCK_METHOD(int, function, ()); }; TEST(TestBase, Test_success) { mock_class1 mock; EXPECT_CALL(mock, function).WillOnce(Return(0)); // Some code t...
61,651,043
61,652,945
Generic object instanciation
I have a class: class User { public: int id = 0; std::string email = ""; User(int id_, std::string email_) : id(id_), email(email_) {} }; I can contruct an instance like this: auto x=Model::User({3,"m"}); But i need to construct the instance using using data from a ve...
You might do: User makeUser(const std::vector<std::any>& args) { return User(std::any_cast<int>(args[0]), std::any_cast<const char*>(args[1])); } As C++ doesn't have reflection, to make it generic, you will have to provide traits to each class you want to support (or be compatible with magic_get) template <typenam...
61,651,063
61,652,704
Deallocate dynamic array returned from a function
I have the following: string *myFunction(void); int main(void) { string *newArrPtr = myFunction(void); //Do something with array //Deallocate memory here? //delete[] newArrPtr? //newArrPtr = NULL? return 0; } string *myFunction(void) { string *oldArrPtr = new string[256]; //Do s...
but I'm now sure how and when to deallocate it again. "How" is easy: you just use delete or delete[] when dealing with arrays. "When" is more interesting. You cannot use delete[] inside myFunction because you would free memory before returning it. Side note: inside a function, no code gets executed after return state...
61,651,079
61,651,170
Does forward declaration fix the number of argument?
I'm learning c++ now, and did some experiment for self study. It seems that if a function is declared with variables assigned by default value, that function does not require arguments for those variables having default value. int foo(int a, int b, int c = 3) { return a+b+c; } int main() { int q = foo(2,5); /...
Simply put, the prototype needs to contain the default argument value: int foo(int a, int b, int c = 3); And when you define the function, you omit it: int foo(int a, int b, int c) { return a+b+c; }
61,651,156
61,651,435
How can interface return an unknown type?
I'm trying to make a cpp interface class (pure virtual) declare a function that all derived classes must implement. However because the interface class is trying to be ignorant of implementation details, it doesn't know about the type of the returned object, and would like to delegate that to the derived class. The s...
Two options come in my mind, depending what fit better in your project: 1) Use a placeholder for return type: class UIInterface { Widget* getWindow() = 0; } you can define in other file using Widget = QWidget. You can hange the alias or even implement your class Widget later and the whole UIInterface will not ch...
61,651,500
61,651,592
why does recursion function works in visual studio eventhough there is no return value
#include <iostream> using namespace std; int test(int numb) { if (numb == 0) return 0; test(numb - 1); } int main() { cout<<test(10); } so i was solving some algorithm questions. this code works in visual studio but not in other online shell. what does test() function returning even though there is no r...
Your function has undefined behavior when it doesn't return anything. The number 1349009568 is meaningless and probably random. For me, it shows a 0, and has the same output as this version which will never return anything. int test(int numb) { if (false) return -1; }
61,651,539
61,659,696
How to create a vector from sub-elements of another vector in C++?
I have a code like: struct cart_point_2d{ double x; double y; } struct curve_point_2d{ double arc; double kappa; cart_point_2d; } std::vector<curve_point_2d> trajectory; After trajectory is initialized I need to create another local vector that has the same length as of trajectory but should only contain cart_point_...
for_each can be used too: std:vector<cart_point_2d> result; std::for_each(trajectory.begin(), trajectory.end(), [&result](const auto& item) { result.push_back(item.point); });
61,651,651
61,652,036
C++ "Class Enum" Novice Problems
I'm starting learning to code in C++ (coming from VB.net) and i need some help in enum class usage. I've done this simple code from a lerning exercise (originally divided in header.h and Exercise.cpp, but i putted it all together here): #include <iostream> #include <string> #define BEGIN_WITH(x) { \ auto &_ = ...
<< operator is not defined for class Gender because it's your own class. You'll need to overload it. More info here. enum class Gender { male, female }; ostream& operator<< (ostream & os, const Gender & g) { switch(g) { case Gender::male: os << "Male"; return os; case Gender::female: os << "Female"...
61,652,223
61,652,316
How does this list-like initialization work?
I know about several types of initialization in C++ and recently learned why list initialization should be preferred. But what about this code? live demo #include <iostream> #include <string> class A { public: A(int x, std::string y) { std::cout << "normal\n"; } A(const A& obj) { std::cout << "copy\n"; } }; ...
So I thought it would create a temporary instance of A from {1, "2"} and then call the copy-constructor. You're right. Here the object a is initialized via the constructor A::A(int x, std::string y) directly because of copy elision. You can compile with -fno-elide-constructors option (with pre-C++17 mode, since C++1...
61,652,334
61,652,538
How do I force the compiler to evaluate a switch at compile time?
I'm working on an embedded project (only C++14 compiler available) and I would like to optimize the speed of execution. Here is an example of what I am doing. enum gpio_type{ TYPE_1, TYPE_2 } template <gpio_type T> class test{ test(){} void set_gpio(bool output) { switch (T) { case TYPE_1: ...
Constant propagation and dead code elimination are one of the simplest compiler optimizations. And since T is a compile time constant I would be extremely extremely surprised if the code isn't optimized by any compiler. I have tested 15 compilers and platforms on godbolt from the venerable x86 to arm, avr, risc-v, rasp...
61,652,502
61,655,638
Can you use different constants for class objects in C++?
I came across a class which sole purpose was to create blinking leds. He used the class for 2 objects which had a different blinking interval. I started thinking in how I could use constants but nothing came to me. Is it possible to use a const int in combination with the constructor to use different constants for obje...
To summarize the discussion, and correct some of your wrong assumptions: class BlinkingLed { private: const byte blPin; // This should definitely be const const unsigned short blinkInterval; // <-- the desired constant (why?) bool blinking; bool ledOn; unsigned long lastTime; public: Bl...
61,652,860
61,658,348
Pointer Arithmetic - Issues with array and pointer to an array
I've switched to C recently and was trying to figure out pointers. #include <stdio.h> int main() { int arr[5] = {1,2,3,4,5}; int *a = &arr; printf("Array : %p\n", arr); for(int i=0; i<5; i++) { printf("Value and Address of Element - %d : %d\t%p,\n", i+1, arr[i], &arr[i]); } printf(...
a = (&a+1); sets a to point to one “thing” beyond the address of a. Earlier, your code sets a to &arr, using int *a = &arr;. (This violates standard C constraints because the type of &arr is a pointer to an array, not a pointer to an int. The correct definition would be int *a = arr;.) I suspect your intent in a = (&a+...
61,653,255
61,656,882
boost::mpi as static member of templated class
I wanted to use boost::mpi communicators in my class, because I want my class to take care of all MPI calls. I used this style to make them static members of my class. // works.cpp // mpic++ -o works works.cpp -lboost_mpi #include <boost/mpi.hpp> #include <iostream> class Example { static boost::mpi::environment env...
Any particular reason you need a boost::mpi::environment instance in your classes? It is just a horrible OO wrapper around the currently singleton nature of MPI - you may initialise MPI only once by calling MPI_Init() and finalise it only once afterwards by calling MPI_Finalize() (at least, until the MPI sessions make ...
61,654,969
61,655,219
Time complexity of 'if' with multiple conditions
I'm confused whether the time complexities of these two codes are same or different. code1 #include<iostream> using namespace std; bool check(int a[]) { if(a[0]==1 && a[1]==1 && a[2]==1 && a[3]==1 && a[4]==1 && a[5]==1 && a[6]==1) return true; return false; } int main() { int a[7] = {1,1,1,1,1,1,1};...
In your case you're doing the same kind of thing for every item in the input once. if..else is just one normal statement you do to each item once. It does neither increase nor decrease the runtime/complexity. Your algorithm is O(1). If as per lizard.ws 2 code is efficient it might be taking the factor that everytime ...
61,655,079
61,661,563
Override pure virtual function with different parameter of derived type
There are a lot of questions about this topic, but however, I didn't find the solution for my following question: I have the following classes: 1) The pure virtual class class Employee { private: vector<Employee> vec_employee; public: Employee() {}; virtual ~Employee() {}; virtual void set_vec_subordin...
There is no way to do exactly what you plan to do (and there is good reason for that). Your code is also inherently broken, as you use the type vector<Employee>, which requires objects of type Employee - which cannot exist, as Employee is an abstract class. You may wish to use a vector of a reference type, e.g., vector...
61,655,365
61,659,952
Why does in C++ big endian to int16 with bitshift not work?
I'm reading a bytearray (2 byte big endian) with Qt QByteArray a = data.mid(cellNumber, 2); int16 res = qFromBigEndian<qint16>(a); and want ot get int16. It works correctly but slow. If I use std::bitset<16> b0(a[0]); std::bitset<16> b1(a[1]); qint16 b = (b0 << 8) | (b1 << 0); the result is wrong. The reason is the...
Thxs to All!!! std::bitset<16> b0(static_cast<unsigned char>(a[cellNumber])); std::bitset<16> b1(static_cast<unsigned char>(a[cellNumber + 1])); std::bitset<16> resb = (b0 << 8) | (b1 << 0); int16_t resi = int16_t(resb.to_ulong()); I tested it also for negativ values, as long they of course don't exceed the int limits...
61,655,584
61,657,053
'char **': invalid target type for dynamic_cast
I have written the following code but when I compile it, the compiler gives me a bunch of errors about dynamic cast usage. How should I fix this issue? I have to implement the code with c++ feature. #include <iostream> #include <ctime> void draw(void* u, int w, int h) { char(*world)[w] = dynamic_cast<char**>(u); ...
To expound upon above The error comes from the fact that dynamic_cast needs a class type as per message : target type must be a pointer or reference to a defined class You can pass a 2D array with a little more work on your part. The idea is you want to treat the first dimension as an array of pointers. #include <ios...
61,655,741
61,681,655
Using sqlite3_load_extension with a windows DLL
Can anyone tell me where I'm going wrong here? I'm using C++ bulder 10.2 (clang compiler). From IDE menu I've selected File|New|Dynamic Link Library and chosen compile as C with no dependencies. I've then added sqliteFcts.c and made the sqliteFcts.dll library. It all compiles fine. Contents of sqliteFcts.c. #include <s...
I finally got it working but with a loose end. Firstly in this line rc=sqlite3_load_extension(db,"C:/temp/sqliteFcts.dll",0,&buf); I supplied a null for the 3rd parameter (the entry point) thinking sqlite would resolve this however sqlite would've supplied sqlite3_sqlitefcts_init (note lower case f) as the entry point...
61,656,319
61,656,396
Sorting vector of different class objects based on their member variables
Let's say I have a code like this #include <iostream> #include <vector> #include <memory> #using namespace std; class animal{ protected: int height; int speed; }; class horse:public animal{ public: horse(){ height=200; speed=75; } }; class cat:public animal{ public: cat(){ height=30; speed=20; } }; clas...
You can use std::sort from <algorithm> with a lambda function define your sorting predicate. std::sort(animalvector.begin(), animalvector.end(), [](auto const& lhs, auto const& rhs) { return lhs->speed > rhs->speed; }); Note that speed would either need to be public or you'd need a public gett...
61,656,425
61,657,668
Pass adress of an object method to another object for it to call
Hi I am in C++ and I would like to pass the method of one object to another object of the same class: class Object{ public: int id; int newId; Object(int _id){ id = _id; }; int (*function)(); int someFunction(){ return id*2; }; void updateFunction(){ newId = function...
There's no way to do with you want with function pointers, because methods cannot be assigned to function pointers. But you can do what you want with std::function which is much more flexible than a function pointer and with a lambda function to bind your method to a particular object, #include <functional> class Obje...
61,656,491
61,657,014
Why can't std::atomic<T> be swapped?
#include <atomic> int main() { auto a = std::atomic_int(1); auto b = std::atomic_int(2); std::swap(a, b); // error } error message: error: no matching function for call to 'swap(std::atomic&, std::atomic&)' Why can't std::atomic<T> be swapped?
There are two levels to that issue. First is plain simple and technical - std::atomic is not move constructible or move assignable as mentioned in other answer. Second is the rationale behind this - swapping std::atomics would not be atomic in itself. And since std::atomics are used in multithreaded environments adding...
61,657,002
61,657,175
Is it possible to overload new operator for allocating something like 2d array in C++?
Is it possible to overload global new and global delete operators in C++ for allocation and deallocation of 2d block of memory with given "height" and "width"?
Is it possible to overload new operator for allocating something like 2d array in C++? Yes. but can I get some code example? Example: std::unique_ptr<int[][10]> arr {new int[n][10]}; with given "height" and "width"? Only if the inner dimensions are compile time constant. Only the outer dimension may be dynamic. ...
61,657,029
61,659,209
Problem with calling constructor outside the setup() in Arduino
I had a OLED SPI display 128x64 and I was using Adafruit_GFX and Adafruit_SSD1306 to control it. I had a class name Engine which had a public constructor like this: Engine::Engine() { display.begin(2U, 0U, true, false); // Define some pinmode not a problem pinMode(button1Pin, INPUT_PULLUP); pinMode(butto...
You need to split that constructor into two parts. Right now your constructor is doing things with hardware like calling pinMode. But if you call it at global scope before setup is called then it will get called before main calls init() and sets up the hardware. Basically, you're calling pinMode before the board is ...
61,657,889
61,894,488
Invalid Wire Type Exception on Protobuf-net Deserialize with Nested Data (C++ to C#)
I've been given a C++ application (a built executable and source code that doesn't build right now) that uses generated proto classes to send protobuf messages. I took the same .proto files it used to generate its classes, and I generated associated classes in a C# app. The intent is to be able to receive and send mess...
My incoming data had about 50 extra bytes of "stuff" I wasn't expecting (i.e. not the message header), which didn't adhere to the defined message format, so the data was essentially corrupt. It was hard to tell this from looking at a stream of bytes; what gave it away was the difference in length of a message that I se...
61,658,326
61,658,454
socket always returns INVALID_SOCKET
i'm trying to create a multi threading server for a school project and i'm relying on a similar code that i wrote in the past but for some reason in the open function it always goes into the if statement and crashes. what stops it from creating the socket? #pragma comment(lib, "Ws2_32.lib") #include <WinSock2.h> #incl...
You should call WSAGetLastError to get the actual error code that caused INVALID_SOCKET to be returned. In this case, it appears you are not calling WSAStartup, so you are getting a WSANOTINITIALISED error. You must call WSAStartup before using any Winsock functions.
61,658,552
61,659,488
Unexpected output in C++
This is not a problem with programming contest but with the language C++. There is an old programming problem on codeforces. The solution is with C++. I already solved in Python but I don't understand this behavior of C++. In my computer and on onlinegdb's C++ compiler, I get expected output but on codeforces judge, I ...
Let's dissect this code and see what problems we can find. It kind of tips over into a code review, but there are multiple problems in addition to the proximate cause of failure. #include<bits/stdc++.h> Never do this. If you see it in an example, you know it's a bad example to follow. using namespace std; Fine, we're...
61,659,186
62,218,551
Can't return Graphics object from a function in Win32 C++ GDI+
I am creating some functions that facilitate a little bit GDI+. I have created this function to begin paint to be used in WM_PAINT: Graphics StartPaint(HWND win, HDC *hdc, PAINTSTRUCT *ps) { *hdc = BeginPaint(win, ps); Graphics g(*hdc); return g; } It gives compile error and takes me to "gdiplusgraphics.h"...
Thank you all. The function now works well as follows: Graphics *StartPaint(HWND win, HDC *hdc, PAINTSTRUCT *ps) { *hdc = BeginPaint(win, ps); return new Graphics(*hdc); }
61,659,569
61,660,899
Why does gcc8.3 appear to attempt to compile an unused template function?
Consider (the name of the file is hello.cpp) this code; the idea is to engineer a safe casting of numeric types without loss or overflow. (I'm porting some code from MSVC to g++). #include <cstdint> #include <iostream> template< typename T/*the desired type*/, typename/*the source type*/ Y > T integral_cast(co...
GCC isn't really "instantiating" or "compiling" the base function template. If it was, you would have two compiled functions with the same name and parameter list. As @Raymond Chen pointed out in the comments, GCC is permitted, but not required, to raise an error for templates that don't have any valid instantiation. F...
61,659,627
61,661,666
Allow a specific undefined reference with GCC
In a C++ program with GCC I am using linker flag -Wl,--no-undefined so the linker will throw an error if there are undefined references. Is there a pragma or something I can put in the code next to a specific symbol that I want to allow to be undefined at link time?
One option is to make that symbol weak: A weak symbol denotes a specially annotated symbol during linking of Executable and Linkable Format (ELF) object files. By default, without any annotation, a symbol in an object file is strong. During linking, a strong symbol can override a weak symbol of the same name. In contr...
61,660,112
61,660,525
Why are both of my arrays are in reverse order when I only intend to reverse one of it? [C++]
Trying to create a Palindrome checker of sorts and one of the processes involves reversing an array. The user enters the number of characters to input, enters the characters one by one, and the code itself will determine if it's a Palindrome ( same words when reversed, the racecar is spelt racecar backwards ). Problem ...
You have undefined behaviour. kimak[i] and rord[i] is undefined, since both strings are size 0. You can either resize the two strings prior to the loop, or use the push_back function of the string.
61,660,573
61,661,038
Are static constexpr variables inlined in C++?
Lets have following code in C++14: using namespace std; void foo(int a) { cout << a; } int main() { //version1 foo(13); //version2 static constexpr int tmp = 13; foo(tmp); return 0; } Will the compiler automatically optimize version2 to version1 so that static constexpr variable will b...
Compilers are given wide latitude under the "as if" rule to optimize as they see fit. Given the fairly trivial nature of the code you posted, a compiler is just as capable of optimizing "version 2" even if you removed static constexpr from the definition. The compiler can see that you don't change the value of the vari...
61,660,590
61,662,782
Why do functions in c++ need pointers to work (pass by value,pass by reference)
I have a question in c++.I 'am a newbie and was coding the other day in c++, more specifically i was trying to implement some functions (1 that adds 2 numbers and 1 that swaps 2 numbers). I realized that the code implementing the addition function didn't need no pointers (void func), while the swap function only worked...
Per your title, functions don't need pointers to work: int add(int a, int b) { return a + b; } In C++ the rule for passing parameters is to pass a copy of the variables, unless told otherwise. When passing by copy (a.k.a. pass by value), the parameters cannot be modified. Rather than passing copies of large d...
61,660,610
61,689,267
How to do manual code vectorization with better performance that automatic vectorization for edge detection
I have been following this coursera course and at some point the code below is given and the instructor claims that vectorization is done by including #pragma omp simd between the inner and outer for loops since guided vectorization is hard. How can I vectorize the code used in the course on my own, and is there a way ...
Here is some untested proof-of-concept implementation which uses 4 adds, 1 fmsub and 3 loads per packet (instead of 9 loads, 7 adds, 1 fmsub for a straight-forward implementation). I left out the clamping (which for float images looks unusual at least, and for uint8 it does nothing, unless you change P val = ... to aut...
61,660,843
61,660,881
I'm having a problem with my little project
So, i'm doing a little "virtual friend" kind of project: #include <iostream> #include <string> using namespace std; int main() { std::cout << "Hey!\n"; std::cout << "My name is Bob! Hope I can be your friend! :D\n"; std::cout << "But before all of my questions... would you like to be my friend?\n\n"; ...
I assume you wanted something closer to string user_input; std::cin >> user_input; if (user_input == "yes") { // yes case } else if (user_input == "no") { // no case }
61,661,100
61,661,860
i tried to calculate the sum of numbers between 1 and the inputted numer
The program demonstrates the operation of the loop operator. Calculation of the sum of natural numbers. The positive integer n is introduced. The sum of natural numbers from 1 to n (inclusive) is calculated. Check n for validity. that was the work that I was given and I still don't know how to accomplish it and this is...
The anatomy of the for loop goes as this: for(1;2;3) What you do when entering the loop. In this case, setting i = 1. The loop's end condition. You seem to be getting this right as well. An operation to do every iteration of the loop. In your case, i += 2 will make i look like this on each iteration: 1 3 5 7 ... n. G...
61,661,281
61,661,345
Illegal operand of type void when defining UnaryPredicate
I'm trying to use std::partition with a custom UnaryPredicate. void Rank(vector< pair<double, string> >& pairs) const { partition(pairs.begin(), pairs.end(), [](const pair<double, string>& a) { isnan(a.first); }); } When doing this I get the following errors from Visual Studio 2015: Error C2297 '&&': illegal...
Your lambda doesn't return anything, it's corresponding function is really something like: void pairIsNan(const pair<double, string>& a) { // Discard the result of the isnan function (void) isnan(a.first); } To make it work you need to return the result of the isnan function call in the lambda: partition(pairs...
61,661,447
61,661,578
What is the difference between a JS object, Python dictionary and a C++ Struct?
This post explains the differences/similarities between a Python dictionary and a JavaScript object. However I would like to know the differences/similarities between a JS object and Python dict to a C++ struct. These 3 datatypes seems to be equivalents to each other in their respective languages, however I would assum...
There is no equivalent data type that is built-in to C++. C++ structs (which are just classes with default public member visibility) have the names and types of their members determined at compile time. For example, with a C++ struct/class, you cannot do these at runtime: Ask an object what members it has (reflection...
61,661,499
61,668,183
How can an the -I compiler option cause different warnings triggers?
I was recently tasked with restructuring an application and ran into a rather bizarre issue. I've reduced the issue into example code as best as I can. Consider the following: offender.h __attribute__ ((visibility ("default"))) typedef struct A { int a; } A; test.cpp: #include <iostream> #include <offender.h> in...
The documentation says The header files declaring interfaces to the operating system and runtime libraries often cannot be written in strictly conforming C. Therefore, GCC gives code found in system headers special treatment. All warnings, other than those generated by ‘#warning’ (see Diagnostics), are suppressed whil...
61,661,658
61,661,765
Auto-unpacking a pair of iterators
In C++, if a function returns a std::pair<int, int>, we can auto-receive it as follows: auto pr = some_function(); std::cout << pr.first << ' ' << pr.second; Now, C++17 standard provides a beautiful way of unpacking this pair directly into separate variables as follows: auto [x, y] = some_function(); std::cout << x <<...
Sure. Write a function that takes a pair of dereferencable things and returns the result of dereferencing them: template <typename Iterator, typename R = typename std::iterator_traits<Iterator>::reference> auto deref(std::pair<Iterator, Iterator> p) -> std::pair<R, R> { return {*p.first, *p.second}; } And ...
61,662,210
61,665,776
std::function - value vs. reference argument
Are there any practical differences between std::function for type with value parameter vs with const reference to value parameter? Consider following code: auto foo = [] (VeryBigType i) { }; auto bar = [] (const VeryBigType& i) { }; std::function<void(VeryBigType)> a; a = foo; a = bar; std::function<void(const...
cppreference says that std::function<R(Args...)>::operator() has signature R operator()(Args... args) const; and that it calls the stored callable f basically by f(std::forward<Args>(args)...). The performance characteristics depend on both the template argument and the lambda's argument type and I think it would be h...
61,662,227
61,663,385
Most efficient way to find iterators of 4 maximum values in const vector in C++
I have to find 4 the biggest numbers in a const vector and return their positions. I want this code to have the best time and space complexity. My first idea is to copy this const vector into vector and bubble sort it 4 times. That gives me 4*N but i have to create a vector. Second idea is to put everything from this c...
You can implement this quite easily with an extra vector, and the nth_element algorithm, which is O(n) time: std::vector<int> const v = ...; // create a vector of elements with original indexes std::vector<std::pair<int,int>> res; // populate the result vector int k = 0; for (int i : v) res.push_back({i,k++}); // ...
61,662,279
61,662,375
vector erase() iterator outside range
I'm getting the error (vector erase() iterator out of range) on this line: t[i].erase(t[i].begin()+k); the input is: 4 9 2 7 8 6 4 3 7 5 8 1 8 7 6 9 4 The error pops up after i turns 2, it works for i=0,1 why? #include <iostream> #include <vector> using namespace std; int main(){ int N, input; cin >> N; ...
As you erase elements of the vector, the vector gets smaller. Since your loop is going to N, eventually the loop index k gets larger than the remaining vector.
61,662,466
61,663,310
Can the tag of MPI_Send() be a long int?
I am working on my project which uses cpp and openmpi. Inside my program, there are many "compute units", I call them elements. For each element, I generate a unique unsigned long int to identify it, I call this integer key. The problem is that I now need some elements to communicate with each other among processors, ...
No, unfortunately, tags cannot be long ints. The C bindings define the tag as int, but the set of actually allowed values is even smaller and is also implementation-dependent. For one, tags must be positive. Then there is an upper bound (UB) imposed by the MPI implementation that is available by querying MPI_COMM_WORLD...
61,662,584
61,670,911
Using gazebo with drake for quadrotor
My objective is to use finite horizon linear quadratic regulator(FHLQR) to follow a trajectory generated by a mathematical program and simulate it in Gazebo. As FHLQR needs a system as input, I'm using the QuadrotorPlant, but I'm not sure if this is ideal. My problems arise when I try to connect the state from Gazebo i...
And for your gazebo interface, and assuming you're all in c++, then I'd imagine it will look something like this: // setup auto regulator = MakeFiniteHorizonLinearQuadraticRegulator(...); auto context = regulator.CreateDefaultContext(); // during execution context->SetTime(time_from_gazebo); context->FixInputPort(0, E...
61,662,623
61,664,807
Applying css style to Gtk::ToolButton is not working with a selector in gtkmm
I am trying to set an application wide css style in gtkmm-3.0 .This is how i initialize and load the style: #include "MainWindow.h" #include <string> #include <iostream> const std::string style = R"( toolbutton { border-color : #000000; border-width : 1px; border-radius: 0px; } )"; vo...
when we create Gtktoolbutton it's actually using Gtkbutton. so in your css if you add toolbutton button { it will work. gtkcss can be kinda confusing to learn as you wont find proper documentation(well I was not able to find a very detailed doc and all).. it's better to use GtkInspector to debug gtk css..
61,663,161
61,665,362
What do I need "normal" functions for when I can write everything in main()?
At the moment I'm only writing all the code in main() and that works quite well, so why do I need other "normal" functions? I ask that because I have noticed that it is better. But why? Since I have never really dealt with functions, I would be very happy over explanations how a function works. Thanks in advance for...
For the simplest of programs, having everything in main() is fine. But as soon as your program becomes somewhat more complex, your code will quickly become a nightmare to work with. With functions, your code will ... ... be easier to read ... be easier to understand ... be easier to maintain ... be easier to distribut...
61,663,205
61,664,279
Why do I get a segmentation fault in my C++ sudoku checker?
I'm actually coding on codingame.com and I get a segmentation fault in my program that doesn't make sense to me. I created a Grid class, which is basically a 2D array of (9*9) char and a couple of checking functions. My public check() calls private checkLine(), checkRow() and checkSquare(). Each of these 3 in turn call...
Two errors: bool checkNine(vector<char> nine) { array<int, 9> tmp; // <-- Too small, it has to hold 10 digits tmp.fill(0); for (int i = 0; i < 9; i++) { tmp[nine[i]] = tmp[nine[i]] + 1; // <-- Out of bounds access } return true; } The nine vector holds char values. Those char values a...
61,663,537
61,663,743
Can I forward-declare names -defined in other header in a header files?
I want to create a class Student that has a member of type library std::string but I don't want to include the header <string> in my Student.h and use only forward-declaration: // Student.h #ifndef STUDENT_H #define STUDENT_H #include <iostream> typedef class string_ string; struct Student { public: Student(cons...
Yes, but only if they match. You forward declared a global type string, not in namespace std. You could probably make it work with namespace std {} but then your program would have undefined behaviour, because you're not allowed to declare new things in that namespace (with a few exceptions). In general, you want to av...
61,664,210
61,664,715
How to deal with SIGSEGV in C++
Here is a func for (i guess) transposing matrix executed, as an arg of a vector copy-constructor: vector<vector<double>> tB(trans(B)); I have a segmention fault here: vector<vector<double>>& trans(vector<vector<double>>* matrix) { vector<vector<double>> result(matrix->size(), vector<double>(matrix->size(), 0.0)); ...
trans returns a reference to an object on the stack, which is deleted when trans returns. This is undefined behaviour. You should return a value, not a reference. So the only change is in the function signature. vector<vector<double>> trans(vector<vector<double>>* matrix) BTW, if you expect matrix to never be nullptr,...
61,664,235
61,664,322
Vector subscript out of range with min and max element
I am trying to make program which finds max and min element of vector, and and outputs elements in the interval min max, but skips those that were specified in the vector. For example: in: 2 6 7 min is 2, max is 7 out: 3 4 5 But I have error message: vector subscript out of range The code: #include <iostream> #inclu...
You can use the std::find along with the computed min and max: for (int i = min + 1; i < max; ++i) if (std::find(vect.begin(), vect.end(), i) == vect.end()) std::cout << i; This is not the most efficient solution (e.g. If you sort the vector, then you don't need to repeatedly call find). Also, be careful when de...
61,664,275
61,664,557
Linker Error "unresolved external symbol" when using constructor of other class
I've been struggling to find why my linker gets an unresolved external symbol error. The error looks like this: Error LNK2019 unresolved external symbol "public: __thiscall Shader::Shader(char const *)" (??0Shader@@QAE@PBD@Z) referenced in function "public: __thiscall GridWorldGPGPU::GridWorldGPGPU(class std::basic_str...
Provide default constructor of the class as well. class Shader { public: Shader(){} // default constructor Shader(const char* cs_path); }; Dont use inline in Shader::Shader(const char* cs_path){} definition
61,664,287
61,664,766
Why does providing an explicit initializer on an extern inside a function not override extern?
According to C++ Primer, we can provide an initializer on a variable defined as extern, but doing so overrides the extern. An extern that has an initializer is a definition: extern double pi = 3.1416; // definition It is also stated in the book that providing an initializer on an extern inside a function is an error. ...
According to C++ Primer, we can provide an initializer on a variable defined as extern, but doing so overrides the extern. Only partially. Providing an initializer forces the declaration to be a definition (except in the case of some static members of classes). It thus partially counteracts the effect of extern, whic...
61,664,817
61,664,991
C++ string to C string
Consider the following piece of code: void fun (string &str1, string &str2) { const char* cstr; .... if(strlen(cstr = (str1+str2).c_str()) < 15) { // here cstr used } } The condition itself works fine, but in the if-condition body cstr contains garbage. Why?
I'm assuming the string in your C++ code is std::string. str1 + str2 produces a temporary std::string object. You invoke the c_str() method on it, and you get a C-style string pointer to the data of this temporary std::string object. When the temporary std::string goes out of scope and is destroyed, the cstr raw C-styl...
61,665,005
61,665,656
Why is the const static variable odr-used here?
Consider the following code: class Test { public: static const int VALUE = 100; }; std::tuple<int> foo(std::tuple<int> value) { return value; } int main() { auto t = std::make_tuple(Test::VALUE); // This compiles fine auto t1 = foo(std::make_tuple(Test::VALUE)); // undefined reference to `Test...
make_tuple takes the argument by const int& (since it's a constant lvalue and it takes a T&& argument), and binding a reference to a value is an ODR-use. Both cases are ill-formed no diagnostic required. At high optimisation levels of gcc for example, the entire program is optimised out and there are no linker errors, ...
61,665,072
61,677,971
Why my C++ code for printing maximum element in stack is not producing correct output?
I am working on a programming exercise Maximum Element (https://www.hackerrank.com/challenges/maximum-element/problem?isFullScreen=false) using C++, the goal of the exercise is to print maximum element for each type 3 query. Each query is one of these three types: Push the element x into the stack. Delete the element ...
1) declared the stack out of the loop 2) previously the elements were being popped out for finding the maximum element so made another stack to keep track of the maximum element New code passed all the test cases:- #include <iostream> #include <stack> using namespace std; int main() { stack<int> s, max; max.push(0...
61,665,173
61,666,349
“Undefined reference” error in communication between Arduino and cmy library
I'm trying to start the development of a arduino project. I implemmentted a library called "IMU", to hold the object Adafruit_BNO055.h and a kalman filter. I follow the Arduino tutorial to create libraries but it's not working. when compilling i'm getting the following error: sketch\main.ino.cpp.o:(.literal._Z4loopv+...
I've just solved the problem. I've mooved the files to outside of the imu folder. Now IMU.h and IMU.cpp is in the same folder then main.ino.
61,665,594
61,665,713
Move constructor and move assignment operator throw error when set to default in .cc source file
I have a template base class that looks roughly like this Vector.cc: template<typename T, unsigned int D> class Vector { private: T _data[D]; ... public: Vector(Vector<T, D>&&); ... public: Vector<T, D>& operator=(Vector<T, D>&&);; }; extern template class Vecto...
The issue is that the default move is not valid. Inside the class, presumably the compiler doesn't bother generating the code for it, since its likely not used. Putting it outside the class might cause the compiler to decide to compile the operator/constructor. Think of it in a basic example: int array[5]; int array2...
61,665,963
61,667,163
Problem about templates and virtual function
I have a problem with templates - virtual function mismatch. First of all, i have a parent class named Unit and 2 child classes named Hero and Monster. These 2 classes have both 2 subclasses and one of the class Hero's subclass is Crusader. class Unit { template <typename target> virtual void Attack(typename std::...
Templates are not the tool you need here. Polymorphism is. Templates are useful for when you have similar or identical code that has to work on multiple unrelated types. Polymorphism is useful for when you have a set of directly related types that all need to do different things. Here, you have Crusaders, Heros, and M...
61,666,159
61,702,558
How do I get #include<> to look in a subfolder of the standard system directory?
I made the original post below but think the question can be made more general. I installed a c++ library called ibex. It contains a file ibex.h and a subfolder ibex, and the subfolder contains more header files that are called by ibex.h. Both ibex.h and the subfolder are located in /usr/local/include. I have confirmed...
I'm unfamilar with XCode and Sublime Text but I can show you a demo of the problem, and how to solve it, at the compiler level. You can work how to apply that in the compiler settings of your IDE. Here's the contents of a project folder for a program: $ ls -R .: header.h main.cpp subfolder ./subfolder: subheader.h ...
61,666,466
61,666,690
this is a cards game and i have a brace enclosed error
i check which player has a bigger value card.... then i print his name in the main function...but then comes an error (the error is in output [ n ] line : cannot convert '' to 'char' in assignment) void CardsGamePlay(int samy[], int magdy[], int n, char output[]) { int max1, max2 = 0; //comparing the card n...
Instead for char[] use, std::string, much simple #include<string> void CardsGamePlay(int samy[], int magdy[], int n, std::string &sName) { int max1, max2 = 0; //comparing the card numbers for (int i = 0; i < n; i++) { if (samy[i] > max1) { max1 = samy[i]; } ...
61,666,558
61,667,219
assigning an unique_ptr with std::move not working
i am quite new to c++ and smart pointers, but it is my understanding that i can assign an unique_ptr with std::move(another unique_ptr). when i try to assign a unique_ptr with std::move(..) it throws the following error: binary '=': no operator found which takes a right-hand operand of type 'std::unique_ptr<T [],std::...
When you do x = std::move(y) And y is of type std::unique_ptr<T>, then x must also be of type std::unique_ptr<T> (or two types whose pointers are implicitly convertible) or the assignment won't work. Your code, as shown, can only work if T is int8_t because that's what's on the left.
61,666,617
61,672,403
WinApi compression, decompression in python3
I have a small client application designed to run on windows machines. It is written in C/C++ (more in C). I want to keep it small and therefore I would prefer not to use external libraries and stick to WinAPI on client side. On the other hand I have a backend server which is implemented in python3. Here I'm happy to u...
I found this Python script, and reverse-engineered it to produce a quick library to handle WinAPI Compression/Decompression. Basically, you can just use ctypes and call the WinAPI from Python. Please keep in mind that I haven't extensively tested this, but it should give you a pretty good place to start :) EDIT: As req...
61,666,827
61,666,849
Extract uint8_t* subset from a vector<uint8_t>
I have a vector<uint8_t>, and I'm interfacing with an api that expects a uint8_t* data, size_t size. I need to provide the api with a subset of my vector, in my current solution I create a subset by using the vector constructor, and then I pass the data() of this new vector to the api: vector<uint8_t> subset(bytes.begi...
Yes, just combine the two but with data instead of begin. api(bytes.data() + offset, size); Using subscript and address-of operators also works api(&bytes[offset], size);
61,666,946
61,667,014
Side effect in different programming language
I am studying the Side Effect for different programming language. For instance, in C++, if I define x = 1; int f(int y) { x = x + y; return x; } and execute f(1) the new value of x is equal to 2. In python, I can surely execute define the same function x = 1 def f(y): x = x + y return x but when I execu...
In Python, you need to use the global keyword if you want to reassign a global variable. In C, you can just access them without needing an extra step. This version of your Python function should work correctly: As @roganjosh commented, global variables are not recommended (in either language), but they would make the...
61,666,948
61,667,040
Why does appear "passing 'const Person' as 'this' argument discards qualifiers" while using STL copy algorithm?
I'm trying to implement a max heap on user defined structures, and I use the std::copy_n() algorithm to take input from heap.in file, but I receive this kind of error from the compiler: passing 'const Person' as 'this' argument discards qualifiers Can anyone tell me where the issue is? #include <fstream> #include <ve...
I guess you meant this int main () { fin >> n; std::copy_n (std::istream_iterator <Person> (fin), n, std::back_inserter(Heap)); return 0; } std::copy_n copies n items from it's first argument to it's third. If you want to append to a vector then you must use the wrapper std::back_inserter as std::copy_n wo...
61,667,261
61,667,744
Why does the C struct hack not work for C++ template declarations?
C has this fun hack where one name can be used to declare both a type and a function: struct foo {}; void foo(void); Now, any time I write foo, the compiler assumes I mean the function unless I prefix it with struct: foo(); // call void foo(void) struct foo bar; // declare variable of type struct foo This works gre...
The wording is in temp.pre-7: A class template shall not have the same name as any other template, class, function, variable, enumeration, enumerator, namespace, or type in the same scope ([basic.scope]), except as specified in [temp.class.spec]... None of the points in temp.class.spec conflict with this example. So,...
61,667,301
61,667,538
Error : friend function not declared in this scope
/****************pair.h******************/ #include<iostream> using namespace std; template<class T1,class T2> class Pair { private : T1 first; T2 second; public : Pair(T1,T2); Pair(){}; Pair<T1,T2> make(T1 a , T2 b); void operator=(const Pair& other); ...
make is a global function. Your header file should look like this template<class T1,class T2> class Pair { private : T1 first; T2 second; public : Pair(T1,T2); Pair(){}; void operator=(const Pair& other); friend ostream& operator<<(ostream& out ,const Pair<T1,T2>& A); }; template<class T1,class T2> Pair<...
61,667,848
61,667,988
Can a derived class be smaller than its parent class?
I'm asking this about C++ since I'm familiar with that but the question really explains itself: is there a language in which we can derive a class and make it occupy less space in memory than the original class? This question is more of a gimmick than an actual problem I'm trying to solve, but I could imagine that some...
Can a derived class be smaller than its parent class? No. A derived class always contains a base class sub object. An object can never be smaller than its sub objects, so a derived class can never be smaller than its base. Is the only way to make this happen by replacing the 'name' field in Person with a get_name() ...