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
71,520,028
71,520,082
Segmentation Fault when refrencing vectors that changed size
So I initialize a vector within a main function, and pass that vector as a reference into a function where its size changes. Now, I would imagine that the initialized vector within the main would change in size, but its not. Am I just implementing this incorrectly? #include <iostream> #include <vector> using std::vector; void createImage(vector<vector<char> >& img){ int cols, rows; std::cin >> rows >> cols; img.clear(); for(int i = 0; i < rows; i++) img.push_back(vector<char>(cols, 'O')); } void colorPixel(vector<vector<char> > &img){ int xCoord, yCoord; char color; std::cin >> xCoord >> yCoord >> color; img[xCoord][yCoord] = color; } void printVector(vector<vector<char> > &img){ for(int i = 0; i < img.size(); i++){ for(int j = 0; j < img[i].size(); j++) std::cout << img[i][j]; std::cout << '\n'; } } int main(){ char operation; while(std::cin >> operation){ vector<vector<char> > myVector; if(operation == 'X') break; if(operation == 'I') createImage(myVector); if(operation == 'C') printVector(myVector); if(operation == 'L') colorPixel(myVector); } } Edit: This is what is effectively happening. When you create the vector so I 5 5 which calls createImage(), that works, but it begins to fail when you L 4 4 P which calls colorPixel() at myVector[4][4]. If I were to initialize myVector in main to 250 250, then print will print all 250 lines, even after being changed in size (such as 4 4) in createImage(). In short, I believe, and know for sure, that the vector within main is not getting the hint that its size has changed, is there any fix for this?
while(std::cin >> operation){ vector<vector<char> > myVector; The very first thing that happens in this while loop is that a new myVector gets created. This is, literally, what this says in C++. When the end of the loop gets reached, this myVector gets destroyed. That's how C++ works: if you declare an object in a loop, or inside the if statement, the object gets destroyed when execution reaches the end of this scope. So, when this while loop reaches this end, this myVector gets destroyed. It becomes no more. It will will be gone. It will ease to exist. It will be pining for the fjords. It will become an ex-myVector. Then, the while loop's condition gets checked again, and if the condition still holds true, execution enters the while again, creating a new myVector, from scratch. It will have nothing to do, whatsoever, with the previous myVector, which is just a faint memory. And the way to fix this is to declare this myVector before this loop, at the beginning of your main, so this myVector gets destroyed only when main, itself, finishes executing.
71,520,512
71,521,598
Enumeration conversion and undefined behavior
From cpprefernce/static_cast/8: A value of integer or enumeration type can be converted to any complete enumeration type. If the underlying type is not fixed, the behavior is undefined if the value of expression is out of range (the range is all values possible for the smallest bit field large enough to hold all enumerators of the target enumeration). I have two questions here: How the underlying type of an enum cannot be fixed. Consider this example: enum A : int { i = -1, b = 'c' }; Does the enum A's underlying type is fixed, regardless of the type of the enumerator values? Does the fixation of the underlying type is determined by either specifying the type or not, regardless of the type of the enumerator values? For example does this enum is fixed enum B { b, c }? How I can determine the range of an enumeration. Consider this example: enum N { c = 'A', hex = 0x64 }; Does the range of enum N is from 65 to 100? Hence the behavior is undefined in the following casts: static_cast<N>(64) // UB? static_cast<N>(101) // UB?
I'm going to write this with a focus on how to read cppreference.com. (This might make it seem more like I am answering one question instead of going over the limit.) How the underlying type of an enum cannot be fixed. This is a question about the enumeration type. So if the answer is not on the current page, the next place to look would be the page for enumeration type. Conveniently, on the page you linked to, the phrase "enumeration type" is linked, so you you don't have to search; just click the link. Once you get to the enumeration type page, you are interested in "fixed". So do a find-in-page (ctrl-f) for "fixed". The first occurrence of "fixed" is highly suggestive of what it means, while the second and third define the term in this context. The definition of an unscoped enumeration type whose underlying type is not fixed looks like form (1) in that section enum A { i = -1, b = 'c' }; while the definition of an unscoped enumeration type whose underlying type is fixed looks like form (2) in that section enum A : int { i = -1, b = 'c' }; If you specify the underlying type, then the underlying type is what you specify; it is fixed. If you do not specify the underlying type, then the underlying type is whatever the compiler decides to use; it is not determined in advance (i.e. not fixed). How I can determine the range of an enumeration This is given in your quote: the range is all values possible for the smallest bit field large enough to hold all enumerators of the target enumeration That's a lot of words, but just take it one piece at a time. Let's use your example: enum N { c = 'A', hex = 0x64 }; The range is all values possible for the smallest bit field large enough to hold all enumerators of the target enumeration. The range is all values possible for the smallest bit field large enough to hold all enumerators of N. The range is all values possible for the smallest bit field large enough to hold 'A' and 0x64. The range is all values possible for the smallest bit field large enough to hold 65 and 100. The range is all values possible for the smallest bit field large enough to hold values representable with 7 bits (unsigned). The range is all values possible for a bit field of length 7. The range is 0 to 127. While the compiler has some leeway in choosing the underlying type, the underlying type must be able to represent all enumerators. No matter what underlying type is chosen, it will be comprised of bits and be at least as large as the "smallest bit field" from the definition. The range of an enumeration consists of the values that will be representable no matter what underlying type is chosen. Values outside this range might fit in the underlying type, but they might not. Hence, whether or not they can be converted is undefined.
71,521,561
71,521,676
Passing two parameters at c++ lambda expression
I wanted to get a subset of vector having the same keyword in the vector. The code below works well, if I give the fixed keyword. auto category_matched = [](Product &p) { std::string str_return; p.GetInfo(kINFO_CATEGORY, str_return); return str_return == "keyword"; }; std::copy_if(list_.begin(), list_.end(), std::back_inserter(products), category_matched); Then I tried replacing "keyword" with string variable, which resulted in error. auto category_matched = [](Product &p, std::string keyword) { std::string str_return; p.GetInfo(kINFO_CATEGORY, str_return); return str_return == keyword; }; std::copy_if(list_.begin(), list_.end(), std::back_inserter(products), category_matched); Some of the error messages are like this: error: no matching function for call to object of type '(lambda at /Users/src/productset.cpp:128:29)' if (__pred(*__first)) note: candidate function not viable: requires 2 arguments, but 1 was provided How can I add string variable to the function?
capture the keyword std::string keyword = "froodle"; auto category_matched = [&keyword](Product &p) { std::string str_return; p.GetInfo(kINFO_CATEGORY, str_return); return str_return == keyword; };
71,521,750
71,521,798
How can I get the data type for boost::any variable?
I am looking for a way to check boost::any data type. If i assign an int to boost::any like: boost::any num1 = 5; And then use typeid(num1).name() , i want my output to be "int" so that i can use it in a if else statement in the future. However for some reason it keeps giving me this as the data type: N5boost3anyE #include <typeinfo> #include <iostream> #include <boost/any.hpp> using namespace std; int main() { int a; double b; float c; bool d; int16_t e; int32_t f; cout << " int: " << typeid(a).name() << endl; cout << "sizeof(): " << sizeof(a) << endl << endl; cout << " double: " << typeid(b).name() << endl; cout << "sizeof(): " << sizeof(b) << endl << endl; cout << " float: " << typeid(c).name() << endl; cout << "sizeof(): " << sizeof(c) << endl << endl; cout << " bool: " << typeid(d).name() << endl; cout << "sizeof(): " << sizeof(d) << endl << endl; cout << " int16_t: " << typeid(e).name() << endl; cout << "sizeof(): " << sizeof(e) << endl << endl; cout << " int32_t: " << typeid(f).name() << endl; cout << "sizeof(): " << sizeof(f) << endl << endl; boost::any num1 = 5; cout << "typeid(num1).name(): " << typeid(num1).name() << endl; boost::any num2 = "dog"; cout << "typeid(num2).name(): " << typeid(num2).name() << endl; } Output: johns-Air:cpp jdoe$ ./main int: i sizeof(): 4 double: d sizeof(): 8 float: f sizeof(): 4 bool: b sizeof(): 1 int16_t: s sizeof(): 2 int32_t: i sizeof(): 4 typeid(num1).name(): N5boost3anyE typeid(num2).name(): N5boost3anyE
You need to use boost::any's member function type() which returns a const std::type_info& of the contained value cout << "num1.type().name(): " << num1.type().name() << endl;
71,522,331
71,522,505
C++20 [[no_unique_address]] not working with clang's win32-coff target
While working with clang-13 in C++20, I noticed that the x86_64-pc-win32-coff cross-compile target seems to outright reject the [[no_unique_address]] attribute. This attribute is otherwise supported for other targets that I tested with. Consider this minimal example: struct bar {}; struct foo { [[no_unique_address]] bar b; }; which, when compiled with -target=x86_64-pc-win32-coff, produces <source>:4:7: warning: unknown attribute 'no_unique_address' ignored [-Wunknown-attributes] [[no_unique_address]] bar b; ^~~~~~~~~~~~~~~~~ 1 warning generated. Live Example Is it a known issue for different targets to reject attributes, or is this a product of just the underlying cross-compile target? I know that MSVC historically did not do empty-base optimization and kept this for ABI compatibility; is this a product of that compatibility? I suspect this is likely a bug in the target since it does not fully satisfy the C++20 spec, but I'm unsure of whether there is a pragmatic or known reason as to why this attribute is outright rejected, when other cross-compile targets seem to work without issue.
no_unique_address is something whose primary support has to be handled at the ABI level. Both the Itanium ABI and Microsoft's de-facto ABI (aka: whatever MSVC does) support no_unique_address... kinda. See, Microsoft is not at present willing to cause an ABI break. And since the attribute does nothing under a C++17 build, this would mean that compiling the same header for C++17 and C++20 could cause ODR violations. So instead, they're holding off on fully implementing the attribute. They have the code ready to go in the compiler (and you can even use the MSVC-specific attribute msvc::no_unique_address to get the same effect). But until they do an ABI break, they don't intend to support it. As such, Clang appears to be following Microsoft's lead on this.
71,522,403
71,565,047
d3dx12.h identifier undefined
I'm learning DirectX 12. I want to use d3dx12.h header file but there are lots of error, most of them are "identifer 'something' undefined'. So I searched about this problem and got some solutions. This is "check Windows SDK version" and I updated VS2019. But that's not a good solution for me. So I thought that DirectX 12 doesn't support GTX 750ti. I also found about it. But DX12 supports GTX 750ti. I don't know why 'd3dx12.h' makes some errors. I use: Windows 10, Visual studio 2019 (updated to latest version), GTX 750ti, d3dx12.h (latest version, https://github.com/microsoft/DirectX-Headers/blob/main/include/directx/d3dx12.h) most of them are "identifier undefined". D3D12_BARRIER_SYNC, D3D12_BARRIER_ACCESS, D3D12_GLOBAL_BARRIER .... and D3D12_FEATURE_DATA_DISPLAYABLE, D3D12_FEATURE_DATA_D3D12_OPTIONS8, D3D12_FEATURE_DATA_D3D12_OPTIONS9, ..., D3D12_FEATURE_DATA_D3D12_OPTIONS12, and D3D12_WAVE_MMA_TIER_NOT_SUPPORTED, D3D12_TRI_STATE_UNKNOWN, D3D_SHADER_MODEL_6_7, etc. These are what is undefined. and there are even more things. Severity Code Description Project File Line Suppression State Error (active) E0020 identifier "D3D12_GLOBAL_BARRIER" is undefined Engine C:\Users\Beomseo Choi\source\repos\Game\Engine\d3dx12.h 4087
The 'latest' version of D3DX12.H on the DirectX-Headers GitHub site is assuming you are using the Agility SDK 1.7 Preview which adds some new types like D3D12_GLOBAL_BARRIER. You should use the D3DX12.H from the release or perhaps this copy.
71,522,473
71,524,290
ZeroMemory a struct with std::string and assigning value to it has different behavior in VS2010 and VS2017
We are upgrading an old MFC project from VS2010 to VS2017, and we discovered a different behavior when assigning data to an std::string inside a struct which was cleared using ZeroMemory. I created a simple MFC program to replicate the issue. std::string getStrData() { std::string temp = "world"; return temp; } CMainFrame::CMainFrame() { struct mystruct{ std::string mystr_in1; std::string mystr_in2; }; std::string mystr_out = "hello"; mystruct* sttemp = new mystruct(); ZeroMemory(sttemp, sizeof(mystruct)); // <-- we think this is bad sttemp->mystr_in1 = mystr_out; // <-- VS2010: "hello" is assigned, but VS2017: garbage is assigned sttemp->mystr_in2 = getStrData(); // <-- VS2010 and VS2017: "world" is assigned } In VS2010, the value of mystr_out ("hello") is assigned properly to mystr_in1. However in VS2017, garbage data is assigned to mystr_in1. I read similar questions here in StackOverflow that doing ZeroMemory in this case destroys the std::string so we think this is the cause of the problem. But in mystr_in2, it is able to assign "world" properly in both VS2010 and VS2017. I have 2 questions about this behavior if anyone can explain. For the 1st case (mystr_in1), why is the code compiled in VS2010 and VS2017 have different behavior? Is there some kind of Project settings in VS2017 to fix this? When upgrading the old VS2010 project, we just opened the VS2010 solution in VS2017 and chose upgrade solution. (Most of our old projects have no problem by just doing this) For the 2nd case (mystr_in2), it's supposed to be the same(?) with the 1st case but the std::string assigned to it was returned from a function. How is this different with the 1st case which also assigns an std::string?
The code has never been correct. Initializing an object by writing literal zero values into memory doesn't have and never had1 any well defined behavior. For trivially copyable types you often get away with it, in practice, but the behavior is still undefined. The code in question, however, cannot claim that gray area for itself: mystruct isn't trivially copyable. The observed change in behavior might well be due to SSO (short string optimization), though it's moot to reason about a change in behavior that never had any well specified behavior to begin with. Luckily, the fix is simple: Just remove the ZeroMemory call. A default-constructed mystruct will have default-constructed std::string members, so there's no reason to "initialize" them again. 1 I believe, anyway. This is C++ after all, and it seems that its complexity has pretty much outgrown average mental capacities.
71,522,719
71,522,757
Error: Object(char message []) not compiling with Object("Text")
I am having an issue with trying to send a ("msg") from main to a Object(char arr[]). InputNum(char msg []) { cout << msg; cin >> _num; } int main() { InputNum num ("Enter a Number"); } The above throws an error from the g++ compiler: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings] So, I am sending a String in main to a char[ ] parameter. But I'm not sure why that is a problem. I was under the illusion that a char[ ] IS a String, which I guess is incorrect is incorrect. Any general advice on what and how to fix it, I would appreciate greatly. Also, code is inspired by p.44 "C++ In Action" by Bartosz Milewski (2001). Editted: greatly :p
You are trying (unknowingly) to make a string literal writable. C++ doesnt like this at all. You have to do void InputNum(const char msg []) { cout << msg; } this promises the compiler that you wont try to change the conents of 'msg'
71,522,737
71,546,426
Error while loading shared object file: No such file or directory
I am trying to generate a usable binary for GCBM, a C++ carbon accounting tool. The binary has been generated from a GitHub Action workflow which is available as an artifact here: https://nightly.link/HarshCasper/moja.canada/actions/runs/1999997115/GCBM.zip I downloaded the ZIP, unzipped it inside a gcbm directory, cd inside it, and tried launching the binary through: ./moja.cli I got the following error: ./moja.cli: error while loading shared libraries: libmoja.flint.so.1: cannot open shared object file: No such file or directory I have tried various ways to fix it by following other StackOverflow threads but nothing really has worked out. Can anyone please help me solve it?
Example, how to run GCBM/moja.cli with the ~40 internal shared libraries mkdir GCBM && cd GCBM/ unzip GCBM.zip chmod +x moja.cli ## create a script moja.sh to run moja.cli : #!/bin/sh export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH exec ./moja.cli ## make the script executable and run ./moja.sh
71,522,815
71,523,041
Why does the xorshift random number generator always seem to use these specific shifts?
I was going through a book that explained the xorshift algorithm (I know, basic stuff). Then, while searching a little bit more on the Internet, I found that all the basic examples seem to shift the bits right/left the same "amount" (13, 17, 5). For instance: struct xorshift32_state { uint32_t a; }; uint32_t xorshiftTransform(struct xorshift32_state *state) { uint32_t x = state->a; x ^= x << 13; x ^= x >> 17; x ^= x << 5; return state->a = x; } Is there a particular reason why in all examples they use 13, 17 and 5? Yep, I found other examples too, but this one keeps repeating, and I don't know if the numbers choice is trivial or not.
This is actually a lot more subtle and interesting than you might suspect! The xorshift random number generator has an interesting theoretical backstory. The use of shifts and XORs corresponds to performing a matrix-vector product where both the matrix and the vector are made of 0s and 1s. The specific matrices in question are derived based on the choices of shift sizes and the directions of those shifts. In order for the RNG to perform well (specifically, to not repeat any outputs until all possible values have been generated), the matrix derived by the shifts must be invertible. Most choices of shifts will not give an invertible matrix, and the author of xorshift ran a computer search to find all possible shift sizes that work. In the paper detailing the xorshift family of RNGs, the author detailed the specific choice of shifts you mentioned and says the following: It uses one of my favorite choices, [a, b, c] = [13, 17, 5], and will pass almost all tests of randomness, except the binary rank test in Diehard [2]. (A long period xorshift RNG necessarily uses a nonsingular matrix transformation, so every successive n vectors must be linearly independent, while truly random binary vectors will be linearly independent only some 30% of the time.) Although I have only tested a few of them, any one of the 648 choices above is likely to provide a very fast, simple, high quality RNG. So in a sense, these numbers satisfy the theoretical necessary conditions needed for the math to work out to make this a good RNG, and the author tested it and singled them out in the original paper, which is why I’m guessing they’re so widely used. But perhaps there’s an even better choice using other numbers from the paper that folks just haven’t gotten around to using yet?
71,522,834
71,523,040
Which C++20 standard library containers have a .at member access function?
Which C++20 standard library containers have a .at function? For example, at least std::map, std::unordered_map and std::vector do. What others are there? Is there some way to work this out without going through the 2000 page standard by hand?
I ended up grepping libstdc++ include directory for \bat( and that has given me: std::basic_string std::basic_string_view std::array std::vector std::vector<bool> std::unordered_map std::map std::dequeue I'm not sure if this is exhaustive. There is also rope and vstring but I don't think these are standard.
71,522,961
71,523,022
"undefined reference to `operator>>(std::istream&, Complex<int>&)" for template Complex<T>
My code: #include <iostream> using std::cin; using std::cout; using std::istream; using std::ostream; template<typename T> class Complex { T real, img; public: Complex():real(0), img(0){} friend istream& operator>>(istream& input, Complex& c1); friend ostream& operator<<(ostream& output, Complex& c1); Complex operator+(Complex& c1); }; template<typename T> istream& operator>>(istream& input, Complex<T>& c1) { cout<<"Real: "; input>>c1.real; cout<<"Imag: "; input>>c1.img; return input; } template<typename T> ostream& operator<<(ostream& output, Complex<T>& c1) { output<<c1.real<<"+"<<c1.img<<"i"; return output; } template<typename T> Complex<T> Complex<T>::operator+(Complex<T>& c1) { Complex temp; temp.real = this->real + c1.real; temp.img = this->img + c1.img; return temp; } int main() { Complex<int> cmp1; cin>>cmp1; return 0; } The error I'm getting is at cin>>cmp1 which is undefined reference to 'operator>>(std::istream&, Complex<int>&)'. But I can't find anything wrong in my code. The code works if I make complex a non-template class which uses double and remove all template-related code, so the definition of operator>>() is essentially correct. What changes when I make Complex a template?
Friend functions are not members so they aren't implicitly templates. Declaration there suggests existence of non-template operator for instantiated type Complex<int>. You may use template<typename U> friend istream& operator>>(istream& input, Complex<U>& c1); template<typename U> friend ostream& operator<<(ostream& output, Complex<U>& c1);
71,523,003
71,523,079
Iterating the creation of objects in C++
I want to be able to create N skyscrapers. Using an inputdata string, I would like to give them coordinate values of their X and Y positions. My main function I used "i" to demonstrate that I am trying to create as many skyscrapers as I can using the input data. Essentially, I would like to create N/3 skyscrapers and assign the input to coordinates for each. #include <iostream> #include <vector> #include <string> #include <math.h> using namespace std; vector<int> inputData = {1, 4, 10, 3, 5, 7, 9, 10, 4, 11, 3, 2, 14, 5, 5}; int N = inputData.size(); class Buildings{ public: int yCoordinateLow; int yCoordinateHigh; int xCoordinateLeft; int xCoordinateRight; }; int main(){ for(int i=0; i<N; i=i+3){ Buildings skyscraper; skyscraper.xCoordianteLeft = inputData.at(i); skyscraper.yCoordianteLow = 0; skyscraper.yCoordinateHigh = inputData.at(i+1); skyscraper.xCoordinateRight = inputData.at(i+2); } return 0; }
Jeff Atwood once said: use the best tools money can buy. And those aren't even expensive: Visual Studio community edition is free. Such a proper IDE will tell you that the skyscraper is unused except for the assignments. Since you probably want to do something with those skyscrapers later, you should store them somewhere, e.g. in another vector. int main() { vector<Buildings> skyscrapers; for (int i = 0; i < N; i = i + 3) { Buildings skyscraper{}; skyscraper.xCoordinateLeft = inputData.at(i); skyscraper.yCoordinateLow = 0; skyscraper.yCoordinateHigh = inputData.at(i + 1); skyscraper.xCoordinateRight = inputData.at(i + 2); skyscrapers.push_back(skyscraper); } return 0; } Other than that, I'd say the loop works fine as long as there are N*3 coordinates in the original vector. If you e.g. implement a game, you would probably not hard code the skyscraper coordinates in a vector but rather read that data from a file, potentially per level. Instead of doing all the error-prone coding, maybe you want to initialize the skyscrapers immediately vector<Buildings> skyscrapers = {{1,0,4,10}, {3,0,5,7}, {9,0,10,4}, {11,0,3,4}, {14,0,5,5}};
71,523,157
71,539,648
Thrust is very slow for array reduction
I am trying to use thrust to reduce an array of 1M elements to a single value. My code is as follows: #include<chrono> #include<iostream> #include<thrust/host_vector.h> #include<thrust/device_vector.h> #include<thrust/reduce.h> int main() { int N,M; N = 1000; M = 1000; thrust::device_vector<float> D(N*M,5.0); int sum; auto start = std::chrono::high_resolution_clock::now(); sum = thrust::reduce(D.begin(),D.end(),(float)0,thrust::plus<float>()); auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end-start); std::cout<<duration.count()<<" "; std::cout<<sum; } The issue is, thrust::reduce alone takes about 4ms to run on my RTX 3070 laptop GPU. This is considerably slower than code I can write based on reduction#4 in this CUDA reference by Mark Harris, which takes about 150microseconds. Am I doing something wrong here? EDIT 1: Changed high_resolution_clock to steady_clock. thrust::reduce now takes 2ms to run. Updated code is as follows: #include<chrono> #include<iostream> #include<thrust/host_vector.h> #include<thrust/device_vector.h> #include<thrust/reduce.h> int main() { int N,M; N = 1000; M = 1000; thrust::device_vector<float> D(N*M,5.0); int sum; auto start = std::chrono::steady_clock::now(); sum = thrust::reduce(D.begin(),D.end(),(float)0,thrust::plus<float>()); auto end = std::chrono::steady_clock::now(); auto duration = std::chrono::duration<double,std::ratio<1,1000>>(end-start); std::cout<<duration.count()<<" "; std::cout<<sum; } Additional information : I am running CUDA C++ on Ubuntu in WSL2 CUDA version - 11.4 I am using the nvcc compiler to compile: nvcc -o reduction reduction.cu To run: ./reduction
Am I doing something wrong here? I would not say you are doing anything wrong here. However that might be a matter of opinion. Let's unpack it a bit, using a profiler. I'm not using the exact same setup as you (I'm using a different GPU - Tesla V100, on Linux, CUDA 11.4). In my case the measurement spit out by the code is ~0.5ms, not 2ms. The profiler tells me that the thrust::reduce is accomplished under the hood via a call to cub::DeviceReduceKernel followed by cub::DeviceReduceSingleTileKernel. This two-kernel approach should make sense to you if you have studied Mark Harris' reduction material. The profiler tells me that together, these two calls account for ~40us of the ~500us overall time. This is the time that would be most comparable to the measurement you made of your implementation of Mark Harris' reduction code, assuming you are timing the kernels only. If we multiply by 4 to account for the overall perf ratio, it is pretty close to your 150us measurement of that. The profiler tells me that the big contributors to the ~500us reported time in my case are a call to cudaMalloc (~200us) and a call to cudaFree (~200us). This isn't surprising because if you study the cub::DeviceReduce methodology that is evidently being used by thrust, it requires an initial call to do a temporary allocation. Since thrust provides a self-contained call for thrust::reduce, it has to perform that call, as well as do a cudaMalloc and cudaFree operation for the indicated temporary storage. So is there anything that can be done? The thrust designers were aware of this situation. To get a (closer to) apples-apples comparison between just measuring the kernel duration(s) of a CUDA C++ implementation, and using thrust to do the same thing, you could use a profiler to compare measurements, or else take control of the temporary allocations yourself. One way to do this would be to switch from thrust to cub. The thrust way to do it is to use a thrust custom allocator. There may be a few other detail differences in methodology that are impacting your measurement. For example, the thrust call intrinsically copies the reduction result back to host memory. You may or may not be timing that step in your other approach which you haven't shown. But according to my profiler measurement, that only accounts for a few microseconds.
71,523,366
71,524,341
Aggregate values of same key in std::multimap and store in std::map
I essentially want to group the elements of the multimap by key, and obtain the new data structure as a map. the multimap: std::multimap<std::string,std::vector<int>> multiMap; VecA VecB ABC 10 30 ABC 10 30 DEF 20 20 the output required: std::map<std::string,std::vector<int>> map; VecA VecB ABC 20 60 DEF 20 20 The following code works for a std::multimap<std::string,int> std::vector<std::string> a = {ABC,ABC,DEF,GHI}; std::vector<int> b = {10,20,30,40}; std::multimap<std::string,int> multiMap; for (int i = 0; i < a.size(); i++) { multiMap.insert(std::pair<std::string,int >(a[i], b[i])); } std::map<std::string,int> map; std::for_each ( multiMap.begin(), multiMap.end(), [&map] (auto const & i) { map[i.first] += i.second; } ); I am unable to change the code in line 19 of the above block (i.e. in the lambda function) to extend in the case of std::multimap<std::string,std::vector<int>> to std::map<std::string,std::vector<int>>
If you want use Arithmetic operators Use valarray Demo: https://wandbox.org/permlink/SAnHNKNZ0UufqZsN #include <iostream> #include <string> #include <vector> #include <map> #include <valarray> #include <numeric> int main() { using key_type = std::valarray<int>; key_type b = {10,20,30,40}; auto containerToStr = [](const auto& cont) { return std::accumulate(std::begin(cont), std::end(cont), std::string{}, [](const auto& str, const auto& val){ return str + " " + std::to_string(val); }); }; std::multimap<std::string,key_type> multiMap; std::vector<std::string> a = {"ABC","ABC","DEF","GHI"}; for (size_t i = 0; i < a.size(); i++) { multiMap.insert(std::pair<std::string,key_type >(a[i], b)); } std::cout << "Before sum" << std::endl; for (const auto& p : multiMap) std::cout << p.first << " " << containerToStr(p.second) << std::endl; std::cout << std::endl; std::map<std::string,key_type> map; std::for_each( multiMap.begin(), multiMap.end(), [&map] (auto const & i) { // map[i.first] += i.second; // caution map[i.first] create an empty key_type if ( map.count(i.first) > 0) { map.at(i.first) += i.second; } else { map.insert({i.first, i.second}); } } ); std::cout << "After sum" << std::endl; for (const auto& p : map) std::cout << p.first << " " << containerToStr(p.second) << std::endl; } If you want use std::vector Define your sum function. Demo: https://wandbox.org/permlink/FteFkLfwQh0P4wzp #include <iostream> #include <string> #include <vector> #include <map> #include <numeric> int main() { using key_type = std::vector<int>; key_type b = {10,20,30,40}; auto containerToStr = [](const auto& cont) { return std::accumulate(std::begin(cont), std::end(cont), std::string{}, [](const auto& str, const auto& val){ return str + " " + std::to_string(val); }); }; std::multimap<std::string,key_type> multiMap; std::vector<std::string> a = {"ABC","ABC","DEF","GHI"}; for (size_t i = 0; i < a.size(); i++) { multiMap.insert(std::pair<std::string,key_type >(a[i], b)); } std::cout << "Before sum" << std::endl; for (const auto& p : multiMap) std::cout << p.first << " " << containerToStr(p.second) << std::endl; std::cout << std::endl; std::map<std::string,key_type> map; // Warning : naive function, to rework auto your_sum = [](const auto& cont1, const auto& cont2) { key_type result; const auto smaller = std::min(cont1.size(), cont2.size()); for ( size_t i = 0 ; i < smaller; i++) { result.push_back(cont1[i]+cont2[i]); } return result; }; std::for_each( multiMap.begin(), multiMap.end(), [&map,&your_sum] (auto const & i) { // map[i.first] += i.second; // caution map[i.first] create an empty key_type if ( map.count(i.first) > 0) { map.at(i.first) = your_sum(i.second, map.at(i.first)); } else { map.insert({i.first, i.second}); } } ); std::cout << "After sum" << std::endl; for (const auto& p : map) std::cout << p.first << " " << containerToStr(p.second) << std::endl; }
71,523,835
71,523,872
How can i read all files in directory in c++?
I want to read all files in specific directory. for example In directory a there are file1.text file2.txt a.txt c.txt I want to know how many words are included in each file. I made a code for a file. But I don't know how to automatically move on next file at same directory. int EBook::get_total_words() { ifstream ifs("inputs//a.txt"); int words = 0; string word; if (!ifs) { std::cout << "Unable to open file " << '\n'; exit(1); } while (ifs >> word) { ++words; } return words; }
With std::filesystem you can do this: std::string path_to_dir = '/some/path/'; for( const auto & entry : std::filesystem::directory_iterator( path_to_dir ) ){ std::cout << entry.path( ) << std::endl; }
71,523,854
71,523,971
How to mmap Eigen into shared memory?
I want to use Eigen library as my shared memory data structure (by mmap). here is my code: producer.cpp: #include<sys/mman.h> #include<sys/types.h> #include<fcntl.h> #include<string.h> #include<stdio.h> #include<unistd.h> #include <vector> #include <iostream> #include <string> #include "eigen3/Eigen/Dense" typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> eigen_matrix; using namespace std; int main(int argc,char **argv) { int fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 0777); size_t size = 100 * 100 * sizeof(typename eigen_matrix::Scalar); lseek(fd, size, SEEK_SET); write(fd,"",1); eigen_matrix* p =(eigen_matrix*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); p->resize(100, 100); (*p)(0, 0) = 1; double s; size_t count = 0; while (std::cin >> s && s != 0) { (*p)(count++, 0) = s; } printf("initialize over\n"); munmap(p, size); close(fd); } consumer.cpp: #include<sys/mman.h> #include<sys/types.h> #include<fcntl.h> #include<string.h> #include<stdio.h> #include<unistd.h> #include <vector> #include <iostream> #include <string> #include "eigen3/Eigen/Dense" using namespace std; typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> eigen_matrix; int main(int argc,char **argv) { int fd = open(argv[1], O_RDWR, 0777); size_t size = 100 * 100 * sizeof(typename eigen_matrix::Scalar); lseek(fd, size, SEEK_SET); eigen_matrix* p = (eigen_matrix*)mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); close(fd); printf("%zu %zu\n", p->cols(), p->rows()); cout << *p <<endl; // here crashed !! std::string s; while (std::cin >> s && s != "quit") { cout << *p << endl; } munmap(p, size); } As you can see in the code, consumer crashed on cout << *p << endl; could you help on this? Is there anything i ignored?
Dynamic Eigen matrices are like std::vector. They don't hold the actual data, they contain pointers to the data plus the size information. You mmapped the object, not the actual data. Something like this should work: Eigen::Index rows = 100, cols = 100; const void* space = mmap(NULL, rows * cols * sizeof(double), PROT_READ, MAP_SHARED, fd, 0); Eigen::MatrixXd::ConstMapType mapped = Eigen::MatrixXd::Map( static_cast<const double*>(space), rows, cols);
71,523,997
71,524,353
How to get a property name and offset in a class at compile time or runtime?
I have a class named SoftInfo. class SoftInfo { public: std::string m_strSoftName; std::string m_strSoftVersion; std::string m_strInstallLocation; } I want to export it to lua in a c++ program via sol3. I write something like this and I can use it in lua world. However, there are something unconvenient. I need to write the name and offset of any property of class SoftInfo. When I change the property name in SoftInfo, I also need to change the name in function Export. Besides, if the number of properties of SoftInfo is too large, it will be very hard to write the Export function manually. void Export(lua_state _state) { _state.new_usertype<SoftInfo>("SoftInfo", "m_strSoftName",&SoftInfo::m_strSoftName, "m_strSoftVersion",&SoftInfo::m_strSoftVersion, "m_strInstallLocation",&SoftInfo::m_strInstallLocation); } or void Export(lua_state _state) { sol::usertype<SoftInfo> usertype_table = _state.new_usertype<SoftInfo>("SoftInfo"); usertype_table["m_strSoftName"] = &SoftInfo::m_strSoftName; usertype_table["m_strSoftVersion"] = &SoftInfo::m_strSoftVersion; usertype_table["m_strInstallLocation"] = &SoftInfo::m_strInstallLocation; } I wonder is there a way to avoid these complicated work like macro that I can wirte something like this? If other solution can reduce the complicated manual working, it is not limited to the solution pattern I supplied below. class SoftInfo { public: //Macro or something defined here std::string m_strSoftName; std::string m_strSoftVersion; std::string m_strInstallLocation; } void Export(lua_state _state) { sol::usertype<ship> usertype_table = _state.new_usertype<SoftInfo>("SoftInfo"); for(auto [properties,offset]:Func(SoftInfo)) usertype_table[properties] = offset; }
What you're asking for is called static reflection. Unfortunately, C++ doesn't have that. However, with boost describe, you may get quite close #include<boost/describe.hpp> BOOST_DESCRIBE_STRUCT(SoftInfo, (), (m_strSoftName, m_strSoftVersion, m_strInstallLocation)) void Export(lua_state _state) { sol::usertype<SoftInfo> usertype_table = _state.new_usertype<SoftInfo>("SoftInfo"); using namespace boost::describe; using M = describe_members<SoftInfo, mod_any_access>; boost::mp11::mp_for_each<M>([&](auto d){ using D = decltype(d); usertype_table[D::name] = D::pointer; }); } BOOST_DESCRIBE_STRUCT has to be maintained manually by filling in all the members but Export will be automatically implemented.
71,524,337
71,524,402
what is the output of conditional operator with unary operator
I have the following code where behavior is not clear to me. Can some one please help how conditional operator evaluate the following code and output ans as 1 #include int main() { bool delayMessages=0; bool Delay = false; delayMessages += Delay ? 1 : -1; std::cout << "Hello world!"<<delayMessages; return 0; } Ans: Hello world!1 Can soemone please help how thsi code is evaluated "delayMessages += Delay ? 1 : -1;"
The expression on the right hand side is evaluated like an if-statement. if (Delay == true) return 1; else return -1; The result is then used for the += assignment. In the C++20 draft standard that's 7.6.19 (6) (Assignment and compound assignment operators) The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. [...] Since Delay == false, the return value of the ternary operator is -1. The fact that you're operating on a boolean instead of an int can make it look like you got the +1 back. Note that you get a compiler warning C4804: warning C4804: '+=': unsafe use of type 'bool' in operation Is it undefined behavior? No. 7.6.19 (6) (Assignment and compound assignment operators) [...] For += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type. and 7.3.8 (2) (Integral conversions) If the destination type is bool, see 7.3.14. which says 7.3.14 (1) (Boolean conversions) A prvalue of arithmetic, unscoped enumeration, pointer, or pointer-to-member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. So the -1 is converted to true and true prints as 1.
71,524,565
71,524,831
Can an iterator such as std::filesystem::directory_iterator be used outside of a loop?
I'm trying to understand how things like iterators can be used in c++, and would specifically like to understand std::filesystem::directory_iterator better. I understand the straight forward examples like this: #include <iostream> #include <filesystem> #include <string> void doSomething(std::string filename) { std::cout << filename; }; int main() { auto iterator = std::filesystem::directory_iterator("c:/somefolder"); for (auto& i : iterator) { doSomething(std::filesystem::path(i.path()).filename().string()); } } But lots of legacy code isn't made in a tight loop like that. Is it possible to use the directory_iterator in a way somewhat similar to WinAPI FindNextFile()? Something similar to this: std::string getNextFilename(std::string path) { // Notice the actual filesystem access code is neatly packed away in a replaceable function suitable for a HAL. static auto iterator = std::filesystem::directory_iterator(path); return std::filesystem::path(iterator.path()).filename().string(); } int main() { while (std::string fileName = getNextFilename("c:/somefolder")) { doSomething(fileName); } // or std::string fileFirst = getNextFilename("c:/somefolder"); std::string fileSecond = getNextFilename("c:/somefolder"); std::string fileLast = getNextFilename("c:/somefolder"); } Please answer: In general for iterators, can or can't they be used like this, and why? In specific how to perform this sort of directory lookup of one file/directory at a time. edit1: Clarified title.
It is easily possible to manually increment iterators (since that is what the range based for loop does as well). However you need to adjust the other code accordingly, as there is no operator bool for std::string. One possible solution (only slightly modifying the original code, which still includes all its issues) could look like this (using std::optional<std::string> to enable returning an "end" condition): #include <iostream> #include <filesystem> #include <string> #include <optional> void doSomething(std::string filename) { std::cout << filename; }; std::optional<std::string> getNextFilename(std::string path) { static auto iterator = std::filesystem::directory_iterator(path); if (iterator != std::filesystem::directory_iterator()) { auto filename = std::filesystem::path(iterator->path()).filename().string(); ++iterator; // advance iterator to next entry in directory return filename; // uses implicit constructor of `std::optional` } else { return {}; // return empty optional if we reached end of directory } } int main() { while (auto fileName = getNextFilename("c:/somefolder")) { doSomething(*fileName); // dereference optional to get value } // or auto fileFirst = getNextFilename("c:/somefolder"); auto fileSecond = getNextFilename("c:/somefolder"); auto fileLast = getNextFilename("c:/somefolder"); }
71,524,636
71,529,455
What am I missing in my custom std::ranges iterator?
I'd like to provide a view for a customer data structure, with it's own iterator. I wrote a small program to test it out, shown below. It I uncomment begin(), then it works. But if I use DummyIter, then I get a compile error. In my full program, I've implemented a full iterator but for simplicity, I narrowed it down to the necessary functions here. #include <iostream> #include <ranges> #include <vector> template<class T> struct DummyIter { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; DummyIter() = default; auto operator*() const { T t; return t; } auto& operator++() { return *this; } auto operator++(int val) { DummyIter tmp = *this; ++*this; return tmp; } auto operator==(const DummyIter& iter) const { return true; } }; template<class V> struct DummyView : std::ranges::view_interface<DummyView<V>> { //auto begin() const { return std::ranges::begin(v); } auto begin() const { return DummyIter<int>(); } auto end() const { return std::ranges::end(v); } V v; }; int main() { auto view = DummyView<std::vector<int>>(); view | std::views::filter([](auto i) { return i > 0; }); } I'm using GCC 11.1.0. What am I missing in my iterator for it to be ranges compliant? error: no match for 'operator|' (operand types are 'DummyView<std::vector<int> >' and 'std::ranges::views::__adaptor::_Partial<std::ranges::views::_Filter, main()::<lambda(auto:15)> >') 37 | view | std::views::filter([](auto i) { return i > 0; }); | ~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | std::ranges::views::__adaptor::_Partial<std::ranges::views::_Filter, main()::<lambda(auto:15)> > | DummyView<std::vector<int> >
The way to check this kind of thing for ranges is: Verify that your iterator is an input_iterator. Verify that your sentinel is a sentinel_for your iterator. Those are the checks that will tell you what functionality you're missing. In this case, that's: using I = DummyIter<int>; using S = std::vector<int>::const_iterator; static_assert(std::input_iterator<I>); // ok static_assert(std::sentinel_for<S, I>); // error And the issue there is that S isn't a sentinel_for<I> because it's not equality comparable. You need to know when the iteration stops, and you don't have that operator - your DummyIter<T> is comparable to another DummyIter<T>, but not to what you're returning from end(). So you either need to add another operator== to DummyIter<T>, or have DummyView<V>::end() return some kind of DummySentinel<V> that is comparable to DummyIter<T>. It depends on the real problem which is the better approach, there are examples of both in the standard library.
71,526,324
71,530,071
Exception with OpenCv DnnSuperResImpl (C++)
I have a problem with the upsample function from the dnnsuperres pack of OpenCV. I am transferring a bmp via a pipe from one application to another. The image resides in datamem, which is an unsigned char array. I use the pipe to transfer many other things, so I transfer the data in the most common datatype. If I do the following: cv::Mat matImg; matImg = cv::imdecode(cv::Mat(1, SizeToRead, CV_8UC1, datamem), -1); //-1==CV_LOAD_IMAGE_UNCHANGED imshow("SomeWindowName", matImg); This succeeds without a problem, the bitmap is shown correctly. If I now try to apply an upsampling: string path = "EDSR_x4.pb"; string modelName = "edsr"; int scale = 4; DnnSuperResImpl sr; sr.readModel(path); sr.setModel(modelName, scale); Mat outputImage; sr.upsample(matImg, outputImage); sr.upsampling() will thrown an exception. Unfortunately the exception info doesn't help me any further (cv::exception at memory location xyz, no additional info. The address seems reasonable). So I tried to simply load a bitmap from my hdd via cv::imread() and pass this to sr.upsample() and this works. I think it might be some format of the bitmap in datamem which is incompatible with sr.upsampling(). Therefore I tried to convert the bitmap to a png and pass it to the upsampling method, but the result was the same, I got the exception. The conversion I did like this: matImg = cv::imdecode(cv::Mat(1, SizeToRead, CV_8UC1, datamem), -1); //-1==CV_LOAD_IMAGE_UNCHANGED cv::Mat test(matImg.rows,matImg.cols,CV_8UC4, (cv::Vec4b*)matImg.data);//convert to png Afterwards I passed of course test to upsampling(), but I got the same exception. Does anyone have an idea what is causing the problem?
the DnnSuperResImpl will only accept 3 channel, BGR images, not your 4 channel bitmaps. convert your image to 3 channels, while decoding it: matImg = cv::imdecode(cv::Mat(1, SizeToRead, CV_8UC1, datamem), cv::IMREAD_COLOR); sr.upsample(matImg, outputImage); So far I found no documentation which says that it needs three channels. indeed, please raise an issue here
71,527,216
71,527,678
Class initialization fails with default constructor
I am learning about classes in C++ and I created a simple one that just creates an interval from int a to int b, using a dynamic int array. Here's the code: Interval::Interval() { a_ = 0; b_ = 0; interval = new int[2]; for (int i = 0; i <= 1; ++i) { interval[i] = 0; } } Interval::Interval(int a, int b) { if (a > b) Interval(); // doesn't seem to work? else if (a == b) { a_ = a; b_ = b; interval = new int[2]; for (int i = 0; i <= 1; ++i) { interval[i] = a; } } else { a_ = a; b_ = b; int size = b - a + 1; interval = new int[size]; for (int i = 0; i < size; ++i) { interval[i] = a++; } } } Interval::~Interval() { delete[] interval; cout << "Destructed\n"; } However, on this part here: if (a > b) Interval(); It doesn't seem to create it. Where am I wrong? Edit: As answered by molbdnilo, I was simply creating a separate object inside of the scope of the constructor without assigning or doing anything with it.
Noting that your default constructor is equivalent to Interval(0,0), you can reuse the non-default constructor instead, by forwarding to it: Interval::Interval() : Interval(0,0) {} Interval::Interval(int a, int b) : a_(a <= b ? a : 0), b_(a <= b ? b : 0) { if (a_ == b_) { interval = new int[2] {a_, a_}; } else { int size = b_ - a_ + 1; interval = new int[size]; for (int i = 0; i < size; ++i) { interval[i] = a_ + i; } } }
71,528,284
71,531,169
std::variant constructed from uint32_t prefers to hold int32_t than std::optional<uint32_t> using GCC 8.2.0
I've got the following code: #include <variant> #include <optional> #include <cstdint> #include <iostream> #include <type_traits> using DataType_t = std::variant< int32_t, std::optional<uint32_t> >; constexpr uint32_t DUMMY_DATA = 0; struct Event { explicit Event(DataType_t data) : data_(data) {} template <class DataType> std::optional<DataType> getData() const { if (auto ptr_data = std::get_if<DataType>(&data_)) { return *ptr_data; } return std::nullopt; } DataType_t data_; }; int main() { auto event = Event(DUMMY_DATA); auto eventData = event.getData<int32_t>(); if(!eventData) { std::cout << "missing\n"; return 1; } return 0; } The code is pretty simple and straightforward but I've encountered a weird behavior. When I compile it using gcc 8.2, the return code is 0 and there is no 'missing' message on the output console, which indicates that the variant was constructed using int32_t. On the other hand, when I compile it using gcc 10.2 it behaves the opposite way. I'm trying to figure out what has changed in standard which would explain this behavior. Here is also compiler explorer link: click
Here's a reduced version: constexpr int f() { return std::variant<int32_t, std::optional<uint32_t>>(0U).index(); } For gcc 8.3, f() == 0 but for gcc 10.2, f() == 1. The reasoning here is ultimately that variant initialization is... complicated. Originally, when C++17 shipped, the way that initializing a variant<T, U> from an expression E worked was basically by way of overload resolution to determine the index. Something like this: constexpr int __index(T) { return 0; } constexpr int __index(U) { return 1; } constexpr int which_index == __index(E); In this particular example, T=int32_t and U=optional<uint32_t>, and E is an expression of type uint32_t. This overload resolution would give us 0: the conversion from uint32_t to int32_t is better than the conversion from uint32_t to optional<uint32_t> (former is standard, latter is user-defined). You can verify this: constexpr int __index(int32_t) { return 0; } constexpr int __index(std::optional<uint32_t>) { return 1; } static_assert(__index(0U) == 0); But this rule has some surprising results. This was summarized in P0608, which included this example: variant<string, bool> x = "abc"; // holds bool This is because the conversion to bool is still a standard conversion, while the conversion to string was user-defined. Which is... very unlikely to be what the user intended. So the new rule ended up being (since modified further by way of P1957) that before we do the round of overload resolution to determine the index, we first prune the list of types to those that aren't narrowing conversions. That is, those types Ti from the pack for which: Ti x[] = {E}; is a valid expression. That is not valid anymore for bool x[] = {"abc"};, which is why the variant<string, bool> example now holds a string as desired. But for the original example here, int32_t x[] = {u}; (for u being an uint32_t) is not a valid declaration - this is a narrowing conversion (this would work for 0U directly, but we lose the constant-ness by the time we get to this check). Once this defect report was applied, we now have this overload set: // constexpr int __index(int32_t) { return 0; } // removed from consideration constexpr int __index(std::optional<uint32_t>) { return 1; } static_assert(__index(0U) == 1); Which is why your variant now holds an optional<uint32_t> rather than an int32_t. The code is pretty simple and straightforward I hope by now you recognize that attempting to initialize a variant<T, U> from a type that is neither T nor U isn't exactly simple or straightforward.
71,528,539
71,529,023
What happens to a reference when the object is deleted?
I did a bit of an experiment to try to understand references in C++: #include <iostream> #include <vector> #include <set> struct Description { int a = 765; }; class Resource { public: Resource(const Description &description) : mDescription(description) {} const Description &mDescription; }; void print_set(const std::set<Resource *> &resources) { for (auto *resource: resources) { std::cout << resource->mDescription.a << "\n"; } } int main() { std::vector<Description> descriptions; std::set<Resource *> resources; descriptions.push_back({ 10 }); resources.insert(new Resource(descriptions.at(0))); // Same as description (prints 10) print_set(resources); // Same as description (prints 20) descriptions.at(0).a = 20; print_set(resources); // Why? (prints 20) descriptions.clear(); print_set(resources); // Object is written to the same address (prints 50) descriptions.push_back({ 50 }); print_set(resources); // Create new array descriptions.reserve(100); // Invalid address print_set(resources); for (auto *res : resources) { delete res; } return 0; } https://godbolt.org/z/TYqaY6Tz8 I don't understand what is going on here. I have found this excerpt from C++ FAQ: Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object, just with another name. It is neither a pointer to the object, nor a copy of the object. It is the object. There is no C++ syntax that lets you operate on the reference itself separate from the object to which it refers. This creates some questions for me. So, if reference is the object itself and I create a new object in the same memory address, does this mean that the reference "becomes" the new object? In the example above, vectors are linear arrays; so, as long as the array points to the same memory range, the object will be valid. However, this becomes a lot trickier when other data sets are being used (e.g sets, maps, linked lists) because each "node" typically points to different parts of memory. Should I treat references as undefined if the original object is destroyed? If yes, is there a way to identify that the reference is destroyed other than a custom mechanism that tracks the references? Note: Tested this with GCC, LLVM, and MSVC
The note is misleading, treating references as syntax sugar for pointers is fine as a mental model. In all the ways a pointer might dangle, a reference will also dangle. Accessing dangling pointers/references is undefined behaviour (UB). int* p = new int{42}; int& i = *p; delete p; void f(int); f(*p); // UB f(i); // UB, with the exact same reason This also extends to the standard containers and their rules about pointer/reference invalidation. The reason any surprising behaviour happens in your example is simply UB.
71,528,931
71,529,033
c++ std::fstream. How do I read a number at the start of the line (a float or an int), and then skip to the next? Using named variables so no loop
I have a text file in the following format: 100 #gravity 5000 #power 30 #fulcrum I want to assign these values to named variables, like so: void Game::reloadAttributes() { float test1, test2, test3; string line; std::fstream file; file.open("attribs.txt"); if (file.is_open()) { cin >> test1; file.ignore(50, '\n'); cin >> test2; file.ignore(50, '\n'); cin >> test3; file.ignore(50, '\n'); file.close(); } else { cout << "\n****Couldn't open file!!****\n" << endl; } cout << ">>>> " << test1 << ", " << test2 << ", " << test3 << endl; } Of course, these aren't destined for the local test variables, but in fields belonging to the Game class, just using these to test its reading correctly. The program just hangs at cin >> test1. Ive tried using getLine(file, line) just beforehand, that didnt work. What am I doing wrong? Cheers
An object of type istream (in this case cin) takes user input. So of course the program will wait for you to input a value and then store it inside test1, test2, and test3 respectively. To fix your issue, just replace cin with file as such: file >> test1; file.ignore(50, '\n'); file >> test2; file.ignore(50, '\n'); file >> test3; file.ignore(50, '\n'); file.close(); Output: >>>> 100, 5000, 30
71,529,124
71,603,895
SYCL program working using VS Debugger but not when running the .exe
I am trying to build and run a simple SYCL program from this book. Here it is: #include <CL/sycl.hpp> #include <iostream> using namespace sycl; const std::string secret { "Ifmmp-!xpsme\"\012J(n!tpssz-!Ebwf/!" "J(n!bgsbje!J!dbo(u!ep!uibu/!.!IBM\01" }; const auto sz = secret.size(); int main(int argc, char* argv[]) { queue Q; char* result = malloc_shared<char>(sz, Q); std::memcpy(result, secret.data(), sz); Q.parallel_for(sz, [=](auto& i) { result[i] -= 1; }).wait(); std::cout << result << "\n"; return 0; } I am using Visual Studio 2019 and I am compilating with Intel oneAPI DPC++ 2022. If I run the Visual Studio Debugger, everything is working, I am obtaining as output: "Hello World! I'm sorry, Dave. I'm afraid i can't do that. - HAL" But if I am executing the .exe file that I just have built from the command prompt, nothing is happening... The program is executing itself, nothing is given as output, and I receive no error either. I tried to put some printf everywhere to see where to problem could come from. If I put a printf right just after "queue Q;" I wouldn't be able to see it when I run the .exe file. From what I have read the problem comes from the initialization of my object Q. I replaced "queue Q;" by "queue Q(default_selector{});" but it didn't solve the problem. EDIT : I have simply reduced the code to the following: #include <CL/sycl.hpp> #include <iostream> using namespace sycl; int main(int argc, char* argv[]) { std::cout << "Beginning of the program.\n"; queue Q; // The problem appears to come from this line std::cout << "End of the program.\n"; system("pause"); return 0; } Here is the output when I am launching the program in the Visual Studio Debugger: > Beginning of the program. > End of the program. > > Sortie de C:\Users\...\test.exe (processus 8108). Code : 0. > Press any key to continue . . . Here is the output when I am calling the .exe from the command prompt: > C:\Users\...\Release>test.exe > Beginning of the program. > > C:\Users\...\Release> I have noticed that during the short time when the program is running in the command prompt (something like one second), I saw that the program Windows Problem Reporting ran in the Task Manager. Than it vanished as soon as the program apparently finished to compute. EDIT 2 : Here is what happens if I am looking for the device used. With the following code: #include <CL/sycl.hpp> #include <iostream> using namespace sycl; int main(int argc, char* argv[]) { default_selector device_selector; std::cout << "default_selector has been defined.\n"; auto defaultQueue = queue(device_selector); std::cout << "default_queue has been defined.\n"; std::cout << "Running on " << defaultQueue.get_device().get_info<info::device::name>() << "\n"; system("pause"); return 0; } I get this output from the Visual Studio debugger: > Beginning of the program... > default_selector has been defined. > default queue has been defined. > Running on Intel(R) Core(TM) i5-3337U CPU @ 1.80GHz > Press any key to continue... And this when I am executing the .exe from the commande prompt (doing this in administrator or not doesn't change anything): > C:\Users\...\Release>test.exe > Beginning of the program... > default_selector has been defined. > > C:\Users\...\Release>
The answer has been brought by the Intel Developer Software Forums. Although the compiler has been well installed on my machine, the oneAPI environment had not be configured yet. This is why it couldn't work when running the .exe in the Windows command prompt. I had to run the batch file setvars.bat that was at the adress C:\Program Files (x86)\intel\oneAPI then it worked!
71,529,364
71,544,923
execve() is not executing the script when trying to run a script using it
I wanna run a script using execve(). in the following code, I am printing environment variables in c++ code then I pass the output of those to a script called "usrscript" to print them there but the execve() is not executing the script. ` #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <iostream> #include <stdio.h> using namespace std; int main(int argc, char *argv[], char * envp[]){ char arg1[100]={}; char arg2[100]={'\0'}; char arg3[100]={}; for (int i=0 ; envp[i] != NULL; i++){ if('U'==envp[i][0] && 'S'==envp[i][1] && 'E'==envp[i][2] && 'R'==envp[i][3] && '='==envp[i][4]){ for(int j=5 ;envp[i][j] != '\0';j++ ){ arg1[j-5] = envp[i][j]; } cout<<arg1<<endl; } if('P'==envp[i][0] && 'A'==envp[i][1] && 'T'==envp[i][2] && 'H'==envp[i][3]){ for(int j=5 ;envp[i][j] != '\0';j++ ){ arg2[j-5] = envp[i][j]; } cout<<arg2<<endl; } if('T'==envp[i][0] && 'E'==envp[i][1] && 'R'==envp[i][2] && 'M'==envp[i][3]){ for(int j=5 ;envp[i][j] != '\0';j++ ){ arg3[j-5] = envp[i][j]; } cout<<arg3<<endl; } } char cmd[]="./usrscript.sh"; char scr[] ="usrscript"; char os[]="OS2022=5ma32zw"; char *const vectorArg[] = {scr,arg1,arg2,arg3,NULL}; char *const vectorEnv[]= {os,NULL}; execve(cmd,vectorArg,vectorEnv); cout<<"Failed\n"; return 0;} the script im passing to is : #!usr/bin/bash echo "hello" for var in "$@" do echo "$var" done echo $OS2022 echo $TERM echo $PATH echo $USER I have tried to look if I am passing incorrect values to execve(), but I could not find anything. Any suggestion will be helpful.
The problem was solved by replacing #!usr/bin/bash with #!/bin/bash in the script.
71,529,704
71,529,705
Compiler variance for overloading over array reference parameters
The following program is, as expected, accepted by both GCC, Clang and MSVC (for various compiler and language versions): // #g.1: rvalue reference function parameter constexpr bool g(int&&) { return true; } // #g.2: const lvalue reference function parameter constexpr bool g(int const&) { return false; } static_assert(g(0), ""); // OK: picks #g.1 The similar case but for overloads over an array {rvalue, const lvalue} reference parameter is, however, rejected by GCC, whilst it is accepted by Clang and MSVC: #include <cstddef> // #f.1: rvalue ref overload template<std::size_t size> constexpr bool f(int (&&)[size]) { return true; } // #f.2: lvalue ref overload template<std::size_t size> constexpr bool f(int const (&)[size]) { return false; } static_assert(f({1, 2, 3}), ""); // Clang: OK (picks #f.1) // MSVC: OK (picks #f.1) // GCC: Error (picks #f.2) DEMO. At first glance this looks like a GCC bug, but I'd like to be sure. Question Which compiler(s) is(/are) right here?
GCC is wrong Since the argument is an initializer list, special rules apply, as per [over.ics.list]/1: When an argument is an initializer list ([dcl.init.list]), it is not an expression and special rules apply for converting it to a parameter type. As the parameter type for both overloads are references types, [over.ics.list]/9 applies [emphasis mine]: Otherwise, if the parameter is a reference, see [over.ics.ref]. [Note 2: The rules in this subclause will apply for initializing the underlying temporary for the reference. — end note] Albeit non-normative, this means that the call f({1, 2, 3}) for both of the candidate functions is (as per [over.ics.list]/6) as if template<typename T> using type = T; f(type<int[3]>{1, 2, 3}); // prvalue array [over.ics.ref], particularly [over.ics.ref]/3, simply covers that this kind of prvalue argument can bind directly both to an rvalue reference or to a const lvalue reference, meaning both candidates are viable candidates. We turn to [over.ics.ran]/3.2.3: /3.2 Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if [...] /3.2.3 S1 and S2 include reference bindings ([dcl.init.ref]) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference Thus, GCC is wrong to pick the const lvalue reference overload #f.2, as #f.1 is the best viable function. We may note that all compilers agree on the #f.1 overload if we explicitly pass an rvalue array instead of using an initializer list (DEMO): template<typename T> using type = T; // All compilers agree: OK static_assert(f(type<int[3]>{1, 2, 3})); GCC's invalid behavior in the original example is thus arguably specifically due to how GCC treats initializer list arguments for candidate functions whose corresponding function parameter type is of array reference type. Bug report Bug 104996 - Overload resolution over rvalue/const lvalue array reference parameters for an init. list argument incorrectly picks the const lvalue ref. overload
71,529,777
71,532,505
Displaying a C++ class via QML in QtQuick2
I am working on a QtQuick 2 application (Qt version 6.2.3). I created one C++ class (let's call this class "Example") that contains the data that my application should deal with. This class can be instantiated several times, representing different datasets to be displayed. class ExampleObject : public QObject { Q_OBJECT Q_PROPERTY(QString property1 MEMBER property1 CONSTANT) ... public: QString property1; }; Q_DECLARE_METATYPE(ExampleObject*) I want to be able to display instances of this class via QML, therefore I created a "Example" custom component with a property pointing to the Example C++ object containing the data I want to display. ExampleComponent { property var exampleCppObject // exampleCppObject is a pointer to an instance of ExampleObject Label { text: exampleCppObject.property1 } } To be able to change the Example instance used by the QML component, I created functions to "reinitialize" and "update" the component: ExampleComponent { property var exampleCppObject // exampleCppObject is a pointer to an instance of ExampleObject property string textToDisplay function update() { textToDisplay=Qt.binding(() => exampleCppObject.property1); } function reinitialize() { textToDisplay="" } Label { text: textToDisplay } } I call these functions after changing or deleting the Example object pointed by ExampleCppObject, and this works quite fine. But I feel like this isn't best practice, and it seems to me that I am doing things wrong. What are better ways of connecting C++ to QML, in the situation I described? Edit: my main.cpp essentially consists in: MainModel mainModel; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("mainModel", &mainModel); engine.load(QStringLiteral("qrc:/main.qml")); Where mainModel is an object which can create different instances of ExampleObject while the application is running.
You can optimize the binding textToDisplay such that you don't have to call the upate and reinitialize functions, which seems to be the question you are after: property var exampleCppObject property string textToDisplay : exampleCppObject ? exampleCppObject.property1 : "" In case you need more complex logic in the future, you can also use braces: property string textToDisplay: { console.log("log me everytime the binding is reevalutated") if(condition1) return "invalid" else if(condition2) return exampleCppObject.property2 else return exampleCppObject.property1 } The best part of this, is that QQmlEngine actually reevaluates the binding for every property that is used in this binding (which has a notify signal), so if crafted correctly, you can largely leave the binding alone (meaning you don't need the update and reinitialize function)
71,529,819
71,530,105
Contradicting definition of references
I am learning about references in C++. In particular, i have learnt that references are not actual objects. Instead they refer to some other object. That is, reference are just alias for other objects. Then i came across this which says: Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object, just with another name. It is neither a pointer to the object, nor a copy of the object. It is the object. There is no C++ syntax that lets you operate on the reference itself separate from the object to which it refers. I get that the above quote means that we can't operate on the reference itself separate from the object to which it refers but it still seems to imply that "a reference is an object". Also, i have come across the the sentence given below: In ISO C++, a reference is not an object. As such, it needs not have any memory representation. I don't have a link to this 2nd quote but i read it in one of SO's post somewhere. My question is that assuming the second quote is also from the standard(which may not be the case), doesn't these 2 quoted statements contradict each other. Or at least the first quote is misleading. Which one is correct. My current understanding(by reading books like C++ Primer 5th edition) is that references are an alias for objects. Which leads me to the thinking that they should not take any space in memory.
Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object, just with another name. ... Notes are informal and usually should not to be interpreted as strict rules. If an interpretation contradicts with standard rules, then that interpretation is wrong. References and objects are different kinds of entities. A reference is not an object distinct from the one that it names. It isn't possible to form a pointer to a reference. A "pointer to reference" isn't even a valid type category. The note is trying to say that reference "is" the object which it names in the sense that using the reference is using the referred object. I was thinking of confirming that whether or not references take any space References take space or they don't take space. It's up to the language implementation to figure out whether it needs space in each case. Standard quote: [dcl.ref] It is unspecified whether or not a reference requires storage Outside of standard specifications, if you want an example of reference using space, try adding a reference member to a class and you are very likely to observe that the size of the class increases. since pointers take space then reference should also take space. ... Pointers do take space in the abstract machine that the standard specifies. But if you never observe the storage, then it's entirely possible that the storage never exists in practice. A significant difference between references and pointers is that you cannot observe the storage of a reference directly. Philosopher: "If a tree falls in an abstract machine and no one is around to observe it, does it have an effect?" Optimiser: "Not if I can help it."
71,530,023
71,531,069
Why images can be uploaded with char array but not with equal std::istringstream in C++?
Consider the code below for a second: char buffer[4000]; size_t bytes = recv(fd, buffer, 4000, 0); write(pipefd[1], buffer, bytes); close(pipefd[1]); wait(NULL); Here I read fd, write data to the pipe and close the pipe. This allows to eventually upload tiny images that can be rendered. However, if I do everything the same, only replace char array with std::istringstream, as in the example below: char buffer[4000]; size_t bytes = recv(fd, buffer, 4000, 0); std::istringstream data(buffer); write(pipefd[1], data.str().c_str(), bytes); close(pipefd[1]); wait(NULL); Then image is uploaded but cannot be rendered. (Via pipes this C++ program communicates with a php-cgi script). Also: if (strcmp(data.str().c_str(), buffer) == 0) // returns true I am very curious as to why this could be the case.
std::istringstream data(buffer); This assumes buffer is a null-terminated string. Binary data typically contains 0x00 bytes, thus you would end up truncating the buffer contents. Use this instead: std::istringstream data(std::string(buffer, bytes), std::ios::binary);
71,530,163
71,533,834
detect 16 bit checksum
hi guys recently im working on reverse engineering a device but now after several weeks hard working i got into checksum calculating problem ! the data is 8 of 16 bit data, the last one is 16bit checksum. here is example of data : 0x0400 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4000 0x0301 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x8100 0x0302 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x8203 0x0303 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4303 0x0304 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x8405 0x0305 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4505 0x0306 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4606 0x0307 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x8706 0x0308 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x8809 0x0309 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4909 0x030A 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4A0A i hope you can help to detect the checksum algorithem
Looks like CRC-16/MODBUS, at least the first three match: https://crccalc.com/?crc=000d000000000100000200000000&method=CRC-16/MODBUS&datatype=hex&outtype=0 https://crccalc.com/?crc=010d000000000100000200000000&method=CRC-16/MODBUS&datatype=hex&outtype=0 https://crccalc.com/?crc=020d000000000100000200000000&method=CRC-16/MODBUS&datatype=hex&outtype=0 I didn't check others, but I assume they will too.
71,530,661
71,530,771
Is there a way i could end a loop with a char in c++?
I am new to programming, and I am currently trying to figure my way around C++. I am working on a program that will display basic information about employees to the users, and I want the program to end when the users entered a char. However, while working through it, I encountered a problem. When I enter the char (x), it somehow looped from 1-120 (as you seen in the counter below), but when I entered its ASCII number (120), it ended the program as intended. Can anyone explain it to me and what are the possible solutions? #include <iomanip> #include <iostream> using namespace std; class Employee { public: int Age; string Name; int ID; void information() { cout << "Name: " << Name << endl; cout << "Age: " << Age << endl; cout << "ID: " << setfill('0') << setw(3) << ID << endl; } Employee(string name, int age, int id) { Name = name; Age = age; ID = id; } }; void createProfile() { int age; int id; string name; cout << "Enter the Employee Name: "; cin >> name; cout << "Enter the Employee Age: "; cin >> age; cout << "Enter the Employee ID: "; cin >> id; } int main() { int num, counter; const char stop = 'x'; cout << "Choose an Employee " << endl; cout << "001 Jack" << endl; cout << "002 Susan" << endl; cout << "003 to create profile" << endl; cout << "Press x to Exit"; for (num = 0; num != stop; num++) { cout << "\n\nEnter the Employee ID: "; cin >> num; counter += 1; if (num == 001) { Employee jack = Employee("Jack", 25, 001); jack.information(); } else if (num == 002) { Employee jack = Employee("Susan", 23, 002); jack.information(); } else if (num == 003) { createProfile(); } else { cout << "Input invalid"; } } cout << "\n" << counter; }
Yes, of course. In C/C++, char is a type that can be represented either by its character value ('A', for example) or its numeric value (65). However, a digit's numeric value does not equal to itself. '1' == 49 120 is the ASCII value of lower case x and since you loop with an int, it is logical that it will end up working in ways you do not expect it to work. You can change your for (num = 0; num != stop; num++) to for (num = 0; ch != stop; num++) and of course ch should be declared as char before your loop. Also, make sure that you replace cin >> num; with cin >> ch;
71,530,932
71,531,100
Best way to parallelize this for loop with multiple threads
I currently have a code block like this UINT8* u = getResult(); for (UINT64 counter = 0; counter < MaxCount; counter++) { for (UINT64 index = 0; index < c_uOneMB; ++index) { *u++ = genValue(); } } Now in order to make this run faster. I am doing something like this. Basically splitting the inner thread into a method. However I have two concerns which I am not sure how to tackle. *u++ how do I handle that? Before calling doSomethingElse() all the threads need to .join() Any suggestions on how to accomplish that? void doSomething(UINT8* u) { for (UINT64 index = 0; index < c_uOneMB; ++index) { *u++ = genValue(); } } UINT8* u = getResult(); for (UINT64 counter = 0; counter < MaxCount; counter++) { std::thread t(doSomething,u); } doSomethingElse();
With little details you have provided I can give only this: std::generate_n(std::execution::par, getResult(), MaxCount * c_uOneMB, genValue); https://en.cppreference.com/w/cpp/algorithm/generate_n https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag
71,531,268
71,531,567
code is Not returning the correct character in cpp
Question: First uppercase letter in a string ( Recursive) Doubt: why this code is not returning the correct character even though it is entering in the if clause at correct time(when the letter is in uppercase). I have added these cout statements for debuging purpose only. # include <bits/stdc++.h> using namespace std; char UpperCase(string str, int i){ cout<<" str "<<i<<" "<<str[i]<<endl; if(i==str.length()){ return '0'; } if(str[i]>=65 && str[i]<=90 ){ char r=str[i]; cout<<" r "<<i<<" "<<r<<endl; return r; } UpperCase(str, i+1); } int main(){ string str; char r; cout<<"Enter string : "; cin>>str; r=UpperCase(str,0); cout<<r<<endl; return 0; } output Enter no of element : geeksforgeeKs str 0 g str 1 e str 2 e str 3 k str 4 s str 5 f str 6 o str 7 r str 8 g str 9 e str 10 e str 11 K r 11 K ö Expected K (instead of ö)
I'm assuming this is an academic exercise. No one would actually implement this task using recursion (nor would they use magic numbers, the plague known as <bits/stdc++.h>, a dreadful practice common on junk "competitive" programming sites, etc.) That said, a very common mistake made by students when learning recursion is failing to realize that function conveying their results by return-value need to be reaped from the recursed call. You've fallen victim to that mistake here. Stripping the debugging statements and just looking at the code itself: char UpperCase(string str, int i) { if (i == str.length()) { return '0'; } if (str[i] >= 65 && str[i] <= 90) { return str[i]; } UpperCase(str, i + 1); // <===== HERE } Note that UpperCase returns a char (or at least it claims to). But in the recursed case you're not reaping that result. In fact, you're not returning anything . This is not only a logical bug, it also leads to undefined behavior. Anyone that invokes this function to reap its result and does not fall into one of the other two targeted exit conditions immediately will have no specified result. Your compiler will tell you this if you pay attention to its warnings: warning: control reaches end of non-void function [-Wreturn-type] The simplest way to address this is to remember what your function is supposed to return, and then make sure it returns it. char UpperCase(string str, int i) { if (i == str.length()) { return '0'; } if (str[i] >= 65 && str[i] <= 90) { return str[i]; } return UpperCase(str, i + 1); // <===== FIXED }
71,531,333
71,547,653
How set CMake to find a local package FFmpeg?
I am trying write CMakeLists with FFmpeg package, with compile on Windows and Linux. First downloaded from FFmpeg-Builds shared releases I imagine the structure of the project like this: <project root> deps/ ffmpeg/ win-x64/ incluve/ lib/ bin/ linux-x64/ incluve/ lib/ bin/ src/ CMakeLists.txt How to help CMake find libraries: avcodec, avformat, avutil, etc? Maybe in the folder lib/pkgconfig using PkgConfig it is possible to specify the path. But I dont know how
The following worked well for me on Linux with cmake. You will have to find the equivalents for Windows. I used ffmpeg on Windows, but without cmake (i.e. directly in a Visual Studio project). Install pkg-config, nasm: sudo apt-get install -y pkg-config sudo apt-get install nasm Download ffmpeg source code: https://ffmpeg.org/download.html Build ffmpeg and install it: tar -xvf <downloaded_filename> cd /root/folder/with/ffmpeg/src ./configure make sudo make install Add the following to your CMakeLists.txt: In the beginning: find_package(PkgConfig REQUIRED) pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavdevice libavfilter libavformat libavcodec libswresample libswscale libavutil ) set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) In the linker area: target_link_libraries(${PROJECT_NAME} PUBLIC PkgConfig::LIBAV)
71,531,724
71,533,065
msvc std::lower_bound requires const operator*
I am getting a Error C2678 binary '*': no operator found which takes a left-hand operand of type 'const _InIt' (or there is no acceptable conversion) it is thrown by this code in MSVC (2022, V17.1) <algorithm> header. template <class _FwdIt, class _Ty, class _Pr> _NODISCARD _CONSTEXPR20 _FwdIt lower_bound(_FwdIt _First, const _FwdIt _Last, const _Ty& _Val, _Pr _Pred) { ... const auto _UMid = _STD next(_UFirst, _Count2); if (_Pred(*_UMid, _Val)) { // try top half The second line throws the error because of the const on the line above. The iterator I am passing in, is a custom LegacyRandomAccessIterator over a "flat-file" and its operator* looks like this: value_type operator*() { return current(); } ... ValueType current() { if (!cur_valid_) { cur_ = ffdb_->get_record(pos_); cur_valid_ = true; } return cur_; } In other words, I can't just mark my operator* as const because it's not, and can't be really - It's doing loading of a buffered set of records from disk, and that's not a const operation in a the current design. I implemented a "dummy" const version to prove that was the problem: value_type operator*() const { return value_type{}; } Error is gone, but clearly this doesn't do anything. libstdc++ doesn't have this expectation of a const operator*. (I haven't tested libc++) Is this solvable, without some major redesign of my iterator? Is it reasonable for MSVC's implementation to have this expectation?
std::lower_bound takes a Cpp17ForwardIterator, which must also be a Cpp17InputIterator. The Cpp17InputIterator requirements include: Expression Return type *a reference, convertible to T Here, a is a "value of type X or const X", so MSVC is justified in requiring a const-qualified unary indirection operator; the "or" means that the code using the iterator can use either, and the author of the iterator has to support both. (Note that Cpp17InputIterator differs from Cpp17OutputIterator, where the required operation is *r = o, with r a non-const reference, X&.) So your operator* should have const qualification, and return a reference; specifically, a reference to T or const T (this is a Cpp17ForwardIterator requirement). You can satisfy this straightforwardly with using reference = const T& and by making cur_ and cur_valid_ mutable. The use of mutable here is entirely legitimate; since operator*() const is idempotent, it is "logically const" and the modifications to the data members are non-observable.
71,532,341
71,547,147
How to use MPI_BCast with dynamic array of own datatype objects
There was a problem with passing dynamic array of object pointers via MPI_BCast(...). When I try to send array that I got error ended prematurely and may have crashed. exit code 0xc0000005. If I use MPI_BCast(...) with one object (like this MPI_Bcast(myObjArray[0], dataTypeMyObject, 1, 0, MPI_COMM_WORLD);) it work correctly. What I need to change in my implementation to send the whole array? Here is the code of my classes class Vector3 final { public: double x; double y; double z; //...(methods) } class MyObject final { public: Vector3 Force; Vector3 Speed; //...(methods) }; Here is a code of datatype init MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Datatype dataTypeVec3; int lenVec3[3] = { 1, 1, 1 }; MPI_Aint posVec3[3] = { offsetof(class Vector3, x),offsetof(class Vector3, y), offsetof(class Vector3, z) }; MPI_Datatype typVec3[3] = { MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE }; MPI_Type_create_struct(3, lenVec3, posVec3, typVec3, &dataTypeVec3); MPI_Type_commit(&dataTypeVec3); MPI_Datatype dataTypeMyObject; int lenMyObject[2] = { 1, 1 }; MPI_Aint posMyObject[2] = { offsetof(class MyObject, Force),offsetof(class MyObject, Speed)}; MPI_Datatype typMyObject[2] = { dataTypeVec3, dataTypeVec3}; MPI_Type_create_struct(2, lenMyObject, posMyObject, typMyObject, &dataTypeMyObject); MPI_Type_commit(&dataTypeMyObject); Here is a part of the code with MPI_BCast(...) MyObject** myObjArray = new MyObject * [10]; for (int i = 0; i < 10; ++i) { myobjArray[i] = new MyObject(); } if(rank == 0) myObjArray[0]->Speed = {5, 0, 0}; MPI_Bcast(myObjArray, 10, dataTypeMyObject, 0, MPI_COMM_WORLD); // Problem is here if(rank != 0) std::cout << "rank = "<< rank << " and speed.x = " << myObjArray[0].Speed.x << std::endl;
MPI_Bcast() expects that the input elements are continuous in memory, i.e. that the 10 MyObject instances are located "behind each other" in memory. But in your case you pass in an array of pointers into MPI_Bcast(), but MPI_Bcast() will not dereference the individual pointers. Instead, try MyObject * myObjArray = new MyObject[10]; // ... initialize objects on rank 0 MPI_Bcast(myObjArray, 10, dataTypeMyObject, 0, MPI_COMM_WORLD);
71,532,344
71,534,844
Getting very big error trying compile hello world | MINGW
Something happened to my compiler, and now I can't even compile hello world. Here's a link to error that I'm getting https://pastebin.com/HtyUdz6f , looks like my std libraries broken or something. How I can fix this problem ? #include <iostream> using namespace std; int main() { cout<<"Hello World"; return 0; }
This code compiles and runs on other C++ compilers, therefore the problem is likely caused by the compiler, not by the program itself. MinGW-w64 8.1.0 has not been updated since 2018, and will most likely stay without updates in the near future. Therefore, the software likely no longer works on modern software/operating systems. You may need to use a different compiler such as Visual Studio. If you are not able to use a different compiler, deleting, then reinstalling MinGW-w64 8.1.0 may solve the issues with the compiler.
71,532,567
71,532,910
Writing a function to find largest number from array in a text file
I can write a program to find the largest and smallest value in main, but I do not know how to do this in a separate function and for the numbers to be gotten from a file.My task is to enter numbers in an array which will be stored in a file and then the largest of those numbers needs to be found. I can write separate programs to do each, but I cannot combine them. #include <iostream> #include <fstream> #include <ostream> using namespace std; int findLargest(); int main() { ofstream outputFileStream("numbers.dat"); int num; for (int i = 0; i < 5; i++) { cout << "please enter number to be written to file " << i << endl; cin >> num; outputFileStream << num << endl; cout << findLargest; } } int findLargest() { int numbers[5]; int smallest = 0; int largest = 0; int temp = 0; for (int i = 0; i < 5; i++) { cout << "please enter numbers" << i + 1 << endl; cin >> numbers[i]; } smallest = numbers[0]; largest = numbers[0]; for (int i = 1; i < 5; i++) { temp = numbers[i]; if (temp > largest) largest = temp; } cout << "largest number is " << largest << endl; }
There are sooo many ways to do this. Here's one: void Find_Largest(std::ostream& output_file) { int smallest = 0; int largest = 0; std::cout << "Please enter number 1:\n"; std::cin >> smallest; largest = smallest; output_file << smallest << "\n"; for (int i = 1; i < 5; ++i) { std::cout << "Please enter number " << i << "\n"; int number; std::cin >> number; if (number < smallest) smallest = number; if (number > largest) largest = number; output_file << number << "\n"; } std::cout << "Largest is: " << largest << "\n"; std::cout << "Smallest is: " << smallest << "\n"; } int main() { ofstream outputFileStream("numbers.dat"); Find_Largest(outputFileStream); return 0; } In the above code, the output file is created in main and passed to the function Find_Largest. The Find_Largest uses a running min and max algorithm. The numbers are written to the output file (that was passed to the function).
71,533,025
71,533,145
What is the difference between *(pointer) and (*pointer)?
Please see the following block of code. Can you tell me the difference between *(sample) and (*sample)? for(i = 0; i < num_samples ; i++ ) { *(sample) &= 0xfff ; if( (*sample) & 0x800 ) *(sample) |= 0xf000 ; *(sample+1) &= 0xfff ; if( *(sample+1) & 0x800 ) *(sample+1) |= 0xf000 ; fprintf( my_data->fout, "%d, %d\n", *sample, *(sample+1) ); sample += 2 ; }
This is purely a question about operator precedence *sample , *(sample) and (*sample) all do this same thing in isolation. They deference the 'sample' pointer Things get more interesting when combined with other operators. You have an example *(sample+1) Lets take out the parens *sample+1 This could mean two things Give me the value pointed at by sample and add 1 to it give me the value thats one after where sample points Explictly bracketing that gives (*sample) + 1 => do the deref, then add 1 *(sample+1) => add 1 then deref So what does *sample+1 mean (ie with no brackets to dictate the order), not surprisingly it means (*sample) + 1 you can apply the same logic to all your other combinatons
71,533,672
71,533,988
Bug in Clang-12? "case value is not a constant expression"
I stumbled upon a strange compile error in Clang-12. The code below compiles just fine in GCC 9. Is this a bug in the compiler or is there an actual problem with my code and GCC is just too forgiving? #include<atomic> enum X { A }; class U { public: std::atomic<X> x; U() { x = A; } }; template<typename T> class V : public U { public: V() { switch(x) { case A: break; } } }; int main() { V<void> v; return 0; } The code also compiles fine in Clang-12 if I remove the template<typename T> line and just write V v; instead of V<void> v;. The problem also goes away if I make x non-atomic. My compile command is: clang++-12 test.cpp -std=c++17 -o test I get the following compiler output: test.cpp:18:9: error: case value is not a constant expression case A: ^ test.cpp:17:10: warning: enumeration value 'A' not handled in switch [-Wswitch] switch(x) { ^ test.cpp:25:10: note: in instantiation of member function 'V<void>::V' requested here V<void> v; ^ 1 warning and 1 error generated.
Looks like a bug to me. Modifying case A to case nullptr gives the following error message (on the template definition): error: no viable conversion from 'std::nullptr_t' to 'std::atomic<X>' Making the class template into a class as suggested in the question then gives error: value of type 'std::nullptr_t' is not implicitly convertible to 'int' The latter message is correct. When class types are used in a switch condition they should be contextually implicitly converted to a integral or enumeration type and then be promoted. Here it should use std::atomic<X>'s conversion function which converts to X and is then promoted to int. It shouldn't matter whether the statement appears in a template or not. The base class is not dependent, so referring to the member x directly without this-> is also fine. A conversion of A to std::atomic<X> would not be a constant expression, which is probably where the diagnostic comes from. Here is an open Clang bug report and here is another potentially related bug report. Actually, although the two mentioned bug reports are still open, the test code they present seems to work correctly since Clang 10. It seems to me that the variant in your question using a base class is a special case missed by that fix.
71,533,755
71,534,065
c++ Bind wide string to sqlite3 prepared statement
I am trying to bind wide string to sqlite3 prepared statement. I was trying to follow this answer, but it didn't work const auto sql_command = L"SELECT * FROM register_names WHERE name is ?VVV"; sqlite3_stmt *statement; sqlite3_prepare16(db, sql_command, -1, &statement, NULL); wstring p = ObjectAttributes->ObjectName->Buffer; sqlite3_bind_text16(statement, 1, p.data(), -1, SQLITE_TRANSIENT); printf("sql command: %s\n", sqlite3_sql(statement)); auto data = "Callback function called"; char *zErrMsg = nullptr; auto rc = sqlite3_exec(db, sqlite3_sql(statement), callback, (void *) data, &zErrMsg); I tried using 0 or 1 in sqlite3_bind_text16 but I either get null or original string with no substitution. What am I doing wrong?
In your SQL statement, change is to =, and change ?VVV to just ?. More importantly, per the documentation, sqlite3_exec() is not the correct way to execute a sqlite3_stmt you have prepared. You need to use sqlite3_step() (and sqlite3_finalize()) instead. Try this: const auto sql_command = u"SELECT * FROM register_names WHERE name = ?"; sqlite3_stmt *statement; auto rc = sqlite3_prepare16(db, sql_command, -1, &statement, NULL); if (rc != SQLITE_OK) ... rc = sqlite3_bind_text16(statement, 1, ObjectAttributes->ObjectName->Buffer, ObjectAttributes->ObjectName->Length, SQLITE_TRANSIENT); if (rc != SQLITE_OK) ... printf("sql command: %s\n", sqlite3_sql(statement)); while ((rc = sqlite3_step(statement)) == SQLITE_ROW) { // process row as needed using sqlite3_column_XXX() functions... } if (rc != SQLITE_DONE) ... rc = sqlite3_finalize(statement); if (rc != SQLITE_OK) ...
71,533,998
71,534,097
If I use alignas on a class, is the first member or base class aligned?
If I declare my class struct alignas(16) C { int x; };, is x guaranteed to be aligned to 16 bytes or could the compiler pad it on the “left”? What about template <typename T, std::size_t Align> struct alignas(Align) Aligned : T { using T::T; };? Would the T of Aligned<T, N> be aligned to N? Is that the right way to make a type that is a T that is always aligned?
If I declare my class struct alignas(16) C { int x; };, is x guaranteed to be aligned to 16 bytes or could the compiler pad it on the “left”? In this case, x has to be on the 16 byte boundary because you have a standard layout class. A standard layout class comes with a guarantee that the first member of the class shares the same address as the class itself, meaning it will have the same alignment. What about template <typename T, std::size_t Align> struct alignas(Align) Aligned : T { using T::T; };? This is the same case as long as T is a standard layout class. If it is then Aligned has standard layout, and the first base class subobject is guaranteed to be at the start of the object in memory, so it has the same alignment. Is that the right way to make a type that is a T that is always aligned? It's an way. Another approach would be to use a std::aligned_storage object and then use placement new to emplace an object into that aligned storage.
71,534,829
71,534,915
Why does char 0x0 becomes 0xFF (255) in QT C++ QByteArray?
Via the USB, I send the following to my QT C++ application. As you can see, we are sending total 5 bytes of data to my QT C++ application. /* Create array of prescalers */ uint8_t send_data_array[5] = {0}; uint8_t index = 0; /* Fill the array */ send_data_array[index++] = SEND_BACK_PWM_PRESCALERS_MESSAGE_TYPE; send_data_array[index++] = STM32_PLC_PWM0_To_PWM3_Get_Prescaler() >> 8; send_data_array[index++] = STM32_PLC_PWM0_To_PWM3_Get_Prescaler(); send_data_array[index++] = STM32_PLC_PWM4_To_PWM7_Get_Prescaler() >> 8; send_data_array[index++] = STM32_PLC_PWM4_To_PWM7_Get_Prescaler(); /* Send the data via USB */ CDC_Transmit_FS(send_data_array, index); When I send data, it looks like this: So when I recieve the data in my QT C++ application, it looks like this: uint32_t MessageServiceThread::readPWMPrescalersFromSTM32PLC(QByteArray usbDataRaw, uint32_t byteIndex){ pwmPrescaler[0] = (usbDataRaw.at(byteIndex) << 8) | usbDataRaw.at(byteIndex + 1); byteIndex += 2; pwmPrescaler[1] = (usbDataRaw.at(byteIndex) << 8) | usbDataRaw.at(byteIndex + 1); byteIndex += 2; uint16_t p0 = pwmPrescaler[0]; uint16_t p1 = pwmPrescaler[1]; Where usbDataRaw contains the data. The first index of usbDataRaw contains the message type that describe what type of message it is. So the code above begins from index 1, not index 0. Let's focusing on pwmPrescaler[0] = (usbDataRaw.at(byteIndex) << 8) | usbDataRaw.at(byteIndex + 1); Here pwmPrescaler is declared as uint16_t pwmPrescaler[2]; and usbDataRaw.at(byteIndex) = 0 and usbDataRaw.at(byteIndex + 1) = 250. But when I combinde them as you can see, I get the number 65530! That's funny, because -6/250 is 0xFA or 250. That means that a 0 must have to become 0xFF right? Why else does 250 become 65530?
It is unspecified whether char is signed or unsigned. usbDataRaw.at(byteIndex + 1) results in a char that intends stores the value 250. It looks like on your platform char is signed, so this value is actually -6. Arithmetic operations on integer types smaller than int get promoted to int before the operation is performed. From cppreference on Integer promotion : prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value. Note the last sentence : "This conversion always preserves the value". The value being preserved in this case is -6 not 250. The char is promoted to an int with the value -6 with a resulting of (assuming 32 bit int) 0xFFFFFFFA. The same thing occurs for the left operand, but the preserved value is 0, which is unchanged by the bitshift. Bitwise OR is then performed resulting in 0xFFFFFFFA, and then truncated to uint16_t for 0xFFFA or 65530. One solution is to cast the char to unsigned char first to allow the promotion to preserve the intended value, 250 in this case. Live example : https://godbolt.org/z/PP8rKqab7
71,535,059
71,566,523
Out of bounds index returns correct values from vector created in chibi scheme
I've embedded chibi scheme into my C++ application and am trying to create a float vector with a size of 3 in scheme, and then get the individual values of that vector back into my c++ program, however when I attempt to do so I only get the correct results if I use indexes beyond the size of the vector. As you can see below I verify the size of the vector. test.scm (define (test-vec in-a in-b) (let ((vec (vector (* 3.1 in-a) (* 4.1 in-b) 5.0))) (display "From Scheme: ") (display vec) (display "\n") vec)) test.cpp #include <iostream> #include <chibi/eval.h> int is_defined(sexp ctx, const char *sym) { sexp_gc_var1(ret); sexp_gc_preserve1(ctx, ret); ret = sexp_eval_string(ctx, sym, -1, NULL); int defined = sexp_procedurep(ret); sexp_gc_release1(ctx); return defined; } int main() { float returnA, returnB, returnC, returnD, returnE, returnF; sexp_scheme_init(); sexp ctx = sexp_make_eval_context(NULL, NULL, NULL, 0, 0); sexp_load_standard_env(ctx, NULL, SEXP_SEVEN); sexp_load_standard_ports(ctx, NULL, stdin, stdout, stderr, 1); // Load the scheme file and create temp variables to pass the values to chibi sexp_gc_var6(inAVal, inASym, inBVal, inBSym, returnedVector, filePath); sexp_gc_preserve6(ctx, inAVal, inASym, inBVal, inBSym, returnedVector, filePath); filePath = sexp_c_string(ctx, "test.scm", -1); sexp_load(ctx, filePath, NULL); // Ensure our procedure is defined if(is_defined(ctx, "test-vec")) std::cout << "test-vec is defined" << std::endl; // Create the values and create the symbols inAVal = sexp_make_flonum(ctx, 1.0); inASym = sexp_intern(ctx, "a", -1); inBVal = sexp_make_flonum(ctx, 2.0); inBSym = sexp_intern(ctx, "b", -1); // Bind the values to the symbols and pass them to chibi sexp_env_define(ctx, sexp_context_env(ctx), inASym, inAVal); sexp_env_define(ctx, sexp_context_env(ctx), inBSym, inBVal); // Evaluate the expression and store the result returnedVector = sexp_eval_string(ctx, "(test-vec a b)", -1, NULL); std::cout << "Vector size: " << sexp_vector_length(returnedVector) << std::endl; // I would expect this to return the expected results? returnA = sexp_flonum_value(sexp_vector_ref(returnedVector, 0)); returnB = sexp_flonum_value(sexp_vector_ref(returnedVector, 1)); returnC = sexp_flonum_value(sexp_vector_ref(returnedVector, 2)); std::cout << "Vector[0] = " << returnA << "\nVector[1] = " << returnB << "\nVector[2] = " << returnC << std::endl << std::endl; // If I index outside of the range of the vector, it gives me the correct results? returnD = sexp_flonum_value(sexp_vector_ref(returnedVector, 0)); returnE = sexp_flonum_value(sexp_vector_ref(returnedVector, 3)); returnF = sexp_flonum_value(sexp_vector_ref(returnedVector, 4)); std::cout << "Vector[0] = " << returnD << "\nVector[3] = " << returnE << "\nVector[4] = " << returnF << std::endl; sexp_gc_release6(ctx); } Which gives me the output: test-vec is defined From Scheme: #(3.1 8.2 5.0) Vector size: 3 Vector[0] = 3.1 Vector[1] = 3.1 Vector[2] = 8.2 Vector[0] = 3.1 Vector[3] = 8.2 Vector[4] = 5 How come indexing beyond the length of the vector is giving me the correct values?
Figured out the issue. It's because sexp_vector_ref(vec, i) evaluates to #define sexp_vector_ref(x,i) (sexp_vector_data(x)[sexp_unbox_fixnum(i)]) and sexp_unbox_fixnum(i) evaluates to #define sexp_unbox_fixnum(n) (((sexp_sint_t)((sexp_uint_t)(n) & ~SEXP_FIXNUM_TAG))/(sexp_sint_t)((sexp_sint_t)1<<SEXP_FIXNUM_BITS)) Which when we just pass in straight integers std::cout << "Unboxed fixnums: " << sexp_unbox_fixnum(0) << " " << sexp_unbox_fixnum(1) << " " << sexp_unbox_fixnum(2) << " " << sexp_unbox_fixnum(3) << " " << sexp_unbox_fixnum(4) << std::endl; gives us the output Unboxed fixnums: 0 0 1 1 2 However if we first convert them into the proper types that chibi expects, like so std::cout << "Fixnum: " << sexp_unbox_fixnum(sexp_make_fixnum(0)) << " " << sexp_unbox_fixnum(sexp_make_fixnum(1)) << " " << sexp_unbox_fixnum(sexp_make_fixnum(2)) << " " << sexp_unbox_fixnum(sexp_make_fixnum(3)) << " " << sexp_unbox_fixnum(sexp_make_fixnum(4)) << std::endl; we get the proper output Fixnum: 0 1 2 3 4 Solution: Use the correct types when indexing
71,535,416
71,539,580
Why doesn't the default case run here?
I wrote these following lines of codes: #include <sdl.h> #include <iostream> #include <stdio.h> #include <string> bool running = true; enum KeyPressSurfaces { KEY_PRESS_SURFACE_DEFAULT, KEY_PRESS_SURFACE_UP, KEY_PRESS_SURFACE_DOWN, KEY_PRESS_SURFACE_LEFT, KEY_PRESS_SURFACE_RIGHT, //de deallocate surface KEY_PRESS_SURFACE_TOTAL }; int main(int argc, char** argv) { //standard stuffs SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("vibin' with smug pika", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 300, 300, 0); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_Surface* loadSurface(std::string path); SDL_Surface* surface = SDL_GetWindowSurface(window); SDL_Surface* keypress [KEY_PRESS_SURFACE_TOTAL]; //anh hien tai dang duoc load, de BlitSurface len surface //SDL_BlitSurface(current --> surface) SDL_Surface* current = NULL; //set windows icon SDL_Surface* icon = SDL_LoadBMP("../pikachu/keypress_bmp/icon.bmp"); SDL_SetWindowIcon(window, icon); SDL_Event event; //load each image into the keypress array keypress[KEY_PRESS_SURFACE_DEFAULT] = SDL_LoadBMP("../pikachu/keypress_bmp/default.bmp"); keypress[KEY_PRESS_SURFACE_UP] = SDL_LoadBMP("../pikachu/keypress_bmp/up.bmp"); keypress[KEY_PRESS_SURFACE_DOWN] = SDL_LoadBMP("../pikachu/keypress_bmp/down.bmp"); keypress[KEY_PRESS_SURFACE_LEFT] = SDL_LoadBMP("../pikachu/keypress_bmp/left.bmp"); keypress[KEY_PRESS_SURFACE_RIGHT] = SDL_LoadBMP("../pikachu/keypress_bmp/right.bmp"); while (running) { while (SDL_PollEvent(&event)){ switch (event.type) { //user click x case SDL_QUIT: running = false; break; //where all the user inputs are handled case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_UP: current = keypress[KEY_PRESS_SURFACE_UP]; break; case SDLK_DOWN: current = keypress[KEY_PRESS_SURFACE_DOWN]; break; case SDLK_LEFT: current = keypress[KEY_PRESS_SURFACE_LEFT]; break; case SDLK_RIGHT: current = keypress[KEY_PRESS_SURFACE_RIGHT]; break; case SDLK_SPACE: current = keypress[KEY_PRESS_SURFACE_DEFAULT]; break; default: current = keypress[KEY_PRESS_SURFACE_DEFAULT]; } } } SDL_BlitSurface(current, NULL, surface, NULL); SDL_UpdateWindowSurface(window); } //deallocating surfaces for(int i=0; i<KEY_PRESS_SURFACE_TOTAL; ++i) { SDL_FreeSurface(keypress[i]); keypress[i] = NULL; } //destroy everythangggg SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); SDL_Quit(); return 0; } However, this bit: default: current = keypress[KEY_PRESS_SURFACE_DEFAULT]; does not run at all, no matter where I put it. The program should have shown the default image at the beginning, but there's only black when I compiled. Everything else runs fine and I cannot determine what mistake I make. I'm using CodeBlock version 20.03 and the latest version of SDL2.
I created a solution for you, and I have some notes to check from your end, Check if the file path is correct ../pikachu/keypress_bmp/default.bmp. When you want to trigger the default, you should press another key e.i Enter, A, B, etc. I have downloaded an SDL library I am not sure if you are using the same, but mine is V2. I have commented on your code, which I didn't use here in the image path. here is my code and result: //#include <sdl.h> #include <SDL.h> #include <iostream> #include <stdio.h> #include <string> bool running = true; enum KeyPressSurfaces { KEY_PRESS_SURFACE_DEFAULT, KEY_PRESS_SURFACE_UP, KEY_PRESS_SURFACE_DOWN, KEY_PRESS_SURFACE_LEFT, KEY_PRESS_SURFACE_RIGHT, //de deallocate surface KEY_PRESS_SURFACE_TOTAL }; int main(int argc, char** argv) { //standard stuffs SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("vibin' with smug pika", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 300, 300, 0); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_Surface* loadSurface(std::string path); SDL_Surface* surface = SDL_GetWindowSurface(window); SDL_Surface* keypress[KEY_PRESS_SURFACE_TOTAL]; //anh hien tai dang duoc load, de BlitSurface len surface //SDL_BlitSurface(current --> surface) SDL_Surface* current = NULL; //set windows icon //SDL_Surface* icon = SDL_LoadBMP("../pikachu/keypress_bmp/icon.bmp"); SDL_Surface* icon = SDL_LoadBMP("C:/Users/Awat/Desktop/bmp/img1.bmp"); SDL_SetWindowIcon(window, icon); SDL_Event event; //load each image into the keypress array /* keypress[KEY_PRESS_SURFACE_DEFAULT] = SDL_LoadBMP("../pikachu/keypress_bmp/default.bmp"); keypress[KEY_PRESS_SURFACE_UP] = SDL_LoadBMP("../pikachu/keypress_bmp/up.bmp"); keypress[KEY_PRESS_SURFACE_DOWN] = SDL_LoadBMP("../pikachu/keypress_bmp/down.bmp"); keypress[KEY_PRESS_SURFACE_LEFT] = SDL_LoadBMP("../pikachu/keypress_bmp/left.bmp"); keypress[KEY_PRESS_SURFACE_RIGHT] = SDL_LoadBMP("../pikachu/keypress_bmp/right.bmp"); */ keypress[KEY_PRESS_SURFACE_DEFAULT] = SDL_LoadBMP("C:/Users/Awat/Desktop/bmp/imgD.bmp"); keypress[KEY_PRESS_SURFACE_UP] = SDL_LoadBMP("C:/Users/Awat/Desktop/bmp/img3.bmp"); keypress[KEY_PRESS_SURFACE_DOWN] = SDL_LoadBMP("C:/Users/Awat/Desktop/bmp/img4.bmp"); keypress[KEY_PRESS_SURFACE_LEFT] = SDL_LoadBMP("C:/Users/Awat/Desktop/bmp/img5.bmp"); keypress[KEY_PRESS_SURFACE_RIGHT] = SDL_LoadBMP("C:/Users/Awat/Desktop/bmp/img6.bmp"); while (running) { while (SDL_PollEvent(&event)) { switch (event.type) { //user click x case SDL_QUIT: running = false; break; //where all the user inputs are handled case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_UP: current = keypress[KEY_PRESS_SURFACE_UP]; break; case SDLK_DOWN: current = keypress[KEY_PRESS_SURFACE_DOWN]; break; case SDLK_LEFT: current = keypress[KEY_PRESS_SURFACE_LEFT]; break; case SDLK_RIGHT: current = keypress[KEY_PRESS_SURFACE_RIGHT]; break; case SDLK_SPACE: current = keypress[KEY_PRESS_SURFACE_DEFAULT]; break; default: current = keypress[KEY_PRESS_SURFACE_DEFAULT]; } } } SDL_BlitSurface(current, NULL, surface, NULL); SDL_UpdateWindowSurface(window); } //deallocating surfaces for (int i = 0; i < KEY_PRESS_SURFACE_TOTAL; ++i) { SDL_FreeSurface(keypress[i]); keypress[i] = NULL; } //destroy everythangggg SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); SDL_Quit(); return 0; }
71,535,569
71,537,317
C++ question: I'm having problems writing array of doubles (single precision 32 bit) to a disc file as 4-byte IEEE754 format
I have an application I'm trying to write in which will take a table of numbers (generated by user) and write the table to a file on disc. This file will then later be transferred to an Arduino AVR device over USB to its EEPROM. The format I wish to save this information in on disc is 4-byte Little Endian as just raw Hex data. My table array called "tbl1Array[]" in my code below has been cast as a double. Below is a snippet of the bunk code I have in place now, in-line following some array preparation code. The file open/close works fine, and in fact, data DOES get transferred to the file, but the format is not what I want. ofstream fileToOutput("318file.bin"); for (int i=0; i<41; i++) { fileToOutput << tbl1Array[i]; } fileToOutput.close(); THE PROBLEM is that what is written to the file is a hex ASCII representation of the decimal value. Not what I want! I don't know what I need to do to get my array as a nice neat concatenated list of 4-byte Little Endian words for my doubles that I can later read from within the Arduino code. I have a working method for transferring the file to the Arduino using AVRDUDE (tested and confirmed), so my only real hang-up is getting these doubles in my applications' array to 4-byte IEEE754 on disc. Any guidance would be greatly appreciated. Regards - Mark
In a text stream, the new-line character is translated. Some operating systems translated to \r\n. A binary stream leaves it as it is. Regardless of how you opened the stream – binary or text: a. When you use the insertion/extraction operator the data is written as text. Assuming 0x01 is a one byte integer, ASCII 1 will be written (that is 0x31). b. If you use the ostream::write method, you write the actual bytes; no translations happens. Assuming 0x01 is a one byte integer, 0x01 will be written. If you want to write the actual bytes, open the stream in binary mode and use ostream::write: ofstream os{ "out.bin", ios::binary }; if (!os) return -1; double d = 1.234567; os.write((const char*)&d, sizeof d); If you want to write the actual bytes as a string, open the stream in text mode and use the insertion operator: ofstream os{ "out.txt" }; if (!os) return -1; double d = 1.234567; static_assert(sizeof(double) == sizeof(long long)); os << hex << *reinterpret_cast<long long*>(&d); If you want to write a double as string, using the maximum precision use: os << setprecision(numeric_limits<double>::max_digits10) << d; Don't use translated & untranslated methods on the same stream. I do not know if all above examples will work on an Arduino compiler.
71,535,696
71,537,864
Introduced intermediate variable in structured binding definition?
In [dcl.struct.bind] 9.6.4, there is definition of structured binding when initializer is a class type with std​::​tuple_­size<E>​::​value properly defined: ... variables are introduced with unique names ri as follows: S Ui ri = initializer ; Each vi is the name of an lvalue of type Ti that refers to the object bound to ri; the referenced type is Ti. My question is why is it necessary to introduce ri, can't we define the identifier vi directly as reference to the result of get<i>(e)?
The intent is to disallow redeclaring structured bindings as references. See CWG 2313.
71,535,879
71,535,920
Using C wrapper of C++ code for ABI stability?
In his talk Jason Turner proposed to break the C++ ABI to keep the language moving forward. He also mentioned that if needed due to compatibility reasons, C++ ABI changes can be isolated by wrapping a C++ library into a C library. A relevant screenshot at 27:30: Here "BinaryLibrary" and "Old C++ stdlib" use an old ABI, and "NewExecutable" uses a hypothetical updated ABI. As far as I understand, this works since old C++ ABI of "BinaryLibrary" gets baked into a separate binary with a more stable interface. But what makes C a good alternative? Can't its ABI change as well?
Can the C ABI change? Well, not easily. There have been occasional changes on some platforms, but so many systems and languages are built using the C ABI as a public interface that it has to be quite stable. Many languages have a C FFI which allows them to call C functions, and changing the C ABI would break those. And the C ABI is a common way of interacting with the operating system, e.g. to open files or send messages, so it's used by many language implementations (e.g. interpreters and standard libraries). Note that the C ABI is not part of the C standard. Each platform or system can define its own C ABI. So while it tends to be stable over time on a given platform, it is not consistent across all platforms.
71,535,946
71,536,230
Using command line parameters outside of main function
I would like a program to read in a file entered by the user via the command line, which is then used in the main body of the code. See example code below: #include <iostream> #include <fstream> struct run_t { std::string file; }; run_t run; const POINTER* ptr = toy(run.file, 0); // Here hardcoded the FILENAME as a string => code works. // I am trying to get it to work when I read in the filename from the // first entry on the command line upon program execution: // //const POINTER* ptr = toy("FILENAME", 0); double Toy1(double a, double b, double c) { return ptr->func(a, b, c); }; double Toy2(double d) { double factor = pow(d, 2); //some dummy prefactor return factor * Toy1(4, 5, 6); }; int main(int argc, char* argv[]) { run_t run; run.file = argv[1]; std::cout << Toy2(1) << std::endl; return 0; } The actual toy and Toy functions are software-specific and recognised by additional include-files. If I manually hardcode run.file in toy(run.file, 0) with the string FILENAME, compile and execute with a single command line parameter (./exe 1, say) then the program works. My question is, how to modify the above code so that the value FILENAME entered in the command line is read in instead as run.file? That is, to make ./exe FILENAME work? I have tried with declaring argv[1] as the argument of toy but I have not yet got this to work.
Here is the code I have tested. Try this #include <iostream> #include <fstream> #include <math.h> struct run_t { std::string file; }; run_t run; class POINTER{ public: POINTER(std::string file , int num){std::cout << "POINTER::POINTER(std::string file , int num)file " << file << std::endl;}; double func(double a, double b, double c) { POINTER *toy(std::string file , int num); return (double)0; } }; POINTER *toy(std::string file , int num) { POINTER* ptr = new POINTER(file , num); std::cout << "POINTER *toy(std::string file , int num) file " << file << std::endl; return ptr; } const POINTER * ptr; double Toy1(double a, double b, double c) { POINTER * ptrCst = const_cast<POINTER *>(ptr); return ptrCst->func(a, b, c); }; double Toy2(double d) { double factor = pow(d, 2); //some dummy prefactor return factor * Toy1(4, 5, 6); }; int main(int argc, char* argv[]) { run.file = argv[1]; POINTER * ptrCst = const_cast<POINTER *>(ptr); ptrCst = toy(run.file, 0); std::cout << Toy2(1) << std::endl; while(1); return 0; }
71,535,955
71,536,130
Why custom comparator for set in c++ requires extra 'const' keyword
I am solving a problem on leetcode OJ where i had to use a custom comparator for set in C++. typedef pair<pair<int,int>,int> ppi; class comp { public: bool operator()(const ppi & p1, const ppi & p2) { if(p1.first.first == p2.first.first) { if(p1.first.second == p2.first.second) return p1.second > p2.second; else return p1.first.second > p2.first.second; } else return p1.first.first > p2.first.first; } }; this is giving me an error when i am trying to delete an element from the set, which looks like: set<ppi, comp> customStack; . . . customStack.erase({{currentFrequency, currentAddress},val}); error: In file included from prog_joined.cpp:1: In file included from ./precompiled/headers.h:50: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/map:60: /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_tree.h:779:4: error: static_assert failed due to requirement 'is_invocable_v<const comp &, const std::pair<std::pair<int, int>, int> &, const std::pair<std::pair<int, int>, int> &>' "comparison object must be invocable as const" static_assert( ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_tree.h:1997:31: note: in instantiation of member function 'std::_Rb_tree<std::pair<std::pair<int, int>, int>, std::pair<std::pair<int, int>, int>, std::_Identity<std::pair<std::pair<int, int>, int>>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::_S_key' requested here if (_M_impl._M_key_compare(_S_key(__x), __k)) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_tree.h:2534:38: note: in instantiation of member function 'std::_Rb_tree<std::pair<std::pair<int, int>, int>, std::pair<std::pair<int, int>, int>, std::_Identity<std::pair<std::pair<int, int>, int>>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::equal_range' requested here pair<iterator, iterator> __p = equal_range(__x); ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_set.h:685:21: note: in instantiation of member function 'std::_Rb_tree<std::pair<std::pair<int, int>, int>, std::pair<std::pair<int, int>, int>, std::_Identity<std::pair<std::pair<int, int>, int>>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::erase' requested here { return _M_t.erase(__x); } ^ Line 39: Char 25: note: in instantiation of member function 'std::set<std::pair<std::pair<int, int>, int>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::erase' requested here customStack.erase({{currentFrequency, currentAddress},val}); ^ 1 error generated. after added 'const' in the comparator (line 4): class comp { public: bool operator()(const ppi & p1, const ppi & p2)const this worked for me. What is the reason for adding that extra keyword?
By adding that const to the end of that member function you're making it a const member function, meaning that it cannot possibly modify any of your member variables. Because calling a non-const member function could modify the object, you can't call it if the object is const. std::set's erase member function requires that operator() be const to stop it from modifying the object's in their set without you realizing. If any member function can be const then it should be const, just like any variables you declare or take in as arguments.
71,536,013
71,536,319
How can I read all files in the same directory?
I made a code for counting words in a file. But I want to adjust it to read all .txt files in the same directory. I found that I have to use <filesystem> but I dont know how to adjust it. int EBook::get_total_num_words() { map <string, int> words; int count = 0; string ws; ifstream file("inputs\\test.txt"); std::string path = "\\inputs"; //for (const auto& entry : std::filesystem::directory_iterator(path)) { while (file >> ws) { if (words[ws]) { ++words[ws]; } else { words[ws] = 1; } } file.close(); return (int)words.size(); }
You already know about directory_iterator. Simply move the ifstream inside the loop, constructing it with the path of the current entry, eg: int EBook::get_total_num_words() { map <string, int> words; string word; std::string path = "\\inputs"; for (const auto& entry : std::filesystem::directory_iterator(path)) { if (entry.path().extension().string() != ".txt") continue; ifstream file(entry.path()); while (file >> word) { ++words[word]; } } return (int)words.size(); }
71,536,199
71,541,182
Prevent "microsoft visual c++ runtime library debug assertion failed" window from appearing upon program crash
I am wondering if there is a way to automatically terminate the program entirely when an exception is thrown, rather than having to choose between the "abort", "retry", and "ignore" buttons on the Visual C++ library window that appears? . (example image) Is there any solution for this? (aside from the obvious -- fixing my code!)
Yes, you can suppress the message box by passing _OUT_TO_STDERR to _set_error_mode(). In case you still get a message box telling you that abort() was called and you want to disable it, too, you additionally need to call _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG). Full example: #include <cassert> #include <cstdlib> #include <crtdbg.h> int main() { _set_error_mode(_OUT_TO_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); assert(false); }
71,536,610
71,537,391
Why does c++ for each loops accept r-values but std::ranges do not?
A statement like this compiles without error: for (int i : std::vector<int>({0, 1})) std::cout << i; But a statement like this does not: std::vector<int>({0, 1}) | std::views::filter([](int i) { return true; }); Why are r-values allowed in for each loops but not in std::range pipes? Is there a way I could get something like the second to work, without having to declare a variable?
The for-loop works fine because the vector<int> (rvalue) is valid while the loop is evaluated. The second code snippet has 2 issues: The predicate must return a bool the vector<int> you are using in the views object is dangling by the time it is evaluated, so the compiler does not accept it. If instead of a vector<int> rvalue, the object cannot dangle (lvalue) or holds references into something else that cannot not dangle, this would work. For example: auto vec = std::vector<int>({0, 1}); auto vw = vec | std::ranges::views::filter([](int i) { std::cout << i; return true; }); Or you can pass an rvalue that has references to a non-dangling vector<int> object, like std::span: auto vec = std::vector<int>({0, 1}); auto vw = span{vec} | std::ranges::views::filter([](int i) { std::cout << i; return true; }) Here, std::span is still a rvalue, but the compiler accepts it because the author of std::span has created an exception for it. For a custom type with references into something else (typically views), you can create your own exception by creating a specialization of the template variable enable_borrowed_range. In the case of vector it would look like this (but don't do this!): template<> // don't do this inline constexpr bool ranges::enable_borrowed_range<std::vector<int>> = true; Your code now compiles but it will trigger undefined behavior because the vector is dangling once the view is evaluated.
71,536,672
71,539,260
Does shared_ptr a = make_shared() create a copy of the shared_ptr before constructor is run?
This might be a stupid question. Let's say we're in C++11 land and we use make_shared() to create a smart pointer. We then use this smart pointer to initialize a variable with like this: std::shared_ptr<class> = make_shared(/* args to c'tor of class*/ ); Now I know two things: Assignement is not initialization. In this case we have initialisation. This would mean in the above case probably the copy constructor is called for the shared_ptr which is returned by make_shared. Copy elision is only mandatory in C++17. Does this mean that on every instance of make_shared a temporary copy of the shared_ptr is created and inserted into the copy constructor? Because this would mean for thread safety that a lock would have to be taken across the initialisation in case other threads preempt the thread and call shared_ptr::use_count() member function?
There are two things to avoid the copy: 1 is the compiler's RVO (return value optimization); 2 is the move constructor/assignment. for code auto foo = std::make_shared<Foo>(); RVO will create the object directly on the stack. and even we disable the RVO by -fno-elide-constructors, the move constructor will try used as the returned object from make_shared is a temporary one. Below is a simple test code. (this code only show the concept but not for a real-world shared_ptr implementation) #include <iostream> template <typename T> struct my_shared_ptr { T *t_{nullptr}; my_shared_ptr(T *t): t_(t) { std::cout << "constructor" << std::endl; }; my_shared_ptr(const my_shared_ptr<T>&) { std::cout << "copy" << std::endl; } my_shared_ptr<T>& operator=(const my_shared_ptr<T>&) { std::cout << "copy" << std::endl; return *this; } #ifndef NO_MOVE my_shared_ptr(my_shared_ptr<T>&&) { std::cout << "move" << std::endl; } my_shared_ptr<T>& operator=(my_shared_ptr<T>&&) { std::cout << "move" << std::endl; return *this; } #endif }; template <typename T> my_shared_ptr<T> my_make_shared() { return my_shared_ptr<T>(new T); } struct Foo {}; int main() { auto foo = my_make_shared<Foo>(); return 0; } Condition 1, compile with c++11 shows: $ g++ a.cc -std=c++11 ; ./a.out constructor Condition 2, compile with c++11/disable RVO shows: $ g++ a.cc -std=c++11 -fno-elide-constructors ; ./a.out constructor move move Condition 3, compile with c++11/disable RVO/no move shows: $ g++ a.cc -std=c++11 -fno-elide-constructors -DNO_MOVE ; ./a.out constructor copy copy
71,536,932
71,537,072
What is happenning in this template header?
There is an amazingly useful answer on how to serialize eigen matrices using cereal: Serializing Eigen::Matrix using Cereal library I copied and verified this code works, but I am having a hard time understanding what is going on in the header: template <class Archive, class _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline typename std::enable_if<traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value, void>::type save(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> const & m) { int32_t rows = m.rows(); int32_t cols = m.cols(); ar(rows); ar(cols); ar(binary_data(m.data(), rows * cols * sizeof(_Scalar))); } The first line is taking a cereal archive type and then all the needed eigen template parameters. I am not 100% sure what the second line is doing, it seems to be declaring the run type? But I can't follow what the type is mean to be. Additionally (if possible, but not required for an answer) Why does this not work? (it doesn't I checked, it won't compile): template <class Archive> void serialize( Archive& archive, Eigen::Vector2f& vec ) { archive( CEREAL_NVP((float&)vec[0]), CEREAL_NVP((float&)vec[1]) ); } template <class Archive> void serialize( Archive& archive, Eigen::Vector3f& vec ) { archive( CEREAL_NVP((float&)vec[0]), CEREAL_NVP((float&)vec[1]), CEREAL_NVP((float&)vec[2]) ); }
The template uses SFINAE (Substitution Failure Is Not An Error) to limit the template parameters this function takes. Basically if the compiler considers the function signature of the template function to be erroneous, it simply ignores this function instead of producing a compiler error. typename std::enable_if<traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value, void>::type is effectively void, if traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value evaluates to true and it results in an erroneous signature, if it evaluates to false.
71,538,369
71,541,057
Failure to select correct operator== with MSVC but not gcc/clang for templated class
The following example compiles fine using gcc and clang, but fails to compile in MSVC. I would like to know if I have unwittingly stumbled into non-standard territory? If not, which compiler is correct? And is there maybe a workaround? Minimal example (https://godbolt.org/z/PG35hPGMW): #include <iostream> #include <type_traits> template <class T> struct Base { Base() = default; Base(T) {} static constexpr bool isBase = true; }; template <class U> constexpr std::enable_if_t<U::isBase, bool> EnableComparisonWithValue(U const *) { return false; } template <class> constexpr bool EnableComparisonWithValue(...) { return true; } template <class T, class U> bool operator==(Base<T> const &, Base<U> const &) { std::cout << "operator==(Base, Base)" << std::endl; return true; } template <class T, class U, std::enable_if_t<EnableComparisonWithValue<U>(nullptr), int> = 0> bool operator==(Base<T> const &, U const &) { std::cout << "operator==(Base, U)" << std::endl; return true; } template <class U, class T, std::enable_if_t<EnableComparisonWithValue<U>(nullptr), int> = 0> bool operator==(U const &, Base<T> const &) { std::cout << "operator==(U, Base)" << std::endl; return true; } int main() { Base<int> b1, b2; b1 == 42; // gcc and clang compile, msvc does not } MSVC throws a compilation error C2676: binary '==': 'Base<int>' does not define this operator or a conversion to a type acceptable to the predefined operator. clang and gcc call operator==(Base, U) as expected. Interestingly, the result is the same if I remove all the members in Base and just define it as template <class T> struct Base{};. Background: I have another class template <class T> Derived : Base<T> which does not contain additional data. I would like to reuse all the operator== without having to redefine them again for Derived. Without the SFINEA stuff, comparing a Derived<int> with an int results in an ambiguous operator call, because the bottom two operator== definitions deduce U as Derived<int> (AFAIK correctly). So my idea was do disable them to force the compiler to use operator==(Base<T> const &, Base<U> const &). But then I came upon the above problem. Also, is there maybe a workaround apart from defining the operators for all combinations of Base and Derived?
I'm surprised that MSVC doesn't compile your code, that seems to me perfectly correct. So... not sure... but I suppose that is a MSVC bug. Anyway... given that you also ask for a workaround... I see that also for MSVC works SFINAE if you enable/disable the return type of the operators, so I propose that you rewrite your operators as follows template <class T, class U> std::enable_if_t<EnableComparisonWithValue<U>(nullptr), bool> operator==(Base<T> const &, U const &) { std::cout << "operator==(Base, U)" << std::endl; return true; } template <class U, class T> std::enable_if_t<EnableComparisonWithValue<U>(nullptr), bool> operator==(U const &, Base<T> const &) { std::cout << "operator==(U, Base)" << std::endl; return true; } The following is a full compiling example with also a Derived class #include <iostream> #include <type_traits> template <class T> struct Base { Base() = default; Base(T) {} static constexpr bool isBase = true; }; struct Derived : public Base<int> { }; template <class U> constexpr std::enable_if_t<U::isBase, bool> EnableComparisonWithValue(U const *) { return false; } template <class> constexpr bool EnableComparisonWithValue(...) { return true; } template <class T, class U> bool operator==(Base<T> const &, Base<U> const &) { std::cout << "operator==(Base, Base)" << std::endl; return true; } template <class T, class U> std::enable_if_t<EnableComparisonWithValue<U>(nullptr), bool> operator==(Base<T> const &, U const &) { std::cout << "operator==(Base, U)" << std::endl; return true; } template <class U, class T> std::enable_if_t<EnableComparisonWithValue<U>(nullptr), bool> operator==(U const &, Base<T> const &) { std::cout << "operator==(U, Base)" << std::endl; return true; } int main() { Base<int> b1, b2; Derived d1, d2; b1 == b2; // Compiles fine b1 == 42; // gcc and clang compile, msvc does not d1 == d2; d1 == b1; b2 == d2; d1 == 42; 42 == d2; }
71,538,502
71,541,820
google mock unable to mock a method with a templated argument
I am not sure if what I am trying to do is possible, but I have a hard time with the compiler trying to mock a method which contains a templated reference parameter. The interface (removed all irrelevant methods) class iat_protocol { public: virtual void get_available_operators(etl::vector<network_operator, 5>&) = 0; }; My mock class at_protocol_mock : public iat_protocol { public: MOCK_METHOD((void), get_available_operators, (etl::vector<network_operator, 5>&), (override)); }; This results in In file included from /home/bp/dev/unode/eclipse/thirdparty/googletest/googlemock/include/gmock/gmock-actions.h:145, from /home/bp/dev/unode/eclipse/thirdparty/googletest/googlemock/include/gmock/gmock.h:57, from ../tests/shared/hal/at/at_channel_tests.cpp:1: /home/bp/dev/unode/eclipse/unit_tests/tests/shared/hal/at/mocks/at_protocol_mock.hpp: In member function ‘testing::internal::MockSpec<void(etl::vector<iobox::hal::at::network_operator, 5>&)> iobox::hal::at_protocol_mock::gmock_get_available_operators(const testing::internal::WithoutMatchers&, testing::internal::Function<void(etl::vector<iobox::hal::at::network_operator, 5>&)>*) const’: /home/bp/dev/unode/eclipse/thirdparty/googletest/googlemock/include/gmock/gmock-function-mocker.h:343:74: error: invalid combination of multiple type-specifiers 343 | typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type | ^~~~ /home/bp/dev/unode/eclipse/thirdparty/googletest/googlemock/include/gmock/internal/gmock-pp.h:17:31: note: in definition of macro ‘GMOCK_PP_IDENTITY’ My c++ skills are not good enough to have a clue what the compiler tries to tell me. Who can help me ?
Well, this is strange, but simple using fixes your problem. #include "gmock/gmock.h" struct network_operator {}; namespace etl { template <typename T, unsigned N> struct vector {}; } // namespace etl using vector_5 = etl::vector<network_operator, 5>; class iat_protocol { public: virtual void get_available_operators(vector_5&) = 0; }; class at_protocol_mock : public iat_protocol { public: MOCK_METHOD(void, get_available_operators, (vector_5&),(override)); }; From gMock cookbook Dealing with unprotected commas
71,538,730
71,538,790
Argument list for class template `sgl::Bag` is missing
So I am currently working on a project to make a library with all of the different data structures in C++. Here I have declared a class Bag: template<typename Type> class Bag { // ... inline static const char* print_seperator = "\n"; public: // ... inline static void set_seperator(const char* new_seperator) { Bag::print_seperator = new_seperator; } } Now this works fine, but when I try to use it in my main() function like this: sgl::Bag::set_seperator(", "); This shows the following error: Argument list for class template sgl::Bag is missing ..so I gave the argument list for the class template: sgl::Bag<int>::set_seperator(", "); ..and it works fine. But I don't want to type that out every time. Is there any way I can overcome this?
You can use default template argument for the template type parameter Type as shown below: //use default argument for template type parameter "Type" template<typename Type = int> class Bag { // ... inline static const char* print_seperator = "\n"; public: // ... inline static void set_seperator(const char* new_seperator) { Bag::print_seperator = new_seperator; } }; int main() { //no need to specify int Bag<>::set_seperator(", "); //angle bracket still needed return 0; } Demo
71,538,925
71,540,857
Insert at given position in link list , in code why we need (pos-2)
In the code given below we insert a node at a given position. My question is: Why do we need to use pos-2 in the for condition? insertNode(Node *head,int pos,int data) { Node *temp=new Node(data); if(pos==1) { temp->next=head; return temp; } Node * curr=head; for(int i=1;i<=pos-2 && curr!=NULL ;i++) curr=curr->next; if(curr==NULL) return head; temp->next=curr->next; curr->next=temp; return head; }
Some things to note: We want curr to point to the node that precedes the position where the new node is to be inserted. This is because we will make the insertion happen with curr->next=temp, where temp is the new node. Since the head node has no predecessor, it is a special case. This occurs when pos is 1. When pos is 2, the preceding node is the head node. Since curr is initialised as head, it should not move. So also for this case, we don't want the loop to make any iterations. When pos is 3, the preceding node is the second node in the list. Since curr points at head, it needs to make one step forward, i.e. the loop should iterate just once. This happens when you make the for condition as <=pos-2. Alternatively, you could reason that we have already dealt with the case where pos is 1, so we could let the loop start at pos=2, and then we can also replace the <= with < which denotes that we want to get to the preceding position, not at the position. And now the loop header looks like this: for (int i = 2; i < pos && curr != NULL; i++) This performs the same number of iterations, but maybe it is more readable. I hope this explains it.
71,539,247
71,539,364
glGenBuffer causes segmentation fault
when using glGenBuffers with almost any other gl function the program crashes in startup #define GL_GLEXT_PROTOTYPES #include </usr/include/GLFW/glfw3.h> #include <iostream> int main() { glfwInit(); GLFWwindow *wd = glfwCreateWindow(900, 800, "main window", NULL, NULL); glfwMakeContextCurrent(wd); GLuint *buffer; glGenBuffers(1, buffer); glBindBuffer(GL_ARRAY_BUFFER, *buffer); while (!glfwWindowShouldClose(wd)) { glfwPollEvents(); } glfwTerminate(); }
Change: GLuint *buffer; glGenBuffers(1, buffer); glBindBuffer(GL_ARRAY_BUFFER, *buffer); to: GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); The problem is: You are giving OpenGL the value of an uninitialized variable, which it will treat as a memory location to store the buffer id into. Instead, you should declare a stack/local variable and use a pointer to that (which is a valid address location) to give OpenGL.
71,539,371
71,539,450
How to convert a string into a multidimensional array of chars
I have a std::string that contains a random phrase. For example: std::string str{ "Lorem ipsum" }; I'd like to take that string and convert it into a std::vector<std::vector<char>> (each sub-array would have all the characters for one word in the phrase, i.e. splitting on spaces). For example after the conversion: std::vector<std::vector<char>> arr{ { 'L', 'o', 'r', 'e', 'm' }, { 'i', 'p', 's', 'u', 'm' } }; Furthermore, I'd like to then be able to convert the std::vector<std::vector<char>> back into a std::string. Thank you for the help!
#include <bits/stdc++.h> using namespace std; int main() { vector<vector<char>> v; vector<char> c; string s = "hello world this"; for(int i=0;i<s.size();i++) { if(s[i]==' ') { v.push_back(c); c.clear(); }else{ c.push_back(s[i]); } } for(int i =0;i<v.size();i++) { for(int j=0;j<v[i].size();j++) { cout<<v[i][j]; } cout<<endl; } return 0; }
71,539,895
71,542,367
Combining Qt with OpenGL: does not compile
I'm trying to create a project in Qt with an QOpenGLWidget and CMake as a building tool. The problem is that it does not compile and I don't know why. [...]\include\ui_MainWindow.h:79: błąd: undefined reference to `__imp__ZN13QOpenGLWidgetC1EP7QWidget6QFlagsIN2Qt10WindowTypeEE' That's my CMakeLists.txt file: cmake_minimum_required(VERSION 3.5) project(QtTest VERSION 0.1 LANGUAGES CXX) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(OpenGL REQUIRED) find_package(QT NAMES Qt6 Qt5 COMPONENTS Widgets REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS OpenGL REQUIRED) set(PROJECT_SOURCES src/main.cpp src/MainWindow.cpp src/MainWindow.hpp src/MainWindow.ui ) if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) qt_add_executable(QtTest MANUAL_FINALIZATION ${PROJECT_SOURCES} ) else() add_executable(QtTest ${PROJECT_SOURCES} ) endif() target_link_libraries(QtTest PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::OpenGL) set_target_properties(QtTest PROPERTIES MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} MACOSX_BUNDLE TRUE WIN32_EXECUTABLE TRUE ) if(QT_VERSION_MAJOR EQUAL 6) qt_finalize_executable(QtTest) endif() In my MainWindow.ui file I only create an QOpenGLWidget widget.
In Qt6 QOpenGLWidget was moved to a new module named OpenGLWidgets. To make your program work you need to add OpenGLWidgets to your find_package command and Qt6::OpenGLWidgets to your target_link_libraries command. find_package(Qt6 COMPONENTS Widgets OpenGL OpenGLWidgets REQUIRED) target_link_libraries(QtTest PRIVATE Qt6::Widgets Qt6::OpenGL Qt6::OpenGLWidgets)
71,540,234
71,542,027
Is accessing elements on a 16 byte aligned contigous memory with paddings between elements faster than tightly packed elements in memory?
So imagine if we had a custom memory allocator that we initialize with a size of 64, and whenever we want to construct a new element inside it, the allocator aligns every element's starting address to be a 16-byte aligned address. For example: If the allocator allocated a memory on heap that starts from address 0x00 to 0x40, and when we allocate four 32-bit integers inside it, the memory addresses of them would be: 0x00, 0x10, 0x20 and 0x30. Now let's imagine another custom allocator that also allocates a 16-byte aligned memory. For example if we say the size to be 15, the allocated memory address will range from 0x00 to 0x10. But this time, instead of aligning each element's starting address to be a 16-byte aligned memory, this allocator will put the elements next to each other. For the sake of our argument, let's again assume that we are trying to construct four 32-bit integers inside this allocator's buffer. This time, the starting addresses of these integers will be 0x00, 0x04, 0x08 and 0x0c. My question is; which of these allocators will result in less CPU instructions, (sorry if am wrong with this, because it may result in same instructions) or will yield faster read times on a 64-bit system?
A 16-bit Processor Let's say I have a processor that loves to make fetches of 16-bits. When data is aligned on a 16-bit boundary, the processor only has to make one fetch: +---+---+ 4 | a | b | +---+---+ In one fetch, the processor can get both a and b (which are 8-bit quantities). If we have data that is not on a 16-bit boundary, the processor would have to make two fetches, then do some bit shifting and masking to make a 16-bit word. +---+---+ 2 | | a | +---+---+ 4 | b | | +---+---+ In the above example, the 16-bits of data are at memory location 3. In order to get the quantity ab, the processor has to make a fetch at address 2 (to get the a quantity), then make a fetch at address 4 to get the b value. This is 2 fetches instead of 1, not to mention the extra effort to get a and b into one 16-bit word. The net effect is that your program is slowed down. Whether the efficiency loss is negligible is another matter. A 32-bit Processor A 32-bit processor is geared up to be most efficient at fetching 32-bit quantities. So when the processor is told to fetch data that is not on a 32-bit boundary it has to make at least one extra fetch, similar scenario to the 16-bit scenario above. Some 32-bit processors may be optimized to also perform 8-bit fetches, so to fetch 3 bytes (3 x 8-bits), the processor would make 3 8-bit fetches. (Although it could be wired to make a 32-bit fetch and then use bit shifting and masking to place the 8-bit quantities into separate registers). Memory Alignment and Address Decoding Let start off with the understanding that there is one address line for every power of 2 in the address range. When accessing memory the fundamental technique is to convert the address to binary and set the address lines accordingly. However, routing all these address lines around the PCBA board gets complicated (and costly). Some platforms may eliminate the first address line for 16-bit alignment and the first and second line for 32-bit alignments (draw the picture and you will see that these lines are not used for the associated fetches). So, with memory aligned on 32-bit boundaries, accessing items not aligned will need to make multiple fetches from memory because the memory may not have all the address lines decoded. This will slow down your program. Whether the slow down is negligible is another matter.
71,540,246
71,540,512
Is it possibile to embed python libraries in C++?
Is it possibile to use python libraries in C++ like selenium , django etc ....? If yes are there any docs that explain this well like fully embedding a python library in C++ not just some run script like PyRun_SimpleString() ???
If you want to mix Python in a C++ project, a simple possibility is to include Boost in your project, and rely on the Boost.Python library which enables interoperability between Pyton and C++ (https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/index.html); This is basically a wrapper around the Python C API to make things easier, included into the well-known C++ Boost library. In your case, you want to embed Python in C++, and Boost almost enables to do it without calling the Python C/ API: https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/tutorial/tutorial/embedding.html. The use is pretty straightforward, you simply need to include boost/python.hpp, and embed the Python interpreter into your code snippet to call Python modules. Without reinventing the wheel, here's a link to another SO question related to your topic with a nice answer which explains how to do it: How to import a function from python file by Boost.Python. Of course, you may not want to include Boost into your project (if you don't want to struggle installing it for instance).
71,540,463
71,540,812
How to write native C++ in VS 2022, using Linux for build and test
I need a native C++ app to make from scratch. It has to run on linux (CentOS). I want to use VS2022 to write and test. I have Hyper-V VM with CentOS. I tried to google a solution but there are only posts for using WSL. Can someone please describe steps to connect VS to Linux VM instead of WSL so I can build and run the app on the VM.
This article describes the process: https://devblogs.microsoft.com/cppblog/linux-development-with-c-in-visual-studio/ add workload to the VS using VS Installer (Linux and embedded..) create project of correct type add SSH credentials in the project Properties (also can be added/removed/edited in Tools-Options-Cross Platform)
71,540,734
71,540,801
How to deal with constness when the method result is cached?
I have a class with a method (getter) that performs some relatively expensive operation, so I want to cache its result. Calling the method does not change behavior of the object, but it needs to store its result in this, so it can't be const. The problem is that I now have another method that is const and I need to invoke my getter. Is there some generally accepted solution to this problem? Should I bypass the constness checking in the getter to make it const, (Coudn't that cause problems with optimizing compiler?) or I have to propagate the non-constness to all methods that use this getter? Example: class MyClass { public: Foo &expensiveGetter() /*const?*/ { if (cachedValue == nullptr) { cachedValue = computeTheValue(); } return *cachedValue; } void myMethod() /* How to make this const? */ { auto &foo = expensiveGetter(); // etc. } private: Foo *cachedValue = nullptr; } I am looking for something like the RefCell in Rust.
This is one of the situations the mutable specifier fits particularly well. When a class member is mutable, that member can be changed even if the enclosing class is const. So, if MyClass::cachedValue is a mutable Foo* instead of a Foo*, you can have const member functions in MyClass that make changes to cachedValue and then all calling code can just act on a const MyClass as normal.
71,540,901
71,540,962
I can't print out sentence with 'cout' in c++
first I not a native English speaker so if you find errors in my English ignore them, below my code #include <iostream> #include <string> #include <vector> using namespace std; //Globle variables int Counter = 0 ; vector<string> tasksList; string task; //functions int AddingTasks(){ cout<<"type your task here: "; cin>>task; tasksList[Counter-1].assign(task); // the "Counter-1" to set the index to zero because 'Counter' variable = 1 cout<<tasksList[Counter-1]<<"added "<<endl; // the problem is here it crash here it won't print out this Sentence return 0; } int main(int argc, char const *argv[]) { tasksList.resize(Counter); int ChooseNum; cout<<"Mustafa ToDoList the best to do list ever! "<<endl; cout<<"Choose: [1] add task [2] view tasks [3] edit task [4] delete task : "; cin>>ChooseNum; if (ChooseNum == 1) { Counter++; AddingTasks(); } // [2][3][4] are unnecessary now return 0; } I think there is no error in my code but there problem in 'AddingTasks()' function the program crash when it tries to print the task that's been added, I don't know why? I am beginner in C++.
Change AddingTasks by: int AddingTasks() { cout << "type your task here: "; cin >> task; tasksList.push_back(task); cout << tasksList[tasksList.size() - 1] << " added " << endl; return 0; } What is happening is, you're trying to access an object that does not exist in the vector.
71,541,210
71,555,756
Valgrind ClientCheck uninitialized string
I'm new to Valgrind, and I've had some trouble finding the source of some of it's warnings. I've been using the VALGRIND_CHECK_VALUE_IS_DEFINED macro from memcheck.h to try and locate the exact source of the error, which has led me to wonder if I am using the tool correctly. Here is a sample program that I run with Valgrind: #include <valgrind/memcheck.h> int main() { std::string str("test"); VALGRIND_CHECK_VALUE_IS_DEFINED(str); return 0; } Which results in the following warnings: ==9612== Uninitialised byte(s) found during client check request ==9612== at 0x11EB45: main (main.cpp:5) ==9612== Address 0x1ffefffd35 is on thread 1's stack ==9612== in frame #0, created by main (main.cpp:3) ==9612== Uninitialised value was created by a stack allocation ==9612== at 0x11EA8E: main (main.cpp:3) A very similar program: #include <valgrind/memcheck.h> int main() { int x = 0; VALGRIND_CHECK_VALUE_IS_DEFINED(x); return 0; } has no such issue. I am using the flag --track-origins=yes for line tracing, and compiling as c++17 using g++ 9.4.0 (although I received the same warning with clang++ 14.0.0) on Ubuntu 20.04 LTS. Is this a mistake on my end, or is it an issue with Valgrind?
The reason for this is fairly straightforward. An std::string roughly consists of a pointer, length and allocated_capacity members. On 64bit Unix-like platforms they are all 8 bytes. The "SSO" [Small String Optimization] will recycle (and extend) the allocated capacity member via a union to store the string if it is short enough. Note that clang libc++ does things a bit differently (I think that the union there recycles the pointer and the capacity to allow larger "small" strings). This means that sizeof(std::string) is 32. There are then two possibilities. If the string is not "short" then the pointer, length and allocated_capacity are all used and the last 8 bytes will be uninitialized. If the string is "short", then any spare capacity in the local_buf (16 bytes for libstdc++) will be uninitialized. Consider the following code. I've used VALGRIND_GET_VBITS which will get a byte with bits set to zero for defined memory and set to 1 for undefined memory. #include "valgrind/memcheck.h" #include <string> #include <iostream> int main() { const auto size = sizeof(std::string); unsigned char bits[size]; // SSO, local buf not filled std::string str("test"); VALGRIND_CHECK_VALUE_IS_DEFINED(str); VALGRIND_GET_VBITS(&str, bits, size); for (int i = 0; i < size; ++i) std::cout << "byte " << std::dec << i << " bits " << std::hex << static_cast<int>(bits[i]) << '\n'; // SSO, local buf illed std::string str2("123456789012345"); VALGRIND_CHECK_VALUE_IS_DEFINED(str2); VALGRIND_GET_VBITS(&str2, bits, size); for (int i = 0; i < size; ++i) std::cout << "byte " << std::dec << i << " bits " << std::hex << static_cast<int>(bits[i]) << '\n'; // not SSO std::string str3("12345678901234567890"); VALGRIND_CHECK_VALUE_IS_DEFINED(str3); VALGRIND_GET_VBITS(&str3, bits, size); for (int i = 0; i < size; ++i) std::cout << "byte " << std::dec << i << " bits " << std::hex << static_cast<int>(bits[i]) << '\n'; return 0; } For str (used 4 bytes plus one for nul, so 5 bytes of the SSO buffer). The output after the "Uninitialized bytes" message is byte 0 bits 0 [same 1 to 13] byte 14 bits 0 byte 15 bits ff [same 16 to 30] byte 31 bits ff So you can see bytes 15 to 31 are undefined. That's 11 bytes, which is what I expected. 16 bytes for the SSO local_buf, the first 5 bytes of which are initialized by "test\0". For str2 there is no "Uninitialized bytes" message, and the VBITS are all defined. Lastly for str3, too long for SSO, again there is an "Uninitialized bytes" message and this time the output is byte 0 bits 0 [same 1 to 22] byte 23 bits 0 byte 24 bits ff [same 25 to 30] byte 31 bits ff Again this is as expected. Now the last 8 bytes of the string are acting like unused padding and are uninitialized.
71,541,973
71,542,031
What is the logic behind "<" and ">" string operators in c++?
I wanted to sort a vector of strings in terms of their ASCII order and my first try was using < > operators.I got some weird results and then I found compare function for strings in c++ and completed my task. But after that when I was reading c++ reference, It was written that > < operators are using the exact compare function for strings! So why do I get different results like this: int main(){ cout << ("ali" > "Zahra") << endl; string a = "ali"; cout << a.compare("Zahra"); } the output is 0 461569 which means in the comparison with > operator "ali" comes first but with compare function "Zahra" comes first (which is more sensible because of ASCII). So my question is how does these operators work for strings?
"ali" and string a = "ali"; are two ways to define a string value but have different types. "ali" is a string literal, which the C++ standard defines as an array of n const char where n is the length of the string up to \0. This is commonly seen as const char[n] string a = "ali"; type is explicitly defined with a type string (std::string) and the value ali. So your first cout statement is calling operator> between two const char[n], and in the second cout statement, you are calling std::string::compare() and passing in a value of type const char[n] And thus the results of two different function calls are not the same.
71,542,209
71,542,272
I'm trying to print only uppercase letters from some input using for loop to iterate trough characters, but for some reason it doesn't work
I'm 100% sure from testing that for loop does iterate through characters how is it suposed to, but the other part of the program isn't working correctly. Im trying with if statement to print only uppercase characters. Here are some input/output samples to get a better pitcure what this program is about: Input: Tim-Berners-Lee Output: TBL Input: Albert-Einstein Output: AE Here is the code: #include <iostream> #include <string> using namespace std; int main(){ string name; cin >> name; int N = name.length(); for (int i = 0; i < N; i++) { if (name[i] == 'A' || 'B' || 'C' || 'D' || 'E' || 'F' || 'G' || 'H' || 'I' || 'J' || 'K' || 'L' || 'M' || 'N' || 'O' || 'P' || 'Q' || 'R' || 'S' || 'T' || 'U' || 'V' || 'W' || 'X' || 'Y' || 'Z'){ cout << name[i]; } } }
Your code will calculate compare name[i] == 'A' first and then take the result to do OR operation with 'B', 'C', and so on..., which absolutely won't work. You should do name[i] == 'A' || name[i] == 'B' || ... or just use std::isupper().
71,542,397
71,542,723
Pascal triangle matrix using vectors in C++
I need make Pascal Triangle matrix using vectors and then print it. This algorithm would work with arrays, but somehow it doesn't work with matrix using vectors. #include <iomanip> #include <iostream> #include <vector> typedef std::vector<std::vector<int>> Matrix; int NumberOfRows(Matrix m) { return m.size(); } int NumberOfColumns(Matrix m) { if (m.size() != 0) return m[0].size(); return 0; } Matrix PascalTriangle(int n) { Matrix mat; int a; for (int i = 1; i <= n; i++) { a = 1; for (int j = 1; j <= i; j++) { if (j == 1) mat.push_back(j); else mat.push_back(a); a = a * (i - j) / j; } } return mat; } void PrintMatrix(Matrix m, int width) { for (int i = 0; i < NumberOfRows(m); i++) { for (int j = 0; j < NumberOfColumns(m); j++) std::cout << std::setw(width) << m[i][j]; std::cout << std::endl; } } int main() { Matrix m = PascalTriangle(7); PrintMatrix(m, 10); return 0; } I get nothing on screen, and here's the same code just without matrix using vectors program (which works fine). Could you help me fix this code?
The main problem is that in PascalTriangle, you are starting out with an empty Matrix in both the number of rows and columns. Since my comments mentioned push_back, here is the way to use it if you did not initialize the Matrix with the number of elements that are passed in. The other issue is that NumberOfColumns should specify the row, not just the matrix vector. The final issue is that you should be passing the Matrix by const reference, not by value. Addressing all of these issues, results in this: Matrix PascalTriangle(int n) { Matrix mat; for (int i = 0; i < n; i++) { mat.push_back({}); // creates a new empty row std::vector<int>& newRow = mat.back(); // get reference to this row int a = 1; for (int j = 0; j < i + 1; j++) { if (j == 0) newRow.push_back(1); else newRow.push_back(a); a = a * (i - j) / (j + 1); } } return mat; } And then in NumberOfColumns: int NumberOfColumns(const Matrix& m, int row) { if (!m.empty()) return m[row].size(); return 0; } And then, NumberOfRows: int NumberOfRows(const Matrix& m) { return m.size(); } And last, PrintMatrix: void PrintMatrix(const Matrix& m, int width) { for (int i = 0; i < NumberOfRows(m); i++) { for (int j = 0; j < NumberOfColumns(m, i); j++) std::cout << std::setw(width) << m[i][j]; std::cout << std::endl; } } Here is a live demo
71,542,730
71,542,770
I am getting the error that variable "count" is not being initialized. But it should be initializing after reading and verifying data from file. C++
I am working on Login/Registration system. So far I am getting the error that the variable "count" is used without being initialized. bool count; string userId, password, id, pass; system("cls"); cout << "\t\t\n Please enter the username and password\n\n"; cout << "Username:"; cin >> userId; cout << "Password:"; cin >> password; //reads info from the file ifstream readL("record.txt"); while (readL >> id >> pass) { if (id == userId && pass == password) { count = true; } else { count = false; } } readL.close(); if (count == true) { cout << userId << " your LOGIN is successfull.\n\n"; main(); } else { cout << "\nLOGING error\n\nPlease check your username and password\n\n\n"; main(); } I have second part of the code and same system works here. ` case 1: { bool count; string suserId, sId, spass; cout << "\n\nEnter the username that you remember:"; cin >> suserId; //reads the file ifstream f2("records.txt"); while (f2 >> sId >> spass) { if (sId == suserId) { count = true; } else { count = false; } } f2.close(); if (count == true) { cout << "\n\n\tYour account is found!\n\nYour password is " << spass << endl << endl; main(); } else { cout << "\n\n\tSorry your account is not found." << endl << endl; main(); } break; } ` The only difference that in the first case it reads two variables during the while if statement, in second only Username. But even if I am going to read only Username in the first case error is still appearing.
Your C++ compiler is smart enough to figure out that if the file could not be opened or is empty, the while loop never executes even once, and count remains uninitialized until its value is checked after the loop. That's what your C++ compiler is telling you. Just because the input file exist or is not empty, and its contents are valid (because garbage in it will also result in the initial attempt to read it fail) is immaterial. It is logically possible for count to be uninitialized when its value gets used, hence your compiler's diagnostic. P.S. the while loop's logic is also fatally flawed, for a different reason. But that's unrelated to the compiler diagnostic you asked about.
71,543,391
71,547,943
Vertically flip text
I'm using Fontstash to load and render my text. However when I draw, the text is vertically flipped: flipped text I cannot change the origin so I think I have to rotate the texture here, however I'm not sure how to do it or if it's the proper way. I set the matrices like this: GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); glViewport(0, 0, viewport[2], viewport[3]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, viewport[2], viewport[3], 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity();
Wyck pointed out that I had face culling enabled, disabling it resolved the issue just fine when flipping the orthographic matrix.
71,543,491
71,544,653
what does char() print out in C++
I tried to find documentation on this but there doesn't seem to be any definite answers to this. I tried in an example program, and it seems to \0 but is this reliable behavior? What does char() initialize to and is this in the C++ standard. int main() { std::cout<<char()<<std::endl; return 0; }
The fact that char() returns \0 is normal, and it's reliable (integer variables are initialized to 0 with such a syntax, and pointers are initialized to nullptr). For example, unsigned short int() will also returns 0. For a char, it's obviously not the character "0", but the NUL character. Then, when trying to print that, you're trying to print a char that is used, in char* strings, to mark the end of the string... So without surprise, it isn't printed at all, even as a single character.
71,543,516
71,545,265
The adc should be able to work well for this kind of applications?
I've been trying to process speech on a stm32f407ve development board for some time now, which makes me wonder if the ADC is really set up to precisely sample the values. CMSIS FFT Functions. But when I try to couple it with the ADC in continuous conversion to sample a sine signal, it doesn't seem to sample well periodically. I put a sine signal into it from a frequency test of a 1khz sine wave from an internet video with a plug that I take out of some headphones, which by the way I already tested that it works correctly with an oscilloscope. So... this one from the development board is obviously not from a DSP but its ADC should work correctly for this type of application? Here is my code, obviously I made sure that the test was emitting voltage before the debug. #include "main.h" #include "arm_math.h" #include "arm_const_structs.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ #define Fs 4096; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ ADC_HandleTypeDef hadc1; /* USER CODE BEGIN PV */ #define SIGNAL_BUFFER_LENGTH 4096 float signalBuffer[2*SIGNAL_BUFFER_LENGTH]; float fftBuffer[2*SIGNAL_BUFFER_LENGTH]; float magnitudes[SIGNAL_BUFFER_LENGTH]; /* USER CODE END PV */ uint32_t k; uint32_t cont1,cont2; uint32_t start; uint32_t stopi; uint32_t delta; float32_t maxValue; /* Max FFT value is stored here */ uint32_t maxIndex; float frecuencia=10.0; float32_t Ts; float tiempo; /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_ADC1_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ #define ARM_CM_DEMCR (*(uint32_t*)0xE000EDFC) #define ARM_CM_DWT_CTRL (*(uint32_t*)0xE0001000) #define ARM_CM_DWT_CYCCNT (*(uint32_t*)0xE0001004) if(ARM_CM_DWT_CTRL !=0){ ARM_CM_DEMCR |= 1<<24; ARM_CM_DWT_CYCCNT =0; ARM_CM_DWT_CTRL |= 1<<0; } /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_ADC1_Init(); /* USER CODE BEGIN 2 */ Ts=1.0/(float)Fs; HAL_ADC_Start(&hadc1); for(k=0;k<2*SIGNAL_BUFFER_LENGTH;k+=2 ) { signalBuffer[k]=HAL_ADC_GetValue(&hadc1); } k++; //signalBuffer[0]=0; //start= ARM_CM_DWT_CYCCNT; arm_cfft_f32(&arm_cfft_sR_f32_len4096,signalBuffer,0,1); signalBuffer[0]=0; arm_cmplx_mag_f32(signalBuffer,magnitudes,4096); arm_max_f32(magnitudes, 4096, &maxValue, &maxIndex); //stopi = ARM_CM_DWT_CYCCNT; //delta=stopi-start; //tiempo=delta/8.0E07*1000.0; /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ }
You are just calling the function to take a single reading over and over in a loop. There is no reason to think that each pass through this loop will take the same amount of time. You need to set the ADC to be triggered from a timer in order to have some kind of reproducible sample rate. In general the internal ADC is not of suitable quality for audio use. There is an external audio codec fitted to this board, look at the example projects in the Stm32CubeF4 package.
71,543,726
71,543,774
GetLastError returns 998 when CreateWindow failed and returns 0
In main.cpp: #include "window.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { Window main_window(hInstance, nCmdShow); main_window.Intitialize(CS_HREDRAW, NULL, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_WINDOW), (WIDE_CHAR) "Application", (WIDE_CHAR) "WindowName"); return main_window.Show(); } In window.h: #include <stdio.h> #ifndef _WINDOW_H_ #define _WINDOW_H_ #include <windows.h> typedef wchar_t* WIDE_CHAR; typedef HINSTANCE INSTANCE; typedef HWND HANDLE_WINDOW; typedef tagWNDCLASSEXW WINDOW_CLASS; LRESULT Procedure(HANDLE_WINDOW, UINT, WPARAM, LPARAM); class Window { private: INSTANCE instance; int show_command; WINDOW_CLASS window_object; HANDLE_WINDOW handle; public: Window(INSTANCE instance, int show_command) { this->instance = instance; this->show_command = show_command; } void Intitialize(UINT style, HICON icon, HCURSOR cursor, HBRUSH background, WIDE_CHAR class_name, WIDE_CHAR title) { window_object.cbSize = sizeof(WINDOW_CLASS); window_object.cbClsExtra = 0; window_object.cbWndExtra = 0; window_object.hInstance = instance; window_object.lpfnWndProc = Procedure; window_object.style = style; window_object.hIcon = icon; window_object.hCursor = cursor; window_object.hbrBackground = background; window_object.lpszMenuName = NULL; window_object.lpszClassName = class_name; window_object.hIconSm = NULL; RegisterClassExW(&window_object); printf("%lld", GetLastError()); handle = CreateWindowExW(WS_EX_CLIENTEDGE, class_name, title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1080, 720, NULL, NULL, instance, NULL); } int Show() { ShowWindow(handle, show_command); UpdateWindow(handle); MSG message; while (GetMessageW(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessageW(&message); } return message.wParam; } }; LRESULT Procedure(HANDLE_WINDOW handle, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CLOSE: DestroyWindow(handle); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(handle, message, wParam, lParam); break; } return 0; } #endif I tried to wrap the Win32 interface and tried to make a window, but I always got stuck in some weird places, like the Unicode... First of all, I can't fully understand the use and conversion of wide characters. I think a large part of the reason for the failure of window registration and window creation is in the use of wide and normal characters. Secondly, I don't understand why I can't use the namespace "std", once I use it, even window registration fails.
You are passing (WIDE_CHAR) "Application" and (WIDE_CHAR) "WindowName" to Intitialize. As you defined typedef wchar_t* WIDE_CHAR; the parameters are NARROW characters cast to WIDE characters. When CreateWindowExW tries to access them, it goes out-of-bounds (because wide string is twice as long as narrow), resulting in error: ERROR_NOACCESS 998 (0x3E6) Invalid access to memory location. according to https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--500-999- Do this instead: main_window.Intitialize(CS_HREDRAW, NULL, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_WINDOW), L"Application", L "WindowName");
71,543,860
71,543,892
Why sort function in Go and C++ is different? And I can't get the right results in Go
I want to sort a slice named nums while not disrupting the original order. So I use inds to record the index of nums and sort inds: vector<int> nums = {1,3,2,1,1,1}; vector<int> inds = {0,1,2,3,4,5}; sort(inds.begin(), inds.end(), [nums](int i, int j) -> bool { return nums[i] > nums[j]; }); for(int i : inds) { cout << i; } The inds is 120345 after sort. While in Go, I test: nums := []int{1,3,2,1,1,1} inds := []int{0,1,2,3,4,5} sort.Slice(inds, func(i, j int) bool { return nums[i] > nums[j] }) fmt.Println(inds) And The inds is [1 0 2 3 4 5] after sort, which is different from the result of C++ and what I expected. Why Go can't sort inds well?
The anonymous function arguments i and j are indices in inds, but the program uses the arguments as indices in nums. Fix by using inds to translate the index values to nums: sort.Slice(inds, func(i, j int) bool { return nums[inds[i]] > nums[inds[j]] })
71,543,991
71,544,098
I got a error ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1
i am learning to implement a simple Stack base machine using Linklist with c++. There are constant.h, Stackframe.h, StackFrame,cpp, main.cpp. I code on MacOs 10.14.6 with Visual Studio Code. I am getting some trouble when i run main.cpp file. Here is error that i got: cd "/Volumes/public/initial/" && g++ main.cpp -o main && "/Volumes/public/initial/"main [MACs-MacBook-Pro:CTDL/BTL/stack-machine-master] macosx% cd "/Volumes/public/initial/" && g++ main.cpp -o main && "/Volumes/public/initial/"main Undefined symbols for architecture x86_64: "StackFrame::run(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from: test(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main-403bc1.o "StackFrame::StackFrame()", referenced from: test(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main-403bc1.o "StackFrame::~StackFrame()", referenced from: test(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main-403bc1.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) My code is below. constant.h: #ifndef __JAVM_CONSTANTS_H__ #define __JAVM_CONSTANTS_H__ #define OPERAND_STACK_MAX_SIZE 32 #define LOCAL_VARIABLE_ARRAY_SIZE 256 #endif // !__JAVM_CONSTANTS_H__ StackFrame.h #ifndef __STACK_FRAME_H__ #define __STACK_FRAME_H__ #include <string> /* StackFrame declaration */ class StackFrame { int opStackMaxSize; // max size of operand stack int localVarArrSize; // size of local variable array public: /* Constructor of StackFrame */ StackFrame(); /* Destructor of StackFrame */ ~StackFrame(); /* Run the method written in the testcase @param filename name of the file */ void run(std::string filename); //Instruction }; #endif // !__STACK_FRAME_H__ StackFrame.cpp #include "StackFrame.h" #include <iostream> #include <fstream> #include "constants.h" using namespace std; StackFrame::StackFrame() : opStackMaxSize(OPERAND_STACK_MAX_SIZE), localVarArrSize(LOCAL_VARIABLE_ARRAY_SIZE) {} StackFrame::~StackFrame() {} void StackFrame::run(string filename) { cout<<filename<<endl; } main.cpp #include <iostream> #include "StackFrame.h" using namespace std; /* Run the testcase written in `filename` @param filename name of the file */ void test(string filename) { StackFrame *sf = new StackFrame(); try { sf->run(filename); } catch (exception& e) { cout << e.what(); } delete sf; } /* Main function */ int main() { string s = "test000.txt"; test(s); return 0; } Hope you guys will help me. (Sorry for my bad English)
You haven't told g++ to compile and link in StackFrame.cpp. Where you have $ g++ main.cpp -o main you should have $ g++ main.cpp StackFrame.cpp -o main -lstdc++ The addition of -lstdc++ might not be required with newer versions of g++.
71,544,120
71,544,149
It is possible to assign an object to another with a different type
I'm working with a C++ project and I need to do some assignment code to assign one object to another with a different type like this: MyClass1 o1; MyClass2 o2; o2 = o1; Ofc, we can make this work with the help of a copy assignment operator of MyClass2: MyClass2& operator=(const MyClass1&). But this gonna be a very heavy job for me because there has been thousands of classes, which need to do the assignment like o2 = o1. I don't want to add a copy assignment operator for each of them one by one... I'm thinking if there is some other way, such as some TMP method to help me... I can ensure that MyClass1 and MyClass2 have exactly the same data members with the same declaration order (see below). If so, is there some TMP method, which could help me? struct MyClass1 { int a; char ch; std::string msg; // some virtual member functions }; struct MyClass2 { int a; char ch; std::string msg; // some virtual member functions }; BTW, you may want to ask why there are such two classes/structs with the same data members. Well, this is about some historical reason, I can't fusion them onto one class/struct. UPDATE It seems that I didn't make my question clear. I'll make an example here. void doJob(const MyClass1& o1) {} void func1(MyClass1 o1) { doJob(o1); } void func2(MyClass2 o2) { MyClass o1; o1.? = o2.?; // assign each element of o2 to o1. doJob(o1); } Here is the real case. As you see, o1.? = o2.? contains multi lines, it depends on how many data members of MyClass1/MyClass2. I'm trying to find some way to avoid this stupid assignment of all data members one by one in the func2. Also, as I said, I have thousands of classes like MyClass1/MyClass2, meaning that these classes have totally different data members. So for MyClass1 and MyClass2, o1.? = o2.? is o1.a = o2.a; o1.ch = o2.ch; o1.msg = o2.msg; But for other classes, it may become o1.f = o2.f; o1.vec = o2.vec;. That's why I'm thinking I may need some TMP technique... UPDATE2 Alice developed the classes: struct MyClass1 {// data members}; struct MyClass2 {// data members}; // MyClass1 and MyClass2 have exactly the same data members and declaration order struct MyClass3 {// data members}; struct MyClass4 {// data members}; // MyClass3 and MyClass4 have exactly the same data members and declaration order ... ... struct MyClass1000 {// data members}; struct MyClass1001 {// data members}; // MyClass1000 and MyClass1001 have exactly the same data members and declaration order I'm developing the functions: void doJob1(const MyClass1& o1) {} void func1(MyClass1 o1) { doJob(o1); } void func2(MyClass2 o2) { MyClass1 o1; o1.? = o2.?; // assign each element of o2 to o1. doJob1(o1); } ... ... void doJob1000(const MyClass1000& o1) {} void func1000(MyClass1000 o1) { doJob1000(o1); } void func1001(MyClass1001 o2) { MyClass1000 o1; o1.? = o2.?; // assign each element of o2 to o1. doJob1000(o1); } Why did Alice do such a stupid design? For some historical reason... Why not using std::memcpy? Because these classes contain virtual functions.
yes, you can... but I is not recommended unless the two classes have an exact one to one correspondence and the exact same meaning in the domain of your problem. Why is not recommended? Because the operation needs to be manually implemented (the compiler cannot help with a = default declaration). auto operator=(MyClass1 const& other) -> MyClass2& { std::tie(a, ch, msg) = std::tie(other.a, other.ch, other.msg); return *this; } Because if you defined assignment, you will eventually need to define equality (==), and inequality (!=) and in both directions. Otherwise the clases will not behave logically. bool operator==(MyClass1 const& mc1, MyClass2 const& mc2) { return std::tie(mc1.a, mc1.ch, mc1.msg) == std::tie(mc2.a, mc2.ch, mc2.msg); } bool operator==(MyClass2 const& mc2, MyClass1 const& mc1) { return std::tie(mc1.a, mc1.ch, mc1.msg) == std::tie(mc2.a, mc2.ch, mc2.msg); } bool operator!=(MyClass1 const& mc1, MyClass2 const& mc2) { return std::tie(mc1.a, mc1.ch, mc1.msg) != std::tie(mc2.a, mc2.ch, mc2.msg); } bool operator!=(MyClass2 const& mc2, MyClass1 const& mc1) { return std::tie(mc1.a, mc1.ch, mc1.msg) != std::tie(mc2.a, mc2.ch, mc2.msg); } Because if you define assignment, you will to define a constructor or a conversion from one to the other. /*explicit?*/ operator MyClass1() const& {return {a, ch, msg};} // need thios and a move constructor? /*explicit?*/ operator MyClass1() && {return {a, ch, std::move(msg)};} // need this if one can be ordered the other also, and you will need to define order between the two classes, in both directions // won't even try // bool operator< // bool operator<= // bool operator> // bool operator>= // bool operator< // bool operator<= // bool operator> // bool operator>= and for that matter any function that work with one should work with the other, because well, when you assign you are saying that two things are logical equal among other tings. full code here: https://godbolt.org/z/c8d34eT48 While it seems to be your case (albeit a very suspicious case), as you see, you open a Pandora's box by defining equality between two classes. Just by calling the "assignment" convert instead you save your self a big headache. Don't use operator=. My recommended code is to just use another name: MyClass2& convert(MyClass1 const& from, MyClass2& to) { std::tie(to.a, to.ch, to.msg) = std::tie(from.a, from.ch, from.msg); return to; } MyClass2& convert(MyClass1&& from, MyClass2& to) { std::tie(to.a, to.ch, to.msg) = std::tie(from.a, from.ch, std::move(from.msg)); return to; } More material: https://www.youtube.com/watch?v=ABkxMSbejZI Once you understand the drawbacks, std::tie can help you (as shown). Also, if all classes are public and simple, Boost.PFR https://www.boost.org/doc/libs/1_78_0/doc/html/boost_pfr.html
71,544,411
71,544,449
Iterate over a vector and create another vector based on elements
Maybe a stupid/naive question, but if I have a vector of vectors like this: std::vector<std::vector<Element> vec what is the most efficient way to create another vector from this one which containes all the sizes of elements from the previous vector: std::vector<std::size_t> newVector = {vec[0].size(), ..., vec[vec.size()-1].size()} is there a function for stuff like this? Thanks in advance.
There might be a 1-liner approach using something from <algorithm> or fancy accumlator/transform routine. But it's hard to beat the readability of this: std::vector<std::size_t> newVector; for (const auto& item : vec) { newVector.push_back(item.size()); } If you prefer the hip way to do it, which some people like, but in my opinion makes for rather unreadable code. vector<int> newVec(vec.size()); std::transform(vec.begin(), vec.end(), newVec.begin(), [](vector<int>& v) {return v.size(); });
71,544,619
71,544,724
Allocating memory to a list stl inside class through user
class Graph { int num; public: Graph(int n) { num = n; } list<int>* mylist = new list<int>[num]; int* arr = new int[num]; queue<pair < int, int >> pq; void accept(); }; int main() { int n; cout << "Enter the number of vertices="; cin >> n; Graph g=Graph(n); g.accept(); } I have this class of graph and I want to allocate memory of size 'num' which is the input from user in the main function. But it shows bad memory allocation.
You should learn about C++'s initialization, which is important and different from assignment. In you example, initialization of mylist and arr happens before "initialization" of num (in fact, you are not initializing num, what you do is default-initialize it and then assign to it), hence the value of num is indeterminate at that point, and new complains "bad memory allocation". Correct way of initializing members: class Graph { // write data members together, // their declaration positions in class do not indicate execution order int num; list<int>* mylist; int* arr; queue<pair < int, int >> pq; void accept(); public: Graph(int n) : num(n), mylist(new list<int>[n]), arr(new int[n]) // member initializer list start with a ":" and followed by a list of // member_name(initializer_for_this_member) // note their order should match the declaration order { // usually initialization all happen in the initializer list, // and constructor body is empty } }; And as πάντα ῥεῖ pointed out, you should avoid using new as much as possible and opt for standard container. In you example, I guess you want an dynamic array of list, and a dynamic array of number. You can use std::vector for this purpose. class Graph { int num; vector<list<int>> mylist; vector<int> arr; queue<pair < int, int >> pq; void accept(); public: Graph(int n) : num(n), mylist(n), arr(n) { } // initialize vector to contain n value-initialized objects };
71,544,912
71,544,964
wrapping templated function call in another function call
Anyone know if it is possible to do something similar to the following: void my_inner_func(int i, double d, ...) { // do stuff here } template <typename Func, typename... Args> void my_outer_func(Func&& f,Args&&... args){ // do other stuff here, put this inside loop, etc f(std::forward<Args>(args)...); } template <typename OuterFunc,typename InnerFunc,typename... Args> void func(OuterFunc&& outer, InnerFunc&& inner, Args&&...args) { outer(std::forward<InnerFunc>(inner),std::forward<Args>(args)...); } Where the calling code might look something like this: func(my_outer_func, my_inner_func, 1, 2.0, ...); The issue that I am running into is that the type of the OuterFunction cannot be deduced. I've tried a bunch of different things including converting func to a functor and making OuterFunc a template template parameter.
It works if you make my_outer_func a function object rather than a function: struct my_outer_func { template <typename Func, typename... Args> void operator()(Func&& f,Args&&... args) const { // do other stuff here, put this inside loop, etc f(std::forward<Args>(args)...); } }; Then: func(my_outer_func(), my_inner_func, 1, 2.0); If you don't like the parentheses at the call site, you can remove them if you create a global struct instance instead: struct { template <typename Func, typename... Args> void operator()(Func&& f,Args&&... args) const { // do other stuff here, put this inside loop, etc f(std::forward<Args>(args)...); } } my_outer_func;
71,545,204
71,545,266
Accessing an std::set via a dereferenced iterator
Consider: #include <stdio.h> #include <set> void printset(std::set<int>& Set) { for (std::set<int>::iterator siter = Set.begin(); siter != Set.end(); ++siter) { int val = *siter; printf("%d ", val); } } void printsetofset0(std::set<std::set<int>>& SetofSet) { for (std::set<std::set<int>>::iterator siter = SetofSet.begin(); siter != SetofSet.end(); ++siter) { std::set<int> Set = *siter; printset(Set); } } void printsetofset1(std::set<std::set<int>>& SetofSet) { for (std::set<std::set<int>>::iterator siter = SetofSet.begin(); siter != SetofSet.end(); ++siter) { printset(*siter);//this line gives error } } printsetofset1 with the printset(*siter); gives error: <source>: In function 'void printsetofset1(std::set<std::set<int> >&)': <source>:20:34: error: binding reference of type 'std::set<int>&' to 'const std::set<int>' discards qualifiers 20 | printset(*siter); | ^~~~~~ <source>:4:38: note: initializing argument 1 of 'void printset(std::set<int>&)' 4 | void printset(std::set<int>& Set) { | ~~~~~~~~~~~~~~~^~~ Compiler returned: 1 See Godbolt Link here. printsetofset0 with the lines: std::set<int> Set = *siter; printset(Set); compiles and works just fine. What is the reason why one printsetofset0 works, while seemingly functionally equivalent (and shorter) preintsetofset1 does not work?
The elements, which the iterator points to, are constant. You can read it here in the Notes: Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions.. But, passing a reference to your printset function would violate this property. Internally, sets allow fast access via index structures. Changing the elements would require to reorder the set (internally). You can solve the situation by adding a const modifier to the parameter of your printset function: void printset(const std::set<int>& Set)
71,545,531
71,547,907
Asio difference between work(), require() and make_work_guard()
Sorry to interrupt, I am a newbie in C++ and Asio... I just come from here Asio difference between prefer, require and make_work_guard. I am trying to make a "dummy work" for my io_context. It is really confusing to a beginner who just wants to make a simple "UDP socket". The ancient book from Packt and Youtube (https://www.youtube.com/watch?v=2hNdkYInj4g&t=2292s) tutorial tells me to use "work()", the old document tell me to use a much more complex class called "excutor_work_guard", and the new fashion document just tell me to use something extremely unreadable "require()"... Could I just use "make_work_guard()" and forget about everything else? Sorry for my English...
As you state yourself, this is a full duplicate of the linked question. The answer there answers every point you make here. The ancient book from Packt and Youtube (https://www.youtube.com/watch?v=2hNdkYInj4g&t=2292s) tutorial tells me to use "work()" I have bad experiences with Packt books on Asio¹. Regardless, there was never a function work(). You probably meant boost::asio::io_service svc; boost::asio::io_service::work work(svc); The newer interface is indeed boost::asio::io_context ioc; auto work = make_work_guard(ioc); That's it. and the new fashion document just tell me to use something extremely unreadable "require()"... I have never (ever) seen that anywhere. Can you point me to the place where you found that? In fact, as the linked answer points out, it can be a bad idea to tie work to executors, because it spreads by copying, losing control and inviting deadlocks. Could I just use "make_work_guard()" and forget about everything else? Yeah. That's what the other answer already said. If you're in doubt, just re-read the summary there :) ¹ e.g. see Crash : terminate called after throwing an instance of 'std::system_error' what(): Resource deadlock avoided
71,545,613
71,545,689
sorting int from a text file in an ascending order
So i have a text file that looks like this: 5 4 9 -3 0 2 first int shows how many int their are that need to be ordered in ascending order so the output looks like this: -3 0 2 4 9 Im trying to do it without any additional libraries and just use #include <iostream> #include <fstream> So far my code reads the first int but when want it to read the rest it doesnt work. Im still stuck at the reading part. int main() { ifstream input; int a,N,i,j; int temp; // Open the file. input.open("test.txt"); if (!input) { cerr << "Could not open the file - '"<< endl; return EXIT_FAILURE; } // Read the numbers of int from the file cout<<"Input fail data"<<endl; input>>N; cout<<"integers: "<<N<<endl; int data[N]; // for(i = 0; i << N; i++){ input>>data[i]; P.S. Shoud the rest of the integers be in an array or a linked list?
So, I tried your code and it worked after some minor changes, which only address the ability for compilation but not the actual approach to read the data. The code considers your restriction to only include iostream and fstream. #include <iostream> #include <fstream> int main() { std::ifstream input("test.txt"); if (!input) { std::cerr << "Could not open the file - '"<< std::endl; return -1; } // Read the numbers of int from the file int N; input >> N; std::cout << "reading " << N << " integers: " << std::endl; int* data = new int[N]; for(int i = 0; i < N; i++){ input >> data[i]; std::cout << data[i] << std::endl; } delete[] data; } Maybe there is something wrong in your code beyond the reading part.
71,545,705
71,554,084
Find closest point from point outside polygon mesh to polygon mesh
I have a polygon mesh defining a valid inner region and a point outside of this polygon mesh. From this point i want to find the closest point on the surface on my polygon mesh. I have no background in computational geometry and don't know the buzzwords. How can i achieve this using cgal or any other library in C++?
You might have a look at the Location Functions in CGAL.
71,545,803
71,545,900
Cryptographically hash multiple keys
How to hash using SHA1(or similar cryptogrphical functions) a class(or struct) which has multiple keys, e.g., struct Foo{ string name; int age; int score; } A naive approach is hash(has(name) + hash(age) + hash(score)), but hash collision is possible.
Either hash the whole structure directly if it contains only POD (i.e. nothing allocated within and its sizeof is a constant): either you can use an union to get a proper byte array, or you use a cast to obtain a char* to provide to hash function. If you have dynamic data inside your struct/class, you need to serialize all data and send them to the hash function - obviously, its size will vary during execution, because of dynamic data. But you must call hash only ONCE per data structure, and in NO WAY adding hashes together - that's a nonsense. You can also use a framework feature that will serialize your struct/class to a text stream (often XML or JSON format), and hash this serialization instead of the binary structure. How to do all this is obviously platform-dependent - which cryptography API do you use, if you prefer. By applying these principles, the collision (totally unavoidable, mathematically proven) won't be more than for any other kind of hashed data.
71,545,818
71,574,301
Who is responsible for destructing the block scoped static Singleton instance?
I couldn't understand how the program below compiles successfully. class SomeClass { public: /** Singleton **/ static SomeClass &instance() { static SomeClass singleInstance; return singleInstance; }; private: SomeClass() = default; SomeClass(const SomeClass&) = delete; SomeClass &operator=(const SomeClass&) = delete; ~SomeClass() {} }; int main() { SomeClass::instance(); // SomeClass::instance().~SomeClass(); // Compiles if destructor was public return 0; } Who is responsible for calling the destructor of the Singleton instance? How does the underlying mechanism access a private method?
Shortly, during the construction, the compiler saves the destructor to a list of functions that will be called at the very end of the program. In the end, the list of functions, including the destructors, are called one by one and the safe destruction occurs. Underlying Mechanism The core of the mechanism is the exit() and atexit(..) functions provided by the C standard library. During the compilation of the program, the compiler injects some other codes around your block-scoped static variable. A pseudo representation is as below. static SomeClass& instance() { static SomeClass singleInstance; /*** COMPILER GENERATED ***/ // Guard variable generated by the compiler static bool b_isConstructed = false; if(!b_isConstructed) ConstructInstance(); // Constructs the Singleton instance b_isConstructed = true; // Push destructor to the list of exit functions atexit(~SomeClass()); } /*** COMPILER GENERATED ***/ return singleInstance; }; The point here is to call the atexit(~SomeClass()) and register the destructor to the automatic call list of the exit() function which is implicitly called when you return from the main(..). As the function pointers are used instead of directly referring to the private destructor method, the access specifier protection mechanism is skipped.
71,545,978
71,546,170
Fastest way for getting last index of item in vector in C++?
Let's say you have a vector of ints, unsorted and with multiple repeating items, like so: vector<int> myVec{1, 0, 0, 0, 1, 1, 0, 1,0,0} What is the fastest way to get the last index of 1 which is 8 for this example, other than looping through it from its end? Would this be different if the vector would contain other items than 0 and 1? What is the fastest way to do this in C++? L.E. I have seen the duplicate topic suggestions but even it dolves partially what I am looking for this has nothing to do with the minimum element in vector so I keep the question maybe it will help someone else too.
Use std::max_element and reverse iterators. And that is looping through the vector. If it is unsorted, there is no faster way.
71,546,411
71,546,466
C++ compiler waring C26409 - avoid calling new and delete
Here is my code that I'm getting (Warning C26409 Avoid calling new and delete explicitly, use std::make_unique instead (r.11).) after doing a Visual Studio 2019 Code Analysis: #include <windows.h> #include <strsafe.h> int main() { auto *sResult = new WCHAR[256]; StringCchPrintfW(sResult, 256, L"this is a %s", L"test"); delete[] sResult; } I was under the assumption to use new/delete instead of calloc/free, but now the compiler is telling me to use std::make_unique. I can't find any examples on how I can change my code to be compliant. So my questions are: how do I change my code so it doens't use new/delete why should I not use new/delte vs std::make_unique?
The warning is somewhat confusing, because it assumes that you need some direct memory allocation. If fact, you don't: #include <windows.h> #include <strsafe.h> #include <vector> int main() { std::vector<WCHAR> sResult(256); StringCchPrintfW(sResult.data(), sResult.size(), L"this is a %s", L"test"); } or int main() { WCHAR sResult[256]; StringCchPrintfW(sResult, 256, L"this is a %s", L"test"); } The idea is to use static storage when you can (small data) to be more efficient (no OS memory call), and use std::vector when you must allocate because the size is either unknown at compile time or too big for the stack and let STL do the work for you. The usage of std::make_unique is when you indeed need to call new directly or indirectly and have it auto-destruct later. TL;DR: Read about modern C++ memory management.
71,546,524
71,546,578
double precision in C++, 308 digits or 15 digits?
If double can represent value up to 3.4E308 (308 zeros), then why do we say that double stores only 15 digits? What is point of saying "ten power of 308" ?
We don't say that "double stores only 15 digits". We say that "double has 15 digits of precision". It means that the computed value of double, when printed as a base-10 sequence of digits, is accurate only up to those 15 digits. double can represent 3.4E308. Yes, to print it you need more than 15 digits of precision. Some particular values have those guarantees thanks to floating-point implementation. But, for example, a number 3.4E308 - 1, which is inside of double's range, cannot be represented accurately by a double. If you want to be sure, just take the first 15 digits of double. Some values can be correctly represented with more than 15 digits, but some cannot. Every value in double's range will be correctly represented up to the 15th digit of its decimal representation.
71,546,874
71,546,932
How to print string in C++ using getline
Why this doesn't print the first word of sentence? #include <iostream> #include <string> int main() { std::string sentence; std::cout<<"Enter sentence: "; std::cin>>sentence; std::getline(std::cin,sentence); std::cout<<sentence; return 0; } If I enter "This is text" output would be " is text"
You dont need the first cin (std::cin>>sentence;), this will solve your problem #include <iostream> #include <string> int main() { std::string sentence; std::cout<<"Enter sentence: "; std::getline(std::cin,sentence); std::cout<<sentence; return 0; }
71,547,246
71,548,880
Array of elements all end up with the same value despite being initialized with different values
#include<cstring> #include<iostream> using namespace std ; class CSR { private: char* csrName; public: void setName(char* n)//a setter for name { csrName = n; } char* getName()//a getter for employee’s name { return csrName; } }; int main() { CSR employees[7]; for(int i=0;i<7;i++) { char name[] = { 'E', 'M', 'P', char(i + 49), '\0' }; employees[i].setName( name); } for(int i=0;i<7;i++) { cout<<employees[i].getName()<<endl; } } /* I am not getting the desired output which is EMP1 EMP2 EMP3 EMP4 EMP5 EMP6 EMP7 When I run this program I am getting EMP7 EMP7 EMP7 EMP7 EMP7 EMP7 EMP7 */
What you are basically doing is that you are pointing your name variable towards the memory that is allocated to the parameter i.e (n) but the problem is that n gets destroyed every time the function stops its execution. What you should do is point your name variable to a new memory location and run a loop so that it holds the same value as the parameter and not the same memory location. Like so void setName(char* n)//a setter for name { csrName = new char [30]; // I just took the size as random, you can change it. for (int i = 0; n[i - 1] != '\0'; i++) { csrName[i] = n[i]; } }
71,547,301
71,549,086
How is date encoded/stored in MySQL?
I have to parse date from raw bytes I get from the database for my application on C++. I've found out that date in MySQL is 4 bytes and the last two are month and day respectively. But the first two bytes strangely encode the year, so if the date is 2002-08-30, the content will be 210, 15, 8, 31. If the date is 1996-12-22, the date will be stored as 204, 15, 12, 22. Obviously, the first byte can't be bigger than 255, so I've checked year 2047 -- it's 255, 15, and 2048 -- it's 128, 16. At first I thought that the key is binary operations, but I did not quite understand the logic: 2047: 0111 1111 1111 255: 0000 1111 1111 15: 0000 0000 1111 2048: 1000 0000 0000 128: 0000 1000 0000 16: 0000 0001 0000 Any idea?
Based on what you provide, it seems to be N1 - 128 + N2 * 128.
71,547,513
71,547,645
C++ vector data strucure, loop only half of elements
how to loop only half of the elements in C++ vector data structure using auto keyword vector<string> InputFIle; void iterateHalf(){ /* iterate only from begin to half of the size */ for (auto w = InputFIle.begin(); w != InputFIle.end(); w++) { cout << *w << " : found " << endl; } }
You need to compute begin and end of your loop, i.e. first and last_exclusive. #include <vector> #include <numeric> #include <iostream> int main(){ std::vector<int> vec(16); std::iota(vec.begin(), vec.end(), 0); size_t first = 3; size_t last_exclusive = 7; //loop using indices for(size_t i = first; i < last_exclusive; i++){ const auto& w = vec[i]; std::cout << w << " "; } std::cout << "\n"; //loop using iterators for(auto iterator = vec.begin() + first; iterator != vec.begin() + last_exclusive; ++iterator){ const auto& w = *iterator; std::cout << w << " "; } std::cout << "\n"; }
71,547,561
71,547,694
Incorrect timing in release mode
I'm trying to measure time of execution of the following code: #include <iostream> #include <cmath> #include <stdio.h> #include <chrono> uint64_t LCG(uint64_t LCG_state) { LCG_state = (LCG_state * 2862933555777941757 + 1422359891750319841); return LCG_state; } int main() { auto begin = std::chrono::high_resolution_clock::now(); uint64_t LCG_state = 333; uint32_t w; for(int i=0; i<640000000; i++) { LCG_state = LCG(LCG_state); w = LCG_state >> 32; //std::cout << w << "\n"; } auto end = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9); } I'm using option release in Code Blocks (because I think I should if I want to measure it right). Problem is that time measured is 0 s every time. What's more if I would do loop: #include <iostream> #include <cmath> #include <stdio.h> #include <chrono> uint64_t LCG(uint64_t LCG_state) { LCG_state = (LCG_state * 2862933555777941757 + 1422359891750319841); return LCG_state; } int main() { auto begin = std::chrono::high_resolution_clock::now(); uint64_t LCG_state = 333; uint32_t w; for(int i=0; i<10000; i++) { for(int i=0; i<640000000; i++) { LCG_state = LCG(LCG_state); w = LCG_state >> 32; //std::cout << w << "\n"; } } auto end = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9); } Then still measurerd time is 0 s. In debug trybe everything works right, but measuring time of code with debug make no sense right? Especially I would like to compare it to for example this: #include <stdint.h> #include <iostream> uint64_t s[2] = {5,11}; uint64_t result; uint64_t next(void) { uint64_t s1 = s[0]; uint64_t s0 = s[1]; uint64_t result = s0 + s1; s[0] = s0; s1 ^= s1 << 23; // a s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); // b, c return result; } int main() { for(int i=0; i<160000000; i++) //while (true) { //std::cout << next() << "\n"; result = next(); //char *c = reinterpret_cast<char*>(&result); //std::cout.write(reinterpret_cast<char*>(&result), sizeof result); } } I want to know what is faster. How to measure it right? Why is the execution time 0 seconds, does the code not execute at all?
You can add an empty asm statement dependent on the variable w #include <iostream> #include <cmath> #include <stdio.h> #include <chrono> uint64_t LCG(uint64_t LCG_state) { LCG_state = (LCG_state * 2862933555777941757 + 1422359891750319841); return LCG_state; } int main() { auto begin = std::chrono::high_resolution_clock::now(); uint64_t LCG_state = 333; uint32_t w; for(int i=0; i<640000000; i++) { LCG_state = LCG(LCG_state); w = LCG_state >> 32; __asm__ volatile("" : "+g" (w) : :); } auto end = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9); } This is opaque to the compiler and will prevent the loop from being optimized out
71,547,967
71,606,613
HIP-Clang Inline Assembly
What is the Hip-Clang equivalent of this CUDA function? __device__ __forceinline__ uint32_t add_cc(uint32_t a, uint32_t b) { uint32_t r; asm volatile ("add.cc.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b)); return r; } I'm porting a CUDA project to HIP-Clang that contains inline PTX assembly. The function is used to implement multi-precision addition in the NVIDIA GPU. I tried: asm volatile ("add.cc.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b)); //invalid instruction asm volatile ("V_ADD_CO_U32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b)); //invalid operand for instruction asm volatile ("V_ADD_CO_U32 %0, %1, %2;" : "=v"(r) : "v"(a), "v"(b)); //operands are not valid for this GPU or mode The target hardware is RX 6800. AMD clang version 14.0.0. Is RDNA2 the correct instruction set reference? Is this LLVM user guide to AMDGPU backend an applicable reference?
It turns out the answer is hardware dependent. For my hardware for which the compiler defines __gfx1030__ the correct syntax is asm volatile ("v_add_co_u32 %0, vcc_lo, %1, %2;" : "=v"(r) : "v"(a), "v"(b)); For earlier architechtures such as __gfx900__ replace vcc_lo with vcc See the discussion on the Rocm Hip Github and this AMD gpu assembly reference.