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,187,137 | 71,188,186 | How to pass and return an object to a C++ function called from iOS Swift? | In my iOS project, I want to call a C++ function from my Swift code that takes an object from my Swift code and returns another object.
So far, following this tutorial and adding a little bit more stuff, I managed to call a C++ function that takes a simple parameter and returns a string:
I create the NativeLibWrapper.h file:
#import <Foundation/Foundation.h>
@interface NativeLibWrapper : NSObject
- (NSString *) sayHello: (bool) boolTest;
@end
I create the NativeLibWrapper.mm file:
#import <Foundation/Foundation.h>
#import "NativeLibWrapper.h"
#import "NativeLib.hpp"
@implementation NativeLibWrapper
- (NSString *) sayHello: (bool) boolTest {
NativeLib nativeLib;
std::string retour = nativeLib.sayHello(boolTest);
return [NSString stringWithCString: retour.c_str() encoding: NSUTF8StringEncoding];
}
@end
I create the NativeLib.hpp file:
#ifndef NativeLib_hpp
#define NativeLib_hpp
#include <stdio.h>
#include <string>
class NativeLib
{
public:
std::string sayHello(bool boolTest);
};
#endif /* NativeLib_hpp */
I create the NativeLib.cpp file:
#include "NativeLib.hpp"
std::string NativeLib::sayHello(bool boolTest)
{
return "Hello C++ : " + std::to_string(boolTest);
}
I add the following in Runner/Runner/Runner-Bridging-Header.h:
#import "NativeLibWrapper.h"
And finally, I call the C++ function in Swift:
NativeLibWrapper().sayHello(true)
But now, let's say that my C++ sayHello() function takes this kind of object as a parameter (so I can access it in the C++ function):
class TestAPOJO {
var value1 = ""
var value2 = false
}
and returns this kind of object (generated from the C++ function but then mapped into a Swift object, or something like that):
class TestBPOJO {
var value3 = 0.0
var value4 = false
}
How can I achieve that?
Thanks.
| OK so here is what I did to make it work:
create Objective-C TestAPOJO and TestBPOJO classes:
// TestAPOJO.h:
#import <Foundation/Foundation.h>
@interface TestAPOJO : NSObject
@property NSString *value1;
@property bool value2;
@end
// TestAPOJO.mm:
#import "TestAPOJO"
@implementation TestAPOJO
@end
create C++ TestAPOJOFromC and TestBPOJOFromC classes:
// TestAPOJOFromC.hpp:
#ifndef TestAPOJOFromC_hpp
#define TestAPOJOFromC_hpp
class TestAPOJOFromC
{
public:
TestAPOJOFromC();
~TestAPOJOFromC();
std::string value1;
bool value2;
};
#endif /* TestAPOJOFromC_hpp */
// TestBPOJOFromC.cpp:
#include "TestBPOJOFromC.hpp"
TestBPOJOFromC::TestBPOJOFromC()
{
value1 = "";
value2 = false;
}
TestBPOJOFromC::~TestBPOJOFromC() = default;
in the NativeLibWrapper.h file, add:
- (TestBPOJO *) getTestPOJOS: (TestAPOJO *) testAPOJO;
in the NativeLibWrapper.mm file, add:
- (TestBPOJO *) getTestPOJOS: (TestAPOJO *) testAPOJO {
NativeLib nativeLib;
TestAPOJOFromC *testAPOJOFromC = new TestAPOJOFromC();
testAPOJOFromC->value1 = std::string([testAPOJO.value1 UTF8String]);
testAPOJOFromC->value2 = testAPOJO.value2;
TestBPOJOFromC * testBPOJOFromC = nativeLib.getTestPOJOS(testAPOJOFromC);
TestBPOJO *testBPOJO = [TestBPOJO new];
testBPOJO.value3 = testBPOJOFromC->value3;
testBPOJO.value4 = testBPOJOFromC->value4;
return testBPOJO;
}
|
71,187,470 | 71,189,020 | converting boost::multiprecision::int256_t to string | how would I convert a boost::multiprecision::int256_t type variable into a string for example if i have
string string1 = "12345";
boost::multiprecision::int256_t int1 (string1);
boost::multiprecision::int256_t int2 = int1 + 5
string string2;
// how do i making string equivalent to int2
| I think you just use the str() method on the multiprecision number.
[Demo]
#include <iostream> // cout
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
int main()
{
std::string string1 = "12345";
boost::multiprecision::int256_t int1 (string1);
boost::multiprecision::int256_t int2 = int1 + 5;
std::string string2{ int2.str() };
std::cout << string2 << "\n";
}
// Outputs:
//
// 12350
|
71,187,556 | 71,187,591 | C++ malloc(): corrupted top size on loop | I'm trying to create a function printarr that prints a dynamically sized array. However, whenever I try to run the code I get the error above. I tried copying code I found online as well, but get the same error, so I'm wondering if there's something wrong with my installation, or another part of the code is somehow affecting it. The entire thing seems super simple, which makes me even more stumped. Here's the code:
#include <iostream>
using namespace std;
//Generates an array with k inversions of size n
int* generate_k_inversion(int k, int n){
int *arr=new int(n);
//Check if number of inversions is possible
if(k>(n*(n-1)/2)){
cout<<"Impossible number of inversions!";
throw(-1);
}
//Loop to generate points
for(int i=0;i < n;i++){
arr[i]=i;
}
//Loop to invert
return arr;
}
//Copies dynamic arrays of size n
int* copy(int* arr1,int n){
int* arr2=new int(n);
for(int i=0;i<n;i++){
arr2[i]=arr1[i];
}
return(arr2);
}
//Generates output of best and worst cases of bubble and insertion sort in integers of size n
void test1(int n){
//generate best case
int *arrb1=generate_k_inversion(0,n);
int *arrb2=copy(arrb2,n);
delete [] arrb1;
delete [] arrb2;
//generate worst case
int *arrw1=generate_k_inversion((n*(n-1)/2),n);
int *arrw2=copy(arrw2,n);
delete [] arrw1;
delete [] arrw2;
}
//Prints a dynamic array arr of size n
void printarr(int* arr, int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
//Just initialize both tests
int main(){
int size=10;
int* arr1=generate_k_inversion(0,size);
printarr(arr1,size);
delete [] arr1;
}
Thanks for the help
| The line
int *arr=new int(n);
will allocate memory for a single int and initialize that int to n.
Therefore, the loop
for(int i=0;i < n;i++){
arr[i]=i;
}
will access arr out of bounds, causing undefined behavior.
What you probably want is to write
int *arr=new int[n];
instead, which will allocate memory for n values of type int.
|
71,187,933 | 71,298,442 | How to save a vector of a custom type of elements on disk, read it, and parse it into a vector again using C++ | The vector type is TrackInfo:
class TrackInfo
{
public:
TrackInfo(URL& _url, String& _title, double& _length, String _fileFormat);
URL url;
String title;
double length;
String fileFormat;
};
====================================================================================
std::vector<TrackInfo> tracks;
TrackInfo track(fileURL, fileName, length, fileFormat);
tracks.push_back(track);
tracks.push_back(track);
So, how can I save this vector on the computer and then reread it when I need and convert the file into the same vector again?
| I used nlohmann JSON. You can find it here -> https://json.nlohmann.me/
My code:
std::vector<TrackInfo> StoreData::jsonToTrackInfo(json jsonFile)
{
std::vector<TrackInfo> tracks;
for (json jsonf : jsonFile["Playlist"])
{
// Try to parse the data. If there is an error, return the empty vector.
// If one of the Playlist tracks has a problem, it won't be parsed and will parse the rest of the playlist.
try
{
String urlString = jsonf["url"];
String title = jsonf["title"];
double length = jsonf["length"];
String format = jsonf["format"];
URL url { urlString };
TrackInfo track(url, title, length, format);
tracks.push_back(track);
}
catch (const std::exception&)
{
//..
}
}
return tracks;
}
json StoreData::trackInfoToJson(std::vector<TrackInfo> tracks)
{
json j;
// Convert each track into JSON data.
for (TrackInfo track : tracks)
{
j.push_back(
{
{"url" , track.url.toString(false).toStdString()},
{"title" , track.title.toStdString() },
{"length", track.length},
{"format", track.fileFormat.toStdString()}
}
);
}
json jsonFile;
jsonFile["Playlist"] = j;
return jsonFile; // return the Json File
}
and the output of the JSON file should look like this:
{
"Playlist": [
{
"format": ".mp3",
"length": 106.0,
"title": "c_major_theme.mp3",
"url": "file:///C%3A/Users/me/Desktop/tracks/c_major_theme.mp3"
},
{
"format": ".mp3",
"length": 84.0,
"title": "fast_melody_regular_drums.mp3",
"url": "file:///C%3A/Users/me/Desktop/tracks/fast_melody_regular_drums.mp3"
}
]
}
You can find helpful examples here on their website: https://json.nlohmann.me/api/basic_json/#non-member-functions
I hope you find this a helpful answer :D
|
71,188,203 | 71,188,338 | Which constructor (or implicit conversion) is called when passing a pointer to the constructor? | class Test {
public:
Test() {
std::cout << "constructing" << std::endl;
}
Test(Test &t) {
std::cout << "calling copy constructor" << std::endl;
}
Test(Test &&t) {
std::cout << "calling move constructor" << std::endl;
}
Test& operator=(const Test& a){
std::cout << "calling = constructor" << std::endl;
return *this;
}
};
Test* t1 = new Test();
Test* t2 (t1); // what's being called here
When passing a pointer to a constructor like t2, what constructor is called? (Or implicit conversion and then constructor?) This code just prints "constructing" as a result of t1 being constructed.
| Test* t2 (t1);
is direct-initialization. Direct-initialization considers constructors for class types, but Test* is a pointer type, not a class type. Non-class types do not have constructors.
For a pointer type, direct-initialization with a single expression in the parenthesized initializer simply copies the value of the expression into the new pointer object (potentially after implicit conversions, which are not necessary here).
So t2 will simply have the same value as t1, pointing to the object created with new Test();.
|
71,188,218 | 71,188,779 | I cant merge two files in a third one | My problem is the following when I show the third file, It shows a lot of 0 and not the ints of file 1 and file 2. My file ends up with 4,00 KB (4.096 bytes) for some reason I don't know.
Btw, the third file should have first: the first int of file1 and then the first of file2 and so on
Edit: I was testing the problem, and I realize that the size of the third file is correct before I show it. It's 24 and that's the sum of file1 and file 2. But when I read it, then it goes crazy
#include <iostream>
using namespace std;
int main()
{
int buffer1, buffer2, buffer3;
//What is written in file 1 and file 2
int file1_content[] = {1,3,5};
int file2_content[] = {2,4,6};
FILE* f3, *f1, *f2;
f1 = fopen("archivo1", "rb");
f2 = fopen("archivo2", "rb");
f3 = fopen("archivo3", "wb+");
if(!f1)
{
cout<<"Error el archivo 1 no se pudo abrir"<<endl;
return 1;
}
if(!f2)
{
cout<<"Error el archivo 2 no se pudo abrir"<<endl;
return 1;
}
if(!f3)
{
cout<<"Error el archivo 3 no se pudo abrir"<<endl;
return 1;
}
//write file 1 and file two in file 3
while(fread(&buffer1, sizeof(int), 1, f1) && fread(&buffer2, sizeof(int), 1, f2) )
{
fwrite(&buffer1, sizeof(int), 1, f3);
fwrite(&buffer2, sizeof(int), 1, f3);
}
fclose(f1);
fclose(f2);
//show file 3
while(fread(&buffer3, sizeof(int), 1, f3))
{
cout<<buffer3<<" ";
}
//EXPECTED OUTPUT
//1 2 3 4 5 6
fclose(f3);
return 0;
}
| Your code has undefined behavior.
According to §7.21.5.3 ¶7 of the ISO C11 standard, when a file is opened in update mode (+), the following restrictions apply:
Output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind).
Input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.
In your program, you are violating rule #1. The easiest solution would be to add a call to rewind between the calls to fwrite and fread, which you should do anyway, because you want to start reading from the start of the file.
|
71,188,236 | 71,188,438 | How to initialize two std::arrays in constructor initializer list when second depends on first | Of the various ways to initialize std::array class members in the constructor initializer list, I found the variadic parameter pack to work best.
However, how can I initialize a second std::array member which depends on the first?
The example here is a struct polygon which takes a variadic parameter pack of Vector2 vertices. From those vertices we also construct the lines. These lines store the vertices again (references or pointers seem unnecessary given the typical 16byte size of a Vector2) in pairs of line.start and line.end and also pre-compute the Length and normal vector of the line for performance.
Note: I don't want to use two std::vectors - that's what the working code has already.
Is there a way to move the logic from the constructor body to the constructor initializer list for this case?
template <unsigned N, typename Number = double>
struct polygon {
std::array<Vector2<Number>, N> vertices;
std::array<Line<Number>, N> lines; // this is calling Line's default constructor: TOO EARLY
template <typename... Pack>
polygon(Pack... vs)
: vertices{vs...} /* , lines{ .... ??? } this is where we need to construct / initialize lines */ {
static_assert(sizeof...(vs) == N, "incorrect number of vertices passed");
for (auto i = 0UL; i != vertices.size(); ++i) {
// this is calling Line's copy assignment operator: TOO LATE
lines[i] = Line(vertices[i], vertices[(i + 1) % vertices.size()]);
}
}
// ...
}
using Vec2 = Vector2<double>;
using triangle = polygon<3>;
using quadrilateral = polygon<4>;
using pentagon = polygon<5>;
int main() {
auto tri = triangle(Vec2{1, 2}, Vec2{3, 4}, Vec2{4, 5});
std::cout << tri << "\n";
// this would be even nicer, but doesn't work: "substitution failure: deduced incomplete pack"
// auto tri = triangle({1, 2}, {3, 4}, {4, 5});
}
| You can put patterns in front of a ..., not just the pack. However, this requires a suitable pack. In this case, a useful pack would be the indices, so you can make a helper for that:
template<std::size_t... Is>
auto make_lines(std::index_sequence<Is...>) {
return std::array<Line<Number>, N>{
Line(vertices[Is], vertices[(Is + 1) % vertices.size()])...
};
}
std::index_sequence is simply a standard holder type for a bunch of std::size_ts, no behaviour of its own.
Then you create the pack when calling it:
polygon(Pack... vs)
: vertices{vs...},
lines(make_lines(std::index_sequence_for<Pack...>{})) { ... }
std::index_sequence_for takes the elements of Pack and creates a sequence 0, 1, 2, ..., N-1, one per element received. That is, it's a sequence from 0 to sizeof...(Pack) - 1, perfect for indices.
|
71,188,379 | 71,188,493 | Certain element sum from array | new to C++ and in need of help with an array. Looking at the code below, you can see I have an array of 20 undefined elements. My queastion is how do I sum up elements from a[5] to a[14]. Only these elements. (Including them ofc)
#include <iostream>
using namespace std;
int main()
{
int a[20];
int summa;
for (int i = 0; i < 20; i++) {
a[i] = rand()%6 + 5;
cout << a[i] << "\n";
}
}
| Use your knowledge of a for loop to add those values to your summa variable (which you did not initialize):
#include <iostream>
using namespace std;
int main()
{
int a[20];
// set this to 0 or your answer will be erroneous
int summa = 0;
for (int i = 0; i < 20; i++) {
a[i] = rand()%6 + 5;
cout << a[i] << " ";
}
cout << endl;
// Now sum the values you want
for (int i = 5; i < 15; i++) {
summa += a[i];
}
cout << "Sum from 5 to 14: " << summa << endl;
}
|
71,189,175 | 71,189,234 | Is there a way to define operators in C++? (or another language) | I am aware about operator overloading, but this is not what I am talking about.
I do quite a bit of scientific computation in C++. So for example I have to compute gradients, dot products, laplacians, hessians...
All of these usually have well defined and standrad math symbols. The gradient uses nabla, the hessian nabla^2 the laplacian \delta ...
I normally have to write vec Gradient(fun_ptr) or Hessian(fun_ptr).
The issues is that this makes the code deviate from the paper I am implementing and it makes it just a little harder to catch when you copied something wrong.
Is there any way to define the \nabla character as an operator for example?
|
Is there a way to define operators in C++?
No. You can only overload (some of) the existing operators for custom types in C++.
You can define functions that implement the operations that you want, and if you encode your source code in a character set that has those symbols (i.e. you use Unicode), and your compiler supports it (which isn't guaranteed since the symbols aren't part of the basic character set), then you can use the symbols as names of those functions. But you cannot call the functions with infix notation in C++.
(or another language)
You can define infix functions in Haskell.
|
71,189,472 | 71,189,838 | how to make bind a map on pybind11 | i am working on a backtester for crypto in cpp, but the backend is on python and flask, i try to use pybind11 in order to make the cpp work on the backend, here is my bind code
namespace py = pybind11;
PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
PYBIND11MODULE(backtester, m)
{
py::class<BT::Backtester>(m, "Backtester");
m.def(py::init<py::bind_map<std::map<std::string, double>>());
}
when i compile the bind i have this error
what can it be? how do i solve the error? thanks in advance
| py::bind_map tells pybind11 to bind a type, it doesn't affect the arguments that py::init gets. This is probably what you wanted to do:
namespace py = pybind11;
PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
PYBIND11_MODULE(backtester, m)
{
py::bind_map<std::map<std::string, double>>(m, "StringDoubleMap");
py::class<BT::Backtester>(m, "Backtester");
m.def(py::init<std::map<std::string, double>>());
}
Like I said in a comment, you should probably just include pybind11/stl.h and let pybind11 handle the dict/map conversion.
|
71,190,412 | 71,190,642 | difference between array of class and array of structure? | I was wondering what the difference between the two.
Source: https://www.geeksforgeeks.org/array-of-structures-vs-array-within-a-structure-in-c-and-cpp/
Sample Array of Structure
#include <stdio.h>
struct class {
int roll_no;
char grade;
float marks;
};
void display(struct class class_record[3])
{
int i, len = 3;
for (i = 0; i < len; i++) {
printf("Roll number : %d\n",
class_record[i].roll_no);
printf("Grade : %c\n",
class_record[i].grade);
printf("Average marks : %.2f\n",
class_record[i].marks);
printf("\n");
}
}
int main()
{
struct class class_record[3]
= { { 1, 'A', 89.5f },
{ 2, 'C', 67.5f },
{ 3, 'B', 70.5f } };
display(class_record);
return 0;
}
| There is no difference between a class type and a structure type in C++. They are the same thing.
The code you are showing is C and not valid C++. In C++ class is a keyword and can not be used to name a type.
You create an array of a class type in C++ exactly in the same way as you create an array of any other type:
class C { }; // or identically struct instead of class
C c[123];
Here c is an array of 123 C objects.
|
71,190,459 | 71,190,472 | Why does returning an initializer list in a function returning a priority_queue call the vector constructor? | Consider the following code:
std::priority_queue<int> foo() {
return {14, 12};
}
I would expect foo() to return a priority_queue containing 2 elements: 14 and 12. However, it returns a priority_queue containing 14 copies of 12. I stepped in with gdb and it appears that the vector constructor is being called. Could someone please explain why this is the case? Thanks.
Edit:
Also what would be the most idiomatic way of creating a priority_queue with 2 elements (or any number of elements) other than creating an empty one and inserting elements one by one (or is that the best option)?
| Creating a priority_queue with two integers like that:
std::priority_queue<int> pq(a, b);
Was till recently treated by most compilers as legal, sending the parameters to the underlying container, thus creating a queue holding a times b. Although the constructor of priority_queue that is used for that is actually expecting two iterators:
std::priority_queue(InputIterator begin, InputIterator end);
Which is constructor #7 or #8 depending on the C++ version, as listed in https://en.cppreference.com/w/cpp/container/priority_queue/priority_queue
The arguments provided do not meet the InputIterator requirements.
And as it seems, most compilers fixed this issue recently and produce compilation error, see:
https://godbolt.org/z/Tqxdzc75d
It is interesting to note that the spec [priority.queue] uses the term InputIterator, but without clearly requiring the arguments to obey to InputIterator requirements. Well as cppreference does require that for constructors 7 to 9:
Iterator-pair constructors. These overloads participate in overload resolution only if InputIt satisfies LegacyInputIterator.
It is quite clear that these constructors are meant for iterators, for example for use case like that:
std::vector<int> v(14, 12);
std::priority_queue<int> p(v.begin(), v.end()); // 14 times 12, now legit
Or, if you want two values - 14 and 12:
std::vector<int> v{14, 12};
std::priority_queue<int> p(v.begin(), v.end()); // 14, 12 - also legit
Bottom line: the original code shall fail compilation.
EDIT
It seems that the recent change is based on LWG defect #3522: Missing requirement on InputIterator template parameter for priority_queue constructors - this made the OP's code illegal and added the requirement for the InputIterator parameters to be actually iterators, already reflected in cppreference, as mentioned above.
|
71,190,760 | 71,190,935 | How can I make the faces of my cube smoothly transition between all colors of the rainbow? | I have a program in Visual Studio that is correctly rendering a 3D cube that is slowly spinning. I have a working FillTriangle() function that fills in the faces of the cube with any color whose hex code I enter as a parameter (for example, 0x00ae00ff for purple). I have set the color of each face to start at red (0xFF000000), and then I have a while loop in main() that updates the scene and draws new pixels every frame. I also have a Timer class that handles all sorts of time-related things, including the Update() method that updates things every frame. I want to make it so that the colors of the faces smoothly transitions from one color to the next, through every color of the rainbow, and I want it to loop and do it as long as the program is running. Right now, it is smoothly transitioning between a few colors before suddenly jumping to another color. For example, it might smoothly transition from yellow to orange to red, but then suddenly jump to green. Here is the code that is doing that right now:
...
main()
{
...
float d = 0.0f; //float for the timer to increment
//screenPixels is the array of all pixels on the screen, numOfPixels is the number of pixels being displayed
while(Update(screenPixels, numOfPixels))
{
...
timer.Signal(); //change in time between the last 2 signals
d += timer.Delta(); //timer.Delta() is the average current time
if(d > (1/30)) // 1 divided by number of frames
{
//Reset timer
d = 0.0f;
//Add to current pixel color being displayed
pixelColor += 0x010101FF;
}
...
}
...
}
Is there a better way to approach this? Adding to the current pixel color was the first thing that came to my mind, and it's kind of working, but it keeps skipping colors for some reason.
| That constant is going to overflow with each addition. Not just as a whole number, but across each component of the color spectrum: R, G, and B.
You need to break your pixelColor into separate Red, Green, and Blue colors and do math on each byte independently. And leave Alpha fixed at 255 (fully opaque). And check for overflow/underflow along the way. When you reach an overflow or underflow moment, just change direction from incrementing to decrementing.
Also, I wouldn't increment each component by the same value (1) on each step. With the same increment on R,G, and B, you'd just be adding "more white" to the color. If you want a more natural rainbow loop, we can do something like the following:
Change this:
pixelColor += 0x010101FF;
To this:
// I'm assuming pixelColor is RGBA
int r = (pixelColor >> 24) & 0x0ff;
int g = (pixelColor >> 16) & 0x0ff;
int b = (pixelColor >> 8) & 0x0ff;
r = Increment(r, &redInc);
r = Increment(g, &greenInc);
g = Increment(g, &blueInc);
pixelColor = (r << 24) | (g << 16) | (b << 8) | 0x0ff;
Where redInc, greenInc, and blueInc are defined and initialized outside your main while loop as follows:
int redInc = -1;
int greenInc = 2;
int blueInc = 4;
And the increment function is something like this:
void Increment(int color, int* increment) {
color += *increment;
if (color < 0) {
color = 0;
*increment = (rand() % 4 + 1);
} else if (color > 255) {
color = 255;
*increment = -(rand() % 4 + 1);
}
}
That should cycle through the colors in a more natural fashion (from darker to brighter to darker again) with a bit of randomness so it's never the same pattern twice. You can play with the randomness by adjusting the initial colorInc constants at initialization time as well as how the *increment value gets updated in the Increment function.
If you see any weird color flickering, it's quite possible that you have the alpha byte in the wrong position. It might be the high byte, not the low byte. Similarly, some systems order the colors in the integer as RGBA. Others do ARGB. And quite possible RGB is flipped with BGR.
|
71,190,853 | 71,191,233 | How to put int arrays into int 2d matrix in C++? | I wrote this(memory error) when I try to put int arrays into int matrix:
#include <iostream>
using std::cout; using std::endl;
int* intToIntArray(int input, int length) {
int output[20];
for (int i = 0; i < length; i++) {
output[i] = input % 10;
input /= 10;
cout << output[i];
}
cout << endl;
cout << "=====" << endl;
return output;
}
int main() {
const int arraySize = 5;
int a[arraySize] = { 111110, 1111000, 11100000, 110000000, 1000000000 };
int NumSize[arraySize] = { 6,7,8,9,10 };
int* arr1D;
int** arr2D = new int*;
for (int counter = 0; counter < arraySize; counter++) {
cout << a[counter] << endl;
arr1D = intToIntArray(a[counter], NumSize[counter]);
arr2D[counter] = arr1D;
}
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < NumSize[i]; j++) {
cout << arr2D[i][j];
}
cout << endl;
}
}
I know how to put the data from int arrays to a int matrix, but very very inefficient:
#include <iostream>
using std::cout; using std::endl;
int* intToIntArray(int input, int length) {
int output[20];
for (int i = length-1; i >= 0; i--) {
output[i] = input % 10;
input /= 10;
cout << output[i];
}
cout << endl;
cout << "=====" << endl;
return output;
}
int main() {
const int arraySize = 5;
int a[arraySize] = { 111110, 1111000, 11100000, 110000000, 1000000000 };
int NumSize[arraySize] = { 6,7,8,9,10 };
int arr2D[20][20];
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < NumSize[i]; j++) {
arr2D[i][j] = intToIntArray(a[i], NumSize[i])[j];
}
}
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < NumSize[i]; j++) {
cout << arr2D[i][j];
}
cout << endl;
}
}
How do I do it efficiently?
I don't want to use any vectors because I want to code it to my GPU later on.
Is there an efficient way to insert the int arrays directly into int matrix?
EDIT: (I kind of did what I wanted to do, I just made it static...)
#include <iostream>
using std::cout; using std::endl;
int* intToIntArray(int input, int length) {
static int output[20];
for (int i = 0; i < length; i++) {
output[i] = input % 10;
input /= 10;
}
return output;
}
int main() {
const int arraySize = 5;
int a[arraySize] = { 111110, 1111000, 11100000, 110000000, 1000000000 };
int NumSize[arraySize] = { 6,7,8,9,10 };
int arr2D[20][20];
for (int counter = 0; counter < arraySize; counter++) {
int *arr1D = intToIntArray(a[counter], NumSize[counter]);
for (int i = 0; i < NumSize[counter]; i++) {
arr2D[counter][i] = arr1D[NumSize[counter]-1-i];
}
}
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < NumSize[i]; j++) {
cout << arr2D[i][j];
}
cout << endl;
}
}
| #include <iostream>
using std::cout; using std::cin;
void intToIntArray(int input, int length, int* &output) {
output = new int[length];
for(int i = length - 1; i >= 0; --i) {
output[i] = input % 10;
input /= 10;
}
}
int main() {
const int arraySize = 5;
int a[] = { 111110, 1111000, 11100000, 110000000, 1000000000 };
int NumSize[] = { 6,7,8,9,10 };
int** arr2D = new int*[arraySize];
for(int i = 0; i < arraySize; ++i) {
intToIntArray(a[i], NumSize[i], arr2D[i]);
}
}
|
71,190,864 | 71,190,919 | Strange Behavior with pointers with arrays in c++ | Hello people of Stacked Overflow! Recently I've been learning about pointers and arrays in my college Computer Science class. In order to try to test the depth of my understanding of the two, I tried to come up with some confusing instances in order to see if I could correctly predict the outcome of the result, as well as the reason for why the result is what it is... Well I seem to have confused myself too much, because I don't understand these few instances that I have come up with.
int vals[] = {1,2,3,4,5,6};
int* valptr = vals;
cout<<*valptr<<endl;
cout<<(**&vals)+1<<endl;
//cout<<*(++valptr)<<endl;
// cout<<*(++vals)<<end1;
cout<<*&valptr[0]<<endl;
cout<<**(&valptr)<<endl;
cout<<valptr[0]<<endl;
Part of the main part of my confusion was solved, so I commented out a line on the code, I wanted to know why lines such as cout<<**(&valptr)<<endl; actually run, I'm just confused on why that works. why does it only work when I have the & on it?
|
I'm very confusing seeing as in nowhere in that short code am I
assigning anything further.
Not quite, you are, indeed, assigning a new value "further". You are doing it right here:
cout<<*(++valptr)<<endl;
In C++, the ++ operator increments its operand. The expression
++valptr
by itself is logically equivalent to valptr=valptr+1, but it occurs as part of the expression. valptr gets increment to a new value as part of the expression that it occurs in. That's what ++ does. You can also make a pretty good guess what the -- operator does, too. And ++ and -- works differently when it occurs before or after its operand, but that's slightly off-topic and is something you can investigate on your own, with your C++ textbook's help.
And this is exactly where you are "assigning anything further". So, *valptr before, and after this line, produces a different result.
|
71,190,880 | 71,190,941 | IDE recommends 'pass by value and use std move' when parameter class has no move constructor | struct Person
{
int mId;
std::string mName;
Person(int id, std::string name) : mId(id), mName(std::move(name))
{
}
};
struct Node
{
Person mData;
Node* mLeft;
Node* mRight;
Node(Person data) : mData(std::move(data)), mLeft(nullptr), mRight(nullptr)
{}
};
When writing a constructor for my Person class I intially defined my 'name' parameter to be a const reference but was recommended to change it to a simple value and use std move.
I understand this is because a rvalue string could be used to initialize 'Person', in which case the string would be moved into the variable 'name' as opposed to being copied. It would then be further moved into the member variable 'mName'- via std::move. I am also under the impression that this only works for std::string because it defines a move constructor.
What I don't understand is why I'm recommended to use std::move again in the 'Node' class constructor as I have not defined a move constructor for Person. Furthermore, I have noticed that removing the string member variable, mName, from the Person class stops this IDE reccomendation.
My guess is that this is because of the default move constructor of the Person class.
(In case it is helpful, my IDE is VS2022 and the reccomendation is from the extension Resharper')
| Your Person class is following the "rule-of-zero", meaning it doesn't declare any copy/move operations or destructor explicitly.
That is usually the correct thing to do, because then the compiler will declare all of them implicitly and define them with the semantics you would usually expect from the these operations, if that is possible.
In your case, all members of Person can be move-constructed, so the implicit move constructor of Person will be defined to move-construct the members one-by-one.
This is what is used when you add std::move in mData(std::move(data)). Without it data is a lvalue and instead the implicit copy constructor which copy-constructs each member would be used.
Copy-constructing a std::string is often more costly than move-constructing it, which is probably why the tool warns about that case, but not if std::string isn't there. Move-constructing and copy-constructing an int member is exactly the same operation.
If you don't want to check each time what members a class has, you can simply always use std::move in these situations. For example changing mId(id) to mId(std::move(id)) is pointless, because id is a scalar type, but it also doesn't make anything worse.
|
71,191,214 | 71,191,288 | Clarification on the relation of arrays and pointers | I wanted some further understanding, and possibly clarification, on a few things that confuse me about arrays and pointers in c++. One of the main things that confuse me is how when you refer to the name of an array, it could be referring to the array, or as a pointer to the first element, as well as a few other things. in order to better display where my trouble understanding is coming from, I'll display a few lines of code, as well as the conclusion that I've made from each one.
let's say that I have
int vals[] = {1,50,3,28,32,500};
int* valptr = vals;
Because vals is a pointer to the first value of the array, then that means that valptr, should equal vals as a whole, since I'm just setting a pointer equal to a pointer, like 1=1.
cout<<vals<<endl;
cout<<&vals<<endl;
cout<<*(&vals)<<endl;
cout<<valptr<<endl;
the code above all prints out the same value, leading me to conclude two things, one that valptr and vals are equal, and can be treated in the same way, as well as the fact that, for some reason, adding & and * to vals doesn't seem to refer to anything different, meaning that using them in this way, is useless, since they all refer to the same value.
cout<<valptr[1]<<endl;//outputs 50
cout<<vals[1]<<endl;//outputs 50
cout<<*vals<<endl;//outputs 1
cout<<*valptr<<endl;//outputs 1
the code above furthers the mindset to me that valptr and vals are the same, seeing as whenever I do something to vals, and do the same thing to valptr, they both yield the same result
cout<<*(&valptr +1)-valptr<<endl;
cout<<endl;
cout<< *(&vals + 1) -vals<<endl;
Now that we have established what I know, or the misconceptions that I may have, now we move on to the two main problems that I have, which we'll go over now.
The first confusion I have is with cout<< *(&vals + 1) -vals<<endl; I know that this outputs the size of the array, and the general concept on how it works, but I'm confused on several parts.
As shown earlier, if
cout<<vals<<endl;
cout<<&vals<<endl;
cout<<*(&vals)<<endl;
all print out the same value, the why do I need the * and & in cout<< *(&vals + 1) -vals<<endl; I know that if I do vals+1 it just refers to the address of the next element on the array, meaning that *(vals+1)returns 50.
This brings me to my first question: Why does the & in *(&vals+1) refer to the next address out the array? why is it not the same output as (vals+1)in the way that *(&vals)and (vals)have the same output?
Now to my second question. We know thatcout<< *(&vals + 1) -vals<<endl; is a valid statement, successfully printing the size of the array. However, as I stated earlier, in every other instance, valptr could be substituted for vals interchangeably. However, in the instance of writingcout<<*(&valptr +1)-valptr<<endl; I get 0 returned, instead of the expected value of 6. How can something that was proven to be interchangeable before, no longer be interchangeable in this instance?
I appreciate any help that anyone reading this can give me
| Arrays and pointers are two different types in C++ that have enough similarities between them to create confusion if they are not understood properly. The fact that pointers are one of the most difficult concepts for beginners to grasp doesn't help either.
So I fell a quick crash course is needed.
Crash course
Arrays, easy
int a[3] = {2, 3, 4};
This creates an array named a that contains 3 elements.
Arrays have defined the array subscript operator:
a[i]
evaluates to the i'th element of the array.
Pointers, easy
int val = 24;
int* p = &val;
p is a pointer pointing to the address of the object val.
Pointers have the indirection (dereference) operator defined:
*p
evaluates to the value of the object pointed by p.
Pointers, acting like arrays
Pointers give you the address of an object in memory. It can be a "standalone object" like in the example above, or it can be an object that is part of an array. Neither the pointer type nor the pointer value can tell you which one it is. Just the programmer. That's why
Pointers also have the array subscript operator defined:
p[i]
evaluates to the ith element to the "right" of the object pointed by p. This assumes that the object pointer by p is part of an array (except in p[0] where it doesn't need to be part of an array).
Note that p[0] is equivalent to (the exact same as) *p.
Arrays, acting like pointers
In most contexts array names decay to a pointer to the first element in the array. That is why many beginners think that arrays and pointers are the same thing. In fact they are not. They are different types.
Back to your questions
Because vals is a pointer to the first value of the array
No, it's not.
... then that means that valptr, should equal vals as a whole, since I'm just setting a pointer equal to a pointer, like 1=1.
Because the premise is false the rest of the sentence is also false.
valptr and vals are equal
No they are not.
can be treated in the same way
Most of the times yes, because of the array to pointer decay. However that is not always the case. E.g. as an expression for sizeof and operand of & (address of) operator.
Why does the & in *(&vals+1) refer to the next address out the array?
&vals this is one of the few situation when vals doesn't decay to a pointer. &vals is the address of the array and is of type int (*)[6] (pointer to array of 6 ints). That's why &vals + 1 is the address of an hypothetical another array just to the right of the array vals.
How can something that was proven to be interchangeable before, no longer be interchangeable in this instance?
Simply that's the language. In most cases the name of the array decays to a pointer to the first element of the array. Except in a few situations that I've mentioned.
More crash course
A pointer to the array is not the same thing as a pointer to the first element of the array. Taking the address of the array is one of the few instances where the array name doesn't decay to a pointer to its first element.
So &a is a pointer to the array, not a pointer to the first element of the array. Both the array and the first element of the array start at the same address so the values of the two (&a and &a[0]) are the same, but their types are different and that matters when you apply the dereference or array subscript operator to them:
Expression
Expression type
Dereference / array subscript expresison
Dereference / array subscript type
a
int[3]
*a / a[i]
int
&a
int (*) [3] (pointer to array)
*&a / &a[i]
int[3]
&a[0]
int *
*&a[0] / (&a[0])[i]
int
|
71,191,244 | 71,191,266 | Why is compiler giving error while using make_unique with array? | Why can't i initialize a unique pointer
#include <iostream>
#include <memory>
class Widget
{
std::unique_ptr<int[]> arr;
public:
Widget(int size)
{
arr = std::make_unique<int[size]>();
}
~Widget()
{
}
};
int main()
{
}
I am not able to understand the meaning of below error messages. What is wrong with my invocation of
arr = std::make_unique<int[size]>();
I am just trying to create a class with unique pointer member which manages an array. How should I change the below program and WHY?
Error(s):
1129699974/source.cpp: In constructor ‘Widget::Widget(int)’:
1129699974/source.cpp:13:43: error: no matching function for call to ‘make_unique<int [size]>()’
arr = std::make_unique<int[size]>();
^
In file included from /usr/include/c++/7/memory:80:0,
from 1129699974/source.cpp:4:
/usr/include/c++/7/bits/unique_ptr.h:824:5: note: candidate: template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...)
make_unique(_Args&&... __args)
^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:824:5: note: template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = int [size]; _Args = {}]’:
1129699974/source.cpp:13:43: required from here
/usr/include/c++/7/bits/unique_ptr.h:824:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:824:5: error: trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
/usr/include/c++/7/bits/unique_ptr.h:830:5: note: candidate: template<class _Tp> typename std::_MakeUniq<_Tp>::__array std::make_unique(std::size_t)
make_unique(size_t __num)
^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:830:5: note: template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp> typename std::_MakeUniq<_Tp>::__array std::make_unique(std::size_t) [with _Tp = int [size]]’:
1129699974/source.cpp:13:43: required from here
/usr/include/c++/7/bits/unique_ptr.h:830:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:830:5: error: trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
/usr/include/c++/7/bits/unique_ptr.h:836:5: note: candidate: template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__invalid_type std::make_unique(_Args&& ...) <deleted>
make_unique(_Args&&...) = delete;
^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:836:5: note: template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__invalid_type std::make_unique(_Args&& ...) [with _Tp = int [size]; _Args = {}]’:
1129699974/source.cpp:13:43: required from here
/usr/include/c++/7/bits/unique_ptr.h:836:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:836:5: error: trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
| You need
arr = std::make_unique<int[]>(size);
make_unique has a specific documented usage:
template< class T > unique_ptr<T> make_unique( std::size_t size );`
... Constructs an array of the given dynamic size. The array elements are value-initialized. This overload participates in overload resolution only if T is an array of unknown bound. The function is equivalent to:
unique_ptr<T>(new std::remove_extent_t<T>[size]())
Conceptually-speaking1, you can think of make_unique as being very similar to std::unique_ptr<T>(new T(...)) where ... represents forwarding of the args passed to make_unique. In this case, the usage is analogous to forwarding the one arg to operator new[] (std::size_t size)
1 The documentation I linked above doesn't say that the arg is forwarded in the array case, and I don't believe the spec does either.
|
71,191,329 | 71,191,941 | Comparing two strings that return the equivalent substring in c++ | I have a function subString that takes in two strings. I loop through my first string to generate substrings of at least size >= 4. I want to find a substring that exists in my second string. For example:
string1: "ABCDE" string2: "XYBCDEFGH"
substrings of string1 include: "ABCD", "ABCDE", "BCDE"
So, I want to compare the substrings generated to string2 and return "BCDE"
I'm confused on how to compare the two strings. I looked through the STL string library (https://www.cplusplus.com/reference/string/string/), but I got stuck trying to find the right method for this problem.
#include <iostream>
#include <string>
using namespace std;
void subString(string s1, string s2){
int n = 4;
int strLength = s1.length();
string firstString;
for (int i = 0; i < strLength; i++){
for(int j = 1; j <= strLength - i; j++){
if (s1.substr(i,j).length() >= n){
firstString = s1.substr(i,j);
cout << firstString << endl;
}
}
}
}
int main()
{
string s1;
string s2;
cin >> s1;
cin >> s2;
subString(s1, s2);
}
| You could
Return a vector of substrings.
Then loop through the vector and search in s2 string using find
method.
See below code sample.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> subString(string s1, string s2){
int n = 4;
int strLength = s1.length();
string firstString;
vector<string> substrings;
for (int i = 0; i < strLength; i++){
for(int j = 1; j <= strLength - i; j++){
if (s1.substr(i,j).length() >= n){
firstString = s1.substr(i,j);
substrings.push_back(firstString);
}
}
}
return substrings;
}
int main()
{
string s1 = "ABCDE";
string s2 = "XYBCDEFGH";
for (auto value : subString(s1, s2))
{
if (s2.find(value) != string::npos)
cout << "found " << value << endl;
}
}
Output of this code
found BCDE
|
71,191,472 | 71,191,766 | Finding next palindrome | I am trying to solve a problem related to palindrome which is:
"For each K, output the smallest palindrome larger than K." (Where K is an integer taken as user input)
I have used the recursive approach but it just throws an error stating SEGMENTATION FAULT....
My approach...
#include <iostream>
using namespace std;
int pal(int x){
int rev=0;
while(x!=0){
int rem=0;
rem=x%10;
rev=rev*10 + rem;
x=x/10;
}
if(rev==x)
return x;
else
pal(x+1);
}
int main() {
int T;
cin>>T;
while(T--){
int N;
cin>>N;
cout<<pal(N+1)<<endl;
}
return 0;
}
Please guide me where am I doing wrong.
| Instead of writing
else {
pal(x+1);
}
write return pal(x+1);
Your current pal function does not return any value if the first x+1 is not a palindrome. Based on what @igorTandentik has written in the comments, this should fix the problem.
EDIT 1:
Your code has a serious flaw. You're making x zero in your while loop and then comparing it with reverse, which will never be true. Now you are calling pal with x+1 which is equivalent to pal(1). You repeat same mistake in recursive call. Hence you enter an infinite loop.
Make a copy of x in your function then use that copy to reverse the x. use x to compare with reverse or forward it to next call.
|
71,191,825 | 71,191,862 | Does member function like operator<< , operator* need ADL to work? | I have a code snippet (Hypothetically):
#include <iostream>
struct Pirate {
void song_name() {
std::cout << "Bink's Sake\n";
}
Pirate& operator*(Pirate const& other) {
// do something
return *this;
}
};
int main() {
Pirate p1{} p2{};
p1.song_name(); // does this use qualified or unqualifed name lookup?
p1 * p2;
std::cout << 5;
std::cout << 'a';
}
Does p1 * p2 use qualified name lookup or unqualified name lookup or ADL?
std::cout << 5 transforms into std::cout.operator<<(5);
std::cout << 'a' transforms into std::operator<<(std::cout, 'a');
Does member functions require ADL to work?
Does the above two statments use qualified or unqualifed name lookup or ADL?
Thanks
| A name is a qualified name if the scope to which it belongs is explicitly denoted using a scope-resolution operator (::) or a member access operator (. or ->).
Case 1
Thus, when you wrote:
p1.song_name(); //here p1.song_name is a qualified name
In the above statement, p1.song_name is a qualified name and so here qualified lookup takes place.
Case 2
Next, when your wrote:
p1 * p2;
The above statement is equivalent to:
p1.operator*(p2);
Since your class Pirate have an overloaded member function operator*, the above statement will use that member function. The above statement uses qualified lookup as well because we have used the member access operator ..
Case 3
Here we have the statement:
std::cout << 5;
The above statement is equivalent to:
std::cout.operator<<(5);
which uses qualified lookup since it has member access operator .
Case 4
Here we look at the statement:
operator<<(std::cout, 'a');
Here the char overload from operator<< for ofstream is used. This uses ADL because in this case the first parameter has a class type. So the compiler will also look in the namespace in which cout is defined. Thus, for this call, the compiler also looks in the std namespace and finds the char overload.
|
71,192,352 | 71,192,631 | How to implement operator[][] for 1D arrays | Is there a way to implement an operator like [][] for a 1D array?
I want to change the implementation of a 2D vector to a 1D vector in my code (cause this increases the execution speed by about %50 in my program). 2D vector supports [y][x]. How can I have such functionality for a 1D vector?
I can do it like this:
const size_t Y_Axis { 20 };
const size_t X_Axis { 30 };
std::vector<char> vec( Y_Axis * X_Axis );
size_t row { 5 };
size_t col { 28 };
vec[ row * X_Axis + col ] = 't'; // assign a value to a specific row-column
However, typing this formula multiple times throughout a source file seems like violating DRY (don't repeat yourself). How can I do this in an efficient and idiomatic way? I want to hide the complexity and make things a bit abstracted just like operator[][] of 2D vector does.
| C++ does not allow virtual containers. So the operator [] is expected to return a true object of the expected size, if you want all the goodies like true iterators to work smoothly.
Here is a post of mine about the iterator question for multi-dimensional containers and a more general question on Code Review
If you only want to build an operator[](int) that returns something that can accept a second [], it can easily be done for a 2D vector, by returning a plain pointer inside the internal data array of a vector:
template <typename T>
class vec2d {
std::vector<T> data;
size_t _cols;
public:
vec2d(int rows, int cols, T* src = nullptr)
: data(rows * cols), _cols(cols) {
if (src != nullptr) {
for (T& val : data) {
val = *src++;
}
}
}
T* operator [] (size_t row) {
return data.data() + row * _cols;
}
const T* operator [] (size_t row) const {
return data.data() + row * _cols;
}
size_t rows() const {
return data.size() / _cols;
}
size_t cols() const {
return _cols;
}
};
And here is an example usage:
int main() {
vec2d<char> v(3, 4, "ABCDEFGHIJKL");
for (size_t i = 0; i < v.rows(); i++) {
for (size_t j = 0; j < v.cols(); j++) {
std::cout << v[i][j] << ' ';
}
std::cout << "\n";
}
}
|
71,192,384 | 71,192,734 | Replicating environment from renderdoc to debug | I have a strange issue, a vulkan application I am writing seemingly runs fine when run from the terminal. But if run from renderdoc an assertion inside the official .hpp header triggers.
Since this only happens if the program is launched with renderdoc I am having a hard time trying to debug it.
Is there a way to get the exact environment configuration renderdoc is using to run the program so that I can replicate the bug?
It is quite bizarre it only happens if the new dynamic rendering extension is active too. If it is not requested renderdoc doesn;t seem to trigger the assertion. But I am on the latest version (1.18).
| If anyone runs into something like this in teh future. The problem was that an old instance of renderdoc was installed in my system, this in turn created conflicts when loading the program onto renderdoc as vulkan wasn't properly configured.
Uninstalling the old version fixed it.
|
71,193,900 | 71,194,203 | What is the meaning of Scalar(0,0,0,)? | Hello i want to ask what is this line of code do?
Mat res(img.rows, img.cols, CV_8UC1, Scalar(0,0,0));
i'm guessing it's making matrix of image rows and columns but i still don't understand what's the Scalar(0,0,0) for?
| From the documentation of OpenCV, you are using the fourth constructor:
Mat (int rows, int cols, int type, const Scalar &s);
The third argument is the array type for the elements of the matrix. You are using CV_8UC1: 8-bit single-channel array.
The fourth argument is an optional value to initialize each matrix element with. Scalar is simmilar to a 4x1 vector. However, since you have specified a single channel, only the first value will be copied to the matrix elements. If you had specified more channels, the remaining elements of Scalar would be used.
|
71,193,912 | 71,194,013 | Check if a string contains palindromes separated by a hash symbol using a vector as an implementation of the stack | I have to write a bool mirrored() function that has to return true if the input meets the following criteria.
The string is mirrored if it contains palindrome substrings separated by one (and only one) hash symbol, and if all the palindromes are correct.
So it should return true for the following:
#, ####, abc#cba, ##a#aabc#cba
and false for the following:
abc, abc#cv, abc#cbaa#aa, ab#bac##c
This is my first exercise concerning the use of stack-related functions and I'm having difficulties with the following code:
bool isMirrored(){
vector<char> stack;
char s;
bool hashSymbol = false;
while(cin >> s){
if(s=='#'){
hashSymbol = true;
while(hashSymbol && !stack.empty()){
if(s==stack.back()){
stack.pop_back();
}
if(stack.empty()){
hashSymbol=false;
}
else{
return false;
}
}
}
stack.push_back(s);
}
return true;
}
My plan is when a # is not present, it loads the stack with characters and when a # is found, my algorithm goes into "check mode" (hence switching the hashSymbol variable to true) and checks if the topmost element of the stack is equal to the next character. If it is, then it checks for the next one and drops the topmost element of the stack. If the characters don't match, then the function returns false. When the stack is empty, then the algorithm should go into "input mode" again (hashSymbol switched to false) and the cycle begins anew. If the function didn't return false and the input is over, then it must return true.
My problem with this is that I can't figure out how to move to the next character in the input. When it finds a #, it enters the inner while statement while s is still the # character.
I thought of (at first glance at least) another possible much simpler solution, but I still can't figure out how to move to the next character in the input when a # is found.
vector<char> stack;
char s;
while(cin >> s){
if(s!='#'){
stack.push_back(s);
}
else{
if(!stack.empty()){
[this is where I would check for equal characters]
}
else{
return true;
}
}
}
return stack.empty();
| A few hints for the first version.
The
while(hashSymbol && !stack.empty()){
Is superfluous. Check just one character at a time.
stack.push_back(s);
pushes the '#' on the stack too.
I think you will have an easier time to adapt your second version rather than correcting the first.
Your not far away from a solution..
|
71,194,142 | 71,194,394 | A little trouble with g++ compiling makefile | I've got the following makefile:
test_containers: containers.o
g++ out/containers.o test/test_containers.cpp -o out/test_containers.exe
containers.o: queue.o stack.o container.o
g++ -c out/queue.o out/stack.o out/container.o -o out/containers.o
queue.o: container.o
g++ -c src/Queue.cpp out/container.o -o out/queue.o
stack.o: container.o
g++ -c src/Stack.cpp out/container.o -o out/stack.o
container.o:
g++ -c src/Container.cpp -o out/container.o
The problem is, when I do make containers.o, out/containers.o does not appear.
Compile log:
D:\DevProjects\2nd-semester\cpp\S1_dev>make containers.o
g++ -c src/Container.cpp -o out/container.o
g++ -c src/Queue.cpp out/container.o -o out/queue.o
g++: warning: out/container.o: linker input file unused because linking not done
g++ -c src/Stack.cpp out/container.o -o out/stack.o
g++: warning: out/container.o: linker input file unused because linking not done
g++ -c out/queue.o out/stack.o out/container.o -o out/containers.o
g++: warning: out/queue.o: linker input file unused because linking not done
g++: warning: out/stack.o: linker input file unused because linking not done
g++: warning: out/container.o: linker input file unused because linking not done
Is there something that I do not understand right? How do I get a containers.o file?
(ran on Windows 10 machine btw)
upd: information supply because people say there's very little
My file tree:
│ makefile
│
├───.vscode
│ settings.json
│
├───out
│ container.o
│ queue.o
│ stack.o
│
├───src
│ Container.cpp
│ Container.h
│ Queue.cpp
│ Queue.h
│ Stack.cpp
│ Stack.h
│
└───test
catch.hpp
test_containers.cpp
I don't really know what I can say more other than that .cpp files include matching .h files, and both Queue.h and Stack.h include Container.h and test_containers.cpp file includes catch.
| Your recipes are cluttered with files that don't belong there. Given the very limited amount of information you've provided, the most direct solution is to just slam out the recipes directly.
test_containers: out/test_containers.exe
out/test_containers.exe: out/test_containers.o out/containers.a
g++ $^ -o $@
out/test_containers.o: test/test_containers.cpp
g++ -c $< -o $@
out/containers.a: out/queue.o out/stack.o out/container.o
ar rcs $@ $^
out/queue.o: src/Queue.cpp
g++ -c $< -o $@
out/stack.o: src/Stack.cpp
g++ -c $< -o $@
out/container.o: src/Container.cpp
g++ -c $< -o $@
clean:
rm -f out/*.o
Some notes about some of the stuff you see up there, that make the rules simpler to write:
$@ is a macro denoting the target of the rule
$^ is a macro that expands to all dependencies of the current target, with duplicate names removed.
$< is a macro that expands to the first dependency.
There is a LOT more that can/should be done (dependency generation, implicit rule usage, phony target, etc.), but that's the basics of it.
|
71,194,444 | 71,194,732 | C++ LNK2005 already defined in B_calculating.obj | Errors:
LNK2005 "private: static char const * const boost::json::key_value_pair::empty_" (?empty_@key_value_pair@json@boost@@0QBDB) already defined in B_calculating.obj
LNK2005 "private: static struct boost::json::object::table boost::json::object::empty_" (?empty_@object@json@boost@@0Utable@123@A) already defined in B_calculating.obj
LNK2005 "private: static struct boost::json::array::table boost::json::array::empty_" (?empty_@array@json@boost@@0Utable@123@A) already defined in B_calculating.obj
And so on...
There are about a hundred of these errors and they are all related to boost json
before asking this question, I spent almost the whole day reading and searching for materials on this topic. It seems that I have already tried everything, but the error remains. I have a few files:
main.cpp:
#include <stdlib.h>
#include <iostream>
#include <mysql/jdbc.h>
#include <boost/json/src.hpp>
#include <boost/json.hpp>
#include <typeinfo>
#include <string>
#include <vector>
#include <math.h>
#include <B_calculating.h>
#include <Level.h>
#include <string>
using namespace std;
//here using B_calculating
//Unfortunately, you won't be able to fully reproduce the example, as it requires data from the database and so on.
....
B_calculating.h:
#pragma once
#include <vector>
#include <boost/json/src.hpp>
#include <boost/json.hpp>
#include <mysql/jdbc.h>
#include <Level.h>
class B_calculating
{
public:
std::vector<Level> depth;
sql::ResultSet* sql_result_query;
const int parameter_value;
const float step;
B_calculating(sql::ResultSet* sql_result, int parameter, float input_step);
void start_processing();
private:
void request_processing(boost::json::value const& jv);
void set_level_and_custom_size(Level& l, float zero_level_price);
void calculate_levels_and_custom_size();
};
B_calculating.cpp:
#include <Q_calculating.h>
using namespace std;
// here I define functions from .h file
Level.h have similar structure and it works fine.
| There is a clue in the boost/json/src.hpp header:
This file is meant to be included once, in a translation unit of the program.
You should only include boost/json/src.hpp in one cpp file. You should remove it from B_calculating.h and only include it in main.cpp.
|
71,194,704 | 71,194,786 | I want my clock program to display the output as 00:00 instead it displays it as 0:0 even though I have used stream manipulators | So I made a sloppy clock program as an assignment. It works fine however I want the output to display each cout as "01:02", instead it displays "1:2", even though I think I have written all the right manipulators. This is my whole program.
#include <thread>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
cout << fixed << right;
cout.fill(0);
for (int m = 0; m < 59; m++)
{
for (int s = 0; s < 59; s++)
{
this_thread::sleep_for(
chrono::seconds(1));
system("cls");
cout << setw(2) << m << ":";
cout << setw(2) << s << endl;
}
}
}
| You are using the null character to fill (which is not visible).
cout.fill(0);
What you probably meant was to use the ASCII character 0, like this:
cout.fill('0');
|
71,194,939 | 71,200,713 | Why constinit of half-initialized struct does not work | struct A1 { int x; int y; };
struct A2 { int x = 1; int y = 2; };
struct A3 { int x = 1; int y; };
constinit A1 a1; // x == 0, y == 0.
constinit A2 a2; // x == 1, y == 2.
A3 a3; // x == 1, y == 0.
constinit A3 a4; // Error: illegal initialization of 'constinit' entity with a non-constant expression
int main() {}
What is the problem with a4? I mean a4.x should be initialized by a constant 1 (same as for a2 where it works) and a4.y by a constant 0 because a4 is a global static variable (same as for a1 where it works).
Now, considering that both MSVC and GCC fail to compile this code I assume the standard somehow forbids it. But any way I look at a4 its initial value is exact, constant and known at compile time so why the standard forbids us from declaring it as constinit)?
In addition to this, clang++ also rejects the first constinitialization:
error: variable does not have a constant initializer
constinit A1 a1; // x == 0, y == 0.
| I think this is a case where we might be missing some wording.
To start with, there are three stages of initialization that happen ([basic.start.static]):
Constant initialization
If not that, zero-initialization (for static storage duration variables, like the ones in this question)
If necessary, dynamic initialization
(1) and (2) together are static initialization, (3) is... well, dynamic. And what constinit does is ensure that there is no dynamic iniitialization, from [dcl.constinit]:
If a variable declared with the constinit specifier has dynamic initialization ([basic.start.dynamic]), the program is ill-formed.
And the rule for constant initialization is, from [expr.const]:
A variable or temporary object o is constant-initialized if
either it has an initializer or its default-initialization results in some initialization being performed, and
the full-expression of its initialization is a constant expression when interpreted as a constant-expression, except that if o is an object, that full-expression may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types.
With that said, let's go through the three types. Starting with the easiest:
struct A2 { int x = 1; int y = 2; };
constinit A2 a2; // x == 1, y == 2.
Here, we're initializing all the members, this is clearly constant initialization. Not really much of a question here.
Next:
struct A1 { int x; int y; };
constinit A1 a1; // x == 0, y == 0.
Here, our default constructor does... nothing, there is no initialization. So this is not constant initialization. But zero-initialization happens and then there is no further initialization. There is certainly no dynamic initialization that has to take place here, so there is nothing for constinit to diagnose.
Lastly:
struct A3 { int x = 1; int y; };
constinit A3 a4; // Error: illegal initialization of 'constinit' entity with a non-constant expression
Prior to the adoption of P1331, this initialization of a4 was clearly not constant initialization because constant initialization explicitly required fully initialized variables. But we don't have this requirement anymore, the rule was moved later - to when a4.y would actually be read.
But I think the intent in this case is very much that a4 is not constant initialized, due to it being partially uninitialized. This probably merits a core issue.
Given that it is not constant initialization, then we go into zero initialization. But after that, a4 still isn't fully initialized - because we have to set x to 1. There is no provision for half-constant half-zero initialization. The rule is constant or, if not that, zero. Since this isn't (or, at least, shouldn't be) constant initialization, and zero-initialization is insufficient, a4 must undergo dynamic initialization. And thus, constinit should flag this case. gcc and msvc are correct here (clang erroneously rejects a1).
|
71,195,215 | 71,195,296 | How can a c++ std::vector<NotAPointer> store objects of different size, and how can ++it know where to jump when it doesn't contain pointers | EDIT: TLDR; I was a victim of object slicing, which I didn't know about. Now the original question follows.
I'm trying to understand how std::vector<MyClass> stores objects when an instance of MyDerived is push_backed into it. Also, how do iterators know where the start of the next memory block will be so that the increment ++ operator knows how to get there. Consider the following code sample:
#include <iostream>
#include <vector>
using namespace std;
class BaseShape
{
public:
// BaseShape() { cout << "BaseShape() "; }
virtual void draw() const { cout << "BASE?\n"; }
};
class Circle : public BaseShape
{
public:
Circle() { cout << "Circle()"; }
virtual void draw() const override { cout << "Circle!\n"; }
void *somePointer, *ptr2;
};
class Triangle : public BaseShape
{
public:
Triangle() { cout << "Triangle()"; }
virtual void draw() const override { cout << "Triangle!\n"; }
void *somePtr, *ptr2, *ptr3, *ptr4, *ptr5;
};
int main()
{
cout << "vector<BaseShape *> ";
vector<BaseShape *> pShapes{new BaseShape(), new Circle(), new Triangle(), new Circle()};
cout << endl;
for (vector<BaseShape *>::iterator it = pShapes.begin(); it != pShapes.end(); ++it)
{
cout << *it << " ";
(*it)->draw();
}
// vector<BaseShape *> Circle()Triangle()Circle()
// 01162F08 BASE?
// 01162F18 Circle!
// 011661A0 Triangle!
// 01162F30 Circle!
cout << "\nvector<BaseShape> ";
vector<BaseShape> shapes{BaseShape(), Circle(), Triangle(), Circle()};
cout << endl;
for (vector<BaseShape>::iterator it = shapes.begin(); it != shapes.end(); ++it)
{
cout << &(*it) << " ";
(*it).draw();
}
// vector<BaseShape> Circle()Triangle()Circle()
// 01162FD0 BASE?
// 01162FD4 BASE?
// 01162FD8 BASE?
// 01162FDC BASE?
return 0;
}
In vector::<BaseShape*> pShapes, I understand that pShapes is only storing pointers to the address of the actual shape. Then, it is easy to know how much to increment the memory address with ++it, as all pointers will have the same memory size. Console output shows how *it jumps around in memory for "Triangle".
Now, my doubt comes when vector<BaseShape> shapes is used instead. Maybe my understanding is wrong, but I believe that shapes would store memory for BaseShape objects directly (more on this later). But if that is correct, then when I push_back a Circle or a Triangle object into it, how is it even possible to store all objects contiguously in memory? That doesn't sound possible, as Circle and Triangle have different sizes in memory, and their memory must be contiguous to that of the BaseShape object (e.g. [BaseShape mem][Circle mem]). Even more, how does ++it know exactly how much memory is needed to jump in order to get the next object? In the console output, I can see that ++it only increased the memory address by 4, which leads me to conclude that somehow only the BaseShape part was stored in memory. Is the [Circle mem] just dropped? Because I can see the Circle constructor was called (as seen in // vector<BaseShape> Circle()Triangle()Circle()).
I maybe was expecting the code to not compile or warn me that storing Circle or Triangle in shapes would lead to information loss, but it didn't and the code kinda worked. The 'kinda' is because draw() was early bound to BaseShape rather than properly late binding to Circle or Triangle as a virtual method should. This signals that shapes is storing contiguous BaseShape memory blocks...
I'm not trying to solve a problem here, I'm just curious about how C++ works and where is my misunderstanding of std::vector, pointers, or iterators.
| When storing BaseShapes in a vector by value you'll experience what is called object slicing.
Basically all information that only the derived classes contain is forgotten about, and only the base class' information is actually stored. All objects will behave as would BaseClass objects, with the only exception of potential class invariants being broken due to the slicing.
|
71,195,244 | 71,195,445 | Error: cannot define 'enum class std::align_val_t' in different module | I am a C ++ beginner and am looking to create a module. I have followed several guides and would like to test modules with classes. When I try to run the first module via g++-11 -c -std=c++20 -fmodules-ts func.cxx i get the following error:
In file included from /usr/local/Cellar/gcc/11.2.0_3/include/c++/11/bits/stl_iterator.h:82,
from /usr/local/Cellar/gcc/11.2.0_3/include/c++/11/bits/stl_algobase.h:67,
from /usr/local/Cellar/gcc/11.2.0_3/include/c++/11/bits/char_traits.h:39,
from /usr/local/Cellar/gcc/11.2.0_3/include/c++/11/string:40,
from func.cxx:2:
/usr/local/Cellar/gcc/11.2.0_3/include/c++/11/new:89:27: error: cannot define 'enum class std::align_val_t' in different module
89 | enum class align_val_t: size_t {};
| ^~~~~~
<built-in>: note: declared here
/usr/local/Cellar/gcc/11.2.0_3/include/c++/11/new:89: confused by earlier errors, bailing out
Below are the files, thanks in advance.
main.cpp
#include <iostream>
import airline_ticket;
int main()
{
std::cout << "Hello" << std::endl;
return 0;
}
func.cxx
export module airline_ticket;
#include <string>
export class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
double calculatePriceInDollars(); std::string getPassengerName();
void setPassengerName(std::string name);
int getNumberOfMiles();
void setNumberOfMiles(int miles);
bool hasEliteSuperRewardsStatus();
void setHasEliteSuperRewardsStatus(bool status);
private:
std::string m_passengerName;
int m_numberOfMiles;
bool m_hasEliteSuperRewardsStatus;
};
func_impl.cxx
module airline_ticket;
AirlineTicket::AirlineTicket()
{
// Initialize data members.
m_passengerName = "Unknown Passenger";
m_numberOfMiles = 0;
m_hasEliteSuperRewardsStatus = false;
}
| the include directive in func.cxx needs to be in the global module fragment area. Else you'll get redefinitions.
I.e.
module;
#include <string>
export module .....
...
|
71,195,257 | 71,197,613 | how to include a separate file containing functions for a class | So i am making a library for a hardware to be used with arduino. Inside that class there are some hardware specific code that needs to included. To improve readability i would like to move the hardware specific functions to another file
//.h
class myClass(){
public:
myClass();
void controlGPIO();
};
//.cpp
myClass::myClass(){
controlGPIO();
}
#ifdef HARDWAREA
#include "deviceA_hal.h"
#endif
#ifdef HARDWAREB
#include "deviceB_hal.h"
#endif
//deviceA_hal.h HardwareA functions
#include <deviceA_specific_Library>
void myClass::controlGPIO(){
// some code unique to hardwareA
}
//deviceB_hal.h HardwareB functions
#include <deviceB_specific_Library>
void myClass::controlGPIO(){
// some code unique to hardwareB
}
Is this possible ? Am i doing this correctly?
This would make adding more specific hardware easier and cleaner. Is there a more better way of doing it>?
| Common is to do one .cpp with
#if defined(HARDWAREA)
#include "deviceA_hal.h"
#elif defined(HARDWAREB)
#include "deviceB_hal.h"
#endif
void myClass::controlGPIO(){
#if defined(HARDWAREA)
// some code unique to hardwareA
#elif defined(HARDWAREB)
// some code unique to hardwareB
#endif
}
this is simpler to maintain than two separate files
|
71,195,423 | 71,195,465 | How to use concepts in if statement | I have a concept which checks whether a type is iterable or not
template<typename T>
concept Iterable = requires(T t) {
t.begin();
};
I cannot use it in a template due to problems with overloading, so I'd like to do something similar to the following:
template<typename T>
void universal_function(T x) {
if (x is Iterable)
// something which works with iterables
else if (x is Printable)
// another thing
else
// third thing
}
| Concept instantiations are boolean values, so they can be used in if statements. You will need to use if constexpr to achieve the desired behavior, as it will allow for branches containing code that would be invalid in a different branch:
if constexpr (Iterable<T>) {
// ...
} else if constexpr (Printable<T>) {
// ...
} else {
// ...
}
|
71,196,145 | 71,197,138 | Overload resolution between constructor and inherited constructor in C++ - which compiler is correct? | In the following program struct B inherits B(int) deleted constructor from its base A, and also defines additional constructor B(int&&). Then an object of B is created with B b(1):
struct A {
A() {}
A(int) = delete;
};
struct B : A {
using A::A;
B(int&&) {}
};
int main() {
B b(1);
}
If both constructors B(int) and B(int&&) had been defined directly in B the result would have been the ambiguity of constructor selection. And in this example, GCC prints a
call of overloaded 'B(int)' is ambiguous`
error as well.
But Clang prefers the constructor declared in B over the one inherited from A. Demo: https://gcc.godbolt.org/z/dnErEenE5
Which compiler is right here?
| GCC is correct here: there is a tiebreaker that prefers direct over inherited constructors ([over.match.best.general]/2.7), but it applies only if they have the same parameter types (ignoring those whose default arguments are being used).
|
71,196,409 | 71,196,549 | C++ how to split string with alphabets and numbers | I have a need to split the following string into their corresponding alpahbets and numbers
CH1000003
ABC000123
WXYZ10001
Results I want are
st1: CH
st2: 1000003
st1: ABC
st2: 000123
st1: WXYZ
st2: 10001
Now I do have a working code but the amount of code I have written seems a bit too much. There has to be an easy way. Perhaps somehow use regex in C++? Suggestions?
My code:
std::string idToCheckStr="CH1000003";
//find length of string
int strLength = idToCheckStr.length();
cout << "idToCheckStr: " << idToCheckStr <<endl;
cout << "strLength : " << strLength <<endl;
string::iterator it;
int index = 0;
for ( it = idToCheckStr.begin() ; it < idToCheckStr.end(); it++ ,index++)
{
//check where the numbers start in the string
if (std::isdigit(*it) != 0)
{
cout<< "FOUND NUMBER!" <<endl;
cout<< index << ": " << *it <<endl;
break;
}
cout<< index << ": " << *it <<endl;
}
std::string firstPartStr = idToCheckStr.substr (0,index);
cout << "firstPartStr: " << firstPartStr <<endl;
std::string secondPartStr = idToCheckStr.substr (index,strLength);
cout << "secondPartStr: " << secondPartStr <<endl;
OUTPUT:
idToCheckStr: CH1000003
strLength : 9
0: C
1: H
FOUND NUMBER!
2: 1
firstPartStr: CH
secondPartStr: 1000003
| Thanks to igor.
size_t first_digit = idToCheckStr.find_first_of("0123456789");
cout << "first_digit: " << first_digit <<endl;
std::string str1 = idToCheckStr.substr (0,first_digit);
cout << "str1: " << str1 <<endl;
std::string str2 = idToCheckStr.substr (first_digit,idToCheckStr.length());
cout << "str2: " << str2 <<endl;
OUTPUT:
first_digit: 2
str1: CH
str2: 1000003
|
71,196,614 | 71,197,286 | Vector push_back() fails when compiling with CMake and MinGW Makefiles | I've been searching all over the internet for a solution to this problem, however there is no good information about the origin of this problem. In essence, the program fails to run whenever I execute any vector-related function such as resize() or initializing the vector with a given size.
This is the current project structure of this example:
example_project
│ CMakeLists.txt
|
└───src
│ | main.cpp
│
└───build
│ Example.exe
│ ...
CMakeLists.txt:
cmake_minimum_required(VERSION 3.20.0)
project(Example)
# Retrieve all source files
file(GLOB_RECURSE SOURCE_FILES ${PROJECT_SOURCE_DIR}/src/main.cpp)
add_executable(Example ${SOURCE_FILES})
main.cpp:
#include <iostream>
#include <vector>
int main() {
std::cout << "Test\n";
// Example code
std::vector<int> exampleVector;
exampleVector.push_back(1);
// Same applies to any other vector operation
// Ex: std::vector<int> exampleVector(10);
return 0;
}
This code runs fine when compiling with CMake for Visual Studio via cmake .. from the build directory via the terminal. However, I want to build this project without any IDE, thus I want to directly compile it with CMake while still being able to use another text editor. Thus I assumed "MinGW Makefiles" to be a good candidate.
Building and running the application:
> cmake -G "MinGW Makefiles" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
> make
The above commands execute without any errors. Then running Example.exe yields:
I am rather inexperienced when it comes to CMake so I would appreciate any feedback on a better solution for building the project. But the bottom-line is that I want to use CMake for managing large projects without having to use any IDE or solution-file systems such as MSVC, just the terminal for building and running the application. The vector standard header seems to be the problem. Thank you in advance!
| Edit:
It seems that the problem had to do with static linking of necessary libraries. Thus the solution I found was to include one of the static flags for g++ such as -static, -static-libstdc++, etc. To tell CMake to do this automatically upon compilation I just added this as a flag:
set(CMAKE_EXE_LINKER_FLAGS "-static-libstdc++")
That being said I still have so many questions regarding the need to actually do this and if this is even the preferred solution or use-case of static linking.
|
71,197,161 | 71,220,713 | How to use ROS services and serial comunication with posix and semahrores in C++? | Im new to Concurrency and parallelism programming in C/C++ so I need some help woth my project.
I want to run multiple process using POSIX and Semaphores in C++. So the structure of the program should be the following one.
First I Open Serial port (Serial communication of the Raspberry PI 4). While the Serial is Open Two processes are running
First one, the main one run automatically and do the following:
The thread ask for ODOM Updates(Pressure and IMU from the microcontroller) and Publish them. Also every 0.3 seconds check the modem inbox and if something new it publish.
The other one only on DEMAND from ROS Services detect that there is new message in the modem inbox do HALT( on the first main Process) and execute (publish) on the serial Port. Then the first process resume with normal work
So I trying to do first some pseudo C++ code that looks like these But I need help as Im new to Concurrency and parallelism. Here it is
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex;
void* thread(void* arg) { //function which act like thread
//Main Thread
// Here code for ASK ODOM UPDATE..
// Here code for CHECK MODEM INBOX...
sem_wait(&mutex); //wait state
// ENTER in the second Process
// Here code for the second process which run on DEMAND..
// ROS SERVICES
// Here code for CHECK The MODEM INBOX and HALT the First Process
// Here code for EXECUTE on SERIAL PORT(PUBLISH)
sleep(0.1); //critical section
printf("\nCompleted...\n"); //comming out from Critical section
sem_post(&mutex);
}
main() {
sem_init(&mutex, 0, 1);
pthread_t th1,th2;
pthread_create(&th1,NULL,thread,NULL);
sleep(1);
pthread_create(&th2,NULL,thread,NULL);
//Join threads with the main thread
pthread_join(th1,NULL);
pthread_join(th2,NULL);
sem_destroy(&mutex);
}
So Im not sure this is the correct way of implementation on C++ . Any help in the implementation and maybe help on the actual C++ code?
Thanks
| Fortunately, ROS lets you decide what threading model you want to use (http://wiki.ros.org/roscpp/Overview/Callbacks%20and%20Spinning).
You could use the ros::AsyncSpinner for that:
Your main thread starts the AsyncSpinner that runs in the background, listens to ROS messages, and calls your ROS callback functions in its own threads.
Then, your main thread cares about your serial port connection and forwards/publishes messages. In pseudo-code, it could look as follows:
#include <ros/ros.h>
#include <mutex>
#include <std_msgs/Float32.h>
std::mutex mutex_;
void callback(std_msgs::Float32ConstPtr msg) {
// reentrant preprocessing
{
std::lock_guard<std::mutex> guard( mutex_ );
// work with serial port
}
// reentrant posprocessing
}
int main(int argc, char* argv[]) {
ros::init(argc, argv, "name");
ros::NodeHandle node("~");
ros::Subscriber sub = node.subscribe("/test", 1, callback);
ros::AsyncSpinner spinner(1);
spinner.start();
while(ros::ok()) {
// reentrant preprocessing
{
std::lock_guard<std::mutex> guard(mutex_);
// work with serial port
}
// reentrant postprocessing
}
}
You can see the code block that is critical. Here, both threads are synchronized, i.e., only one thread is in its critical path at a time.
I used the C++ mutex, as it is the C++ std way, but you could change that of course.
Also, feel free to wait for serial port messages in the main thread to reduce heat production on your chip.
|
71,197,216 | 71,211,971 | Why does compiling a header file with constexpr array use so much memory? | I have a header file with an array of unsigned chars that holds some raw binary data:
#include <string>
#include <array>
extern __declspec(selectany) inline constexpr std::string_view bin_name = std::string_view("test.bin");
extern __declspec(selectany) inline constexpr int bin_size = 10812406;
extern __declspec(selectany) inline constexpr std::array<unsigned char, 10812406> bin_data = {...}
I have another header file that takes that array and writes it to a file:
#include "_.h"
#include <fstream>
void write_file(std::string const outputDir = ".") {
std::ofstream file;
file.open(outputDir + "/" + bin_name.data(), std::ios::out | std::ios::binary);
file.write((const char*)& bin_data[0], bin_size);
file.close();
}
And finally in main I just call the function to write the file:
#include "_.h"
int main()
{
write_file();
}
Trying to compile the above in Visual Studio, or directly using cl (cl /Os /std:c++17 /Zc:externConstexpr main.cpp) results in the compiler using more than 12 GB of memory!
The bin_data is only around 10 MB in size, so the >12GB allocation by the compiler seems an overkill. More importantly, the actual size of the binary data I wanted to use is around 50 MB, however as you might have guessed, compiling that exceeds my systems 32GB of ram, thus I can't do that.
So my questions are:
Why does the compiler need so much ram?
What can I do to reduce that?
Is this a bug?
Is this behavior unique to vc++, or does the same happen in gcc/clang?
| Compilers don't tend to do well with large initializers since the go-to method of compiling an initializer is to make an AST node for each element.
There's a proposal to deal with this in the language directly that includes motivation and alternatives:
constexpr std::span<const std::byte> bin_data = std::embed("test.bin");
The author of this proposal also wrote a blog post to look at the current state of things and further argue for the proposal.
The alternatives aren't really great. One technique is to put the large initializer into its own translation unit to avoid recompiling it. However, that doesn't scale—your too-large initializer would need to be split up appropriately to cap the memory usage for any particular TU, and that still doesn't play well with parallelized builds.
Another technique is to encode the data within a string literal and then parse it to get the type you were looking for. The proposal mentions that MSVC doesn't allow large string literals, and I don't know whether that's changed in the past couple years. Regardless of whether the data file contains the string literal directly or is used to generate the string literal in a build step, it's not great.
Then there are the alternatives that perform better, but are quite non-portable and might require significant effort and ugliness to make portable enough. This involves placing the data directly in a file that is linked to, with tools to make that feasible and symbols to access the data. These also remove the possibility of using the data in constant expressions.
All in all, I haven't come across an alternative that doesn't come with significant baggage. From a business perspective, I would quite honestly consider that supporting the standardization efforts of a good solution could be worth it in the long run. Contributing optimizations to compilers' handling of large initializers is another avenue, but certainly isn't a trivial task. Circle had some success as part of the blog post's benchmarks, but that doesn't mean it's easy to transfer the results to other compilers, and MSVC is off the table entirely there.
|
71,197,736 | 71,197,799 | C++ Linked List from header file is resetting memory storage | So I've been working on a linked list in C++ through a header file. When I insert values into it, it works fine, but as soon as I return to the main class and try to print the value stored inside a node, it returns a negative number. Here is an excerpt of my code so far, I tried to keep it as simplistic as possible.
This is the header file that contains the code for the linked list.
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class LinkedList {
public:
struct Node {
T data;
struct Node* next;
};
Node* head;
void AddHead(const T& addData) {
Node n;
n.data = addData;
n.next = head;
head = &n;
Print();
}
void Print() {
cout << head << " " << (*head).data << endl;
}
private:
};
And here is the reference from main.
LinkedList<int> l = LinkedList<int>();
int i = 5;
l.AddHead(i);
l.Print();
Now I thought this would work fine, but apparently something happens between when the node is added, when the program returns out of the header file, and when it prints again. I put in a second print statement inside to show the difference.
As it stands the output looks like this:
0000004F9A8FF7F8 5
0000004F9A8FF7F8 -1464607816
So at the same memory address, the value stored inside changes? I don't know what I'm doing wrong and I appreciate any help.
| void AddHead(const T& addData) {
Node n;
n.data = addData;
n.next = head;
head = &n;
Print();
}
Once AddHead ends n is released, its a temorary variable on the stack. You have to create the nodes on the heap
void AddHead(const T& addData) {
Node *n = new Node();
n->data = addData;
n->next = head;
head = n;
Print();
}
And next advice. dont use naked pointers, use std::shared_ptr or std::unique_ptr.
|
71,197,769 | 71,207,983 | how to read and update the SACL properties of a folder in a remote machine in active directory | I am trying to read and update the SACL properties of a folder in a domain machine from the domain controller.
I came across this link but I don't know how to use the IADs::Get to get the object of the folder from the active directory.
I am struggling to find the ldap query to get the folder, I searched all over the internet but I couldn't find a single example for this use case.
Can anyone help me with an example or a reference?
| IADs::Get is only for objects in Active Directory itself. You can't use it for files on a file system.
To modify permissions a file on a remote computer, you treat it pretty much the same as a file on the local system. You can use GetNamedSecurityInfo, where pObjectName would be the path to the file in the format of \\server\share\directory\file.txt and ObjectType is SE_FILE_OBJECT.
The credentials being used to run your program will need to already have rights to access that file on the remote system.
Some more reading here: File Security and Access Rights
|
71,197,988 | 71,198,093 | Built-in array with variable size? | Chapter 2.3.2 of The C++ Programming Language lists this constructor:
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { }
private:
double* elem;
int sz;
};
As far as I know, the array size must be a constant expression, and s isn't. Is this legal? If so, why?
| Yes, it's legal because the array is allocated at runtime with the 'new' operator.
If you want to allocate an array at compile-time, you must provide a const int, or constant expression.
int count = 0;
cin >> count;
int* a = new int[count]; // This is dynamic allocation happen at runtime.
int b[6]; // This is static allocation and it happen at compile-time.
|
71,198,597 | 71,199,520 | is a concurent write and read to a non-atomic variable of fundamental type without using it undefined behavior? | in a lock-free queue.pop(), I read a trivialy_copyable variable (of integral type) after synchronization with an atomic aquire inside a loop.
Minimized pseudo code:
//somewhere else writePosition.store(...,release)
bool pop(size_t & returnValue){
writePosition = writePosition.load(aquire)
oldReadPosition = readPosition.load(relaxed)
size_t value{};
do{
value = data[oldReadPosition]
newReadPosition = oldReadPosition+1
}while(readPosition.compare_exchange(oldReadPosition, newReadPosition, relaxed)
// here we are owner of the value
returnValue = value;
return true;
}
the memory of data[oldReadPosition] can only be changed iff this value was read from another thread bevor.
read and write Positions are ABA safe.
with a simple copy, value = data[oldReadPosition] the memory of data[oldReadPosition] will not be changed.
but a write thread queue.push(...) can change data[oldReadPosition] while reading, iff another thread has already read oldPosition and changed the readPosition.
it would be a race condition, if you use the value, but is it also a race condition, and thus undefined behavior, when we leave value untouched? the standard is not spezific enough or I don´t understand it.
imo, this should be possible, because it has no effect.
I would be very happy to get an qualified answer to get deeper insights
thanks a lot
| Yes, it's UB in ISO C++; value = data[oldReadPosition] in the C++ abstract machine involves reading the value of that object. (Usually that means lvalue to rvalue conversion, IIRC.)
But it's mostly harmless, probably only going to be a problem on machines with hardware race detection (not normal mainstream CPUs, but possibly on C implementations like clang with threadsanitizer).
Another use-case for non-atomic read and then checking for possible tearing is the SeqLock, where readers can prove no tearing by reading the same value from an atomic counter before and after the non-atomic read. It's UB in C++, even with volatile for the non-atomic data, although that may be helpful in making sure the compiler-generated asm is safe. (With memory barriers and current handling of atomics by existing compilers, even non-volatile makes working asm). See Optimal way to pass a few variables between 2 threads pinning different CPUs
atomic_thread_fence is still necessary for a SeqLock to be safe, and some of the necessary ordering of atomic loads wrt. non-atomic may be an implementation detail if it can't sync with something and create a happens-before.
People do use Seq Locks in real life, depending on the fact that real-life compilers de-facto define a bit more behaviour than ISO C++. Or another way to put it is that happen to work for now; if you're careful about what code you put around the non-atomic read it's unlikely for a compiler to be able to do anything problematic.
But you're definitely venturing out past the safe area of guaranteed behaviour, and probably need to understand how C++ compiles to asm, and how asm works on the target platforms you care about; see also Who's afraid of a big bad optimizing compiler? on LWN; it's aimed at Linux kernel code, which is the main user of hand-rolled atomics and stuff like that.
|
71,199,179 | 71,209,937 | CMake project builds but shows include error in LSP | I'm working on a C++ project using ccls (the LSP language server) and lsp-mode in Emacs. I also have a CMake project definition for my project. My project builds correctly with make using the Makefile generated by CMake, but ccls says that my #include is not found.
Here's the project structure:
+ CMakeLists.txt
+ main.cpp
+ src/
|\
| + SomeClass.cpp
| + SomeClass.hpp
The CMakeLists.txt file looks like this:
cmake_minimum_required(VERSION 3.22)
project(includefail)
set(simple_VERSION_MAJOR 0)
set(simple_VERSION_MINOR 1)
add_executable(
includefail
${CMAKE_SOURCE_DIR}/main.cpp
${CMAKE_SOURCE_DIR}/src/SomeClass.cpp
)
target_include_directories(
includefail PRIVATE
${CMAKE_SOURCE_DIR}/src
)
This generates the following compile_commands.json (which is what ccls uses):
[
{
"directory": "/home/user/code/c/include-fail/build",
"command": "/usr/bin/c++ -I/home/user/code/c/include-fail/src -o CMakeFiles/includefail.dir/main.cpp.o -c /home/user/code/c/include-fail/main.cpp",
"file": "/home/user/code/c/include-fail/main.cpp"
},
{
"directory": "/home/user/code/c/include-fail/build",
"command": "/usr/bin/c++ -I/home/user/code/c/include-fail/src -o CMakeFiles/includefail.dir/src/SomeClass.cpp.o -c /home/user/code/c/include-fail/src/SomeClass.cpp",
"file": "/home/user/code/c/include-fail/src/SomeClass.cpp"
}
]
src/SomeClass.hpp looks like this:
class SomeClass {
public:
SomeClass();
private:
int x;
};
src/SomeClass.hpp looks like this:
#include "SomeClass.hpp"
SomeClass::SomeClass() {
x = 1;
}
And main.cpp looks like this:
#include "SomeClass.hpp"
int main(int argc, char* arv[]) {
SomeClass sc = SomeClass();
return 0;
}
It's in main.cpp where I get the error from LSP. It says 'SomeClass.hpp' file not found.
So why is ccls not able to find this include?
| ccls tries to find SomeClass.hpp in the root of your project.
It should be fine when you change the first line of your main.cpp to this (At least for me it resolved the error):
#include "src/SomeClass.hpp"
|
71,199,229 | 71,199,296 | OpenGL. Multiplying a vertex by a projection matrix | I'm trying to draw a model and this is what I ran into, the code below works like 2d, although there should be a perspective
Code # 1
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
norm = Proj * View * World * vec4(t.norm, 0);
dot1 = Proj * View * World * vec4(t.dot1, 1);
dot2 = Proj * View * World * vec4(t.dot2, 1);
dot3 = Proj * View * World * vec4(t.dot3, 1);
glNormal3f(norm);
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex3f(dot2.x, dot2.y, dot3.z);
glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();
And so the perspective appears:
Code # 2
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glMatrixMode(GL_PROJECTION);
glLoadMatrix(Proj);
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
norm = View * World * vec4(t.norm, 0);
dot1 = View * World * vec4(t.dot1, 1);
dot2 = View * World * vec4(t.dot2, 1);
dot3 = View * World * vec4(t.dot3, 1);
glNormal3f(norm);
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex3f(dot2.x, dot2.y, dot3.z);
glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();
From which the question arose: why code 2 and code 3 get the same result, but code 1 and code 2 are different?
Code # 3
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glMatrixMode(GL_PROJECTION);
glLoadMatrix(Proj);
*glMatrixMode(GL_MODELVIEW);
glLoadMatrix(View);*
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
norm = World * vec4(t.norm, 0);
dot1 = World * vec4(t.dot1, 1);
dot2 = World * vec4(t.dot2, 1);
dot3 = World * vec4(t.dot3, 1);
glNormal3f(norm);
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex3f(dot2.x, dot2.y, dot3.z);
glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();
Tell me what am I doing wrong? How can I calculate the vertex multiplied by the projection matrix correctly?
| The transformation with the projection matrix generates Homogeneous coordinates. A Homogeneous coordinate has 4 components, but you just pass 3 components to the vertex coordinate. Use all 4 components to specify the vertex coordinate. e.g:
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex4f(dot1.x, dot1.y, dot1.z, dot1.w);
or
glVertex4fv(glm::value_ptr(dot1));
|
71,199,354 | 71,200,047 | Vulkan dynamic rendering, nothing seems to be getting rasterized | I am trying to render using the dynamic rendering extension, to this effect I am trying to render just a triangle with these 2 shaders:
#version 450
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 0) out vec3 fragColor;
void main() {
gl_Position = vec4(inPosition, 0.5, 1.0);
fragColor = inColor;
}
#version 450
layout(location = 0) in vec3 fragColor;
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(vec3(1), 1.0);
}
I am testing my first frame with renderdoc, the vertices seem fine:
So does the output of the vertex shader:
These are the rasterization settings:
As you can see there is no culling, so no matter what the triangle should be rasterized.
But when I go onto the FB both the swapchain image and depth attachment are unaffected. The depth is 1 everywhere and the color attachment is 0 everywhere.
I don't understand why this is not rendering.
| In case someone runs into this problem in the future.
I was trying to render just a single frame (rather than on a loop) so I was not synchronizing objects because I thought it would not be necessary.
Turns out it very much is, so if you are rendering to the swacphain images even if just once, things won't work unless you use the appropriate fences and semaphores.
|
71,199,574 | 71,200,028 | C++20 Concepts: Explicit instantiation of partially ordered constraints for member functions | This works and outputs "1", because the function's constraints are partially ordered and the most constrained overload wins:
template<class T>
struct B {
int f() requires std::same_as<T, int> {
return 0;
}
int f() requires (std::same_as<T, int> && !std::same_as<T, char>) {
return 1;
}
};
int main() {
std::cout << B<int>{}.f();
}
This works as well, because explicit instantiation doesn't instantiate member functions with unsatisfied constraints:
template<class T>
struct B {
int f() requires std::same_as<T, int> {
return 0;
}
int f() requires (!std::same_as<T, int>) {
return 1;
}
};
template struct B<int>;
So what should this do?
template<class T>
struct B {
int f() requires std::same_as<T, int> {
return 0;
}
int f() requires (std::same_as<T, int> && !std::same_as<T, char>) {
return 1;
}
};
template struct B<int>;
Currently this crashes trunk gcc because it compiles two functions with the same mangling. I think it would make sense to compile only the second function, so that the behavior is consistent with the regular overload resolution. Does anything in the standard handle this edge case?
| C++20 recognizes that there can be different spellings of the same effective requirements. So the standard defines two concepts: "equivalent" and "functionally equivalent".
True "equivalence" is based on satisfying the ODR (one-definition rule):
Two expressions involving template parameters are considered equivalent if two function definitions containing the expressions would satisfy the one-definition rule, except that the tokens used to name the template parameters may differ as long as a token used to name a template parameter in one expression is replaced by another token that names the same template parameter in the other expression.
There's more to it, but that's not an issue here.
Equivalence for template heads includes that all constraint expressions are equivalent (template headers include constraints).
Functional equivalence is (usually) about the results of expressions being equal. For template heads, two template heads that are not ODR equivalent can be functionally equivalent:
Two template-heads are functionally equivalent if they accept and are satisfied by ([temp.constr.constr]) the same set of template argument lists.
That's based in part on the validity of the constraint expressions.
Your two template heads in versions 1 and 3 are not ODR equivalent, but they are functionally equivalent, as they both accept the same template parameters. And the behavior of that code will be different from its behavior if they were ODR equivalent. Therefore, this passage kicks in:
If the validity or meaning of the program depends on whether two constructs are equivalent, and they are functionally equivalent but not equivalent, the program is ill-formed, no diagnostic required.
As such, all of the compilers are equally right because your code is wrong. Obviously a compiler shouldn't straight-up crash (and that should be submitted as a bug), but "ill-formed, no diagnostic required" often carries with it unforeseen consequences.
|
71,199,777 | 71,199,988 | Any way to know how many bytes will be sent on TCP before sending? | I'm aware that the ::send within a Linux TCP server can limit the sending of the payload such that ::send needs to be called multiple times until the entire payload is sent.
i.e. Payload is 1024 bytes
sent_bytes = ::send(fd, ...) where sent_bytes is only 256 bytes so this needs to be called again.
Is there any way to know exactly how many bytes can be sent before sending? If the socket will allow for the entire message, or that the message will be fragmented and by how much?
Example Case
2 messages are sent to the same socket by different threads at the same time on the same tcp client via ::send(). In some cases where messages are large multiple calls to ::send() are required as not all the bytes are sent at the initial call. Thus, go with the loop solution until all the bytes are sent. The loop is mutexed so can be seen as thread safe, so each thread has to perform the sending after the other. But, my worry is that beacuse Tcp is a stream the client will receive fragments of each message and I was thinking that adding framing to each message I could rebuild the message on the client side, if I knew how many bytes are sent at a time.
Although the call to ::send() is done sequentially, is the any chance that the byte stream is still mixed?
Effectively, could this happen:
Server Side
Message 1: "CiaoCiao"
Message 2: "HelloThere"
Client Side
Received Message: "CiaoHelloCiaoThere"
|
Although the call to ::send() is done sequentially, is the any chance that
the byte stream is still mixed?
Of course. Not only there's a chance of that, it is pretty much going to be a certainty, at one point or another. It's going to happen at one point. Guaranteed.
sent to the same socket by different threads
It will be necessary to handle the synchronization at this level, by employing a mutex that each thread locks before sending its message and unlocking it only after the entire message is sent.
It goes without sending that this leaves open a possibility that a blocked/hung socket will result in a single thread locking this mutex for an excessive amount of time, until the socket times out and your execution thread ends up dealing with a failed send() or write(), in whatever fashion it is already doing now (you are, of course, checking the return value from send/write, and handling the exception conditions appropriately).
There is no single, cookie-cutter, paint-by-numbers, solution to this that works in every situation, in every program, that needs to do something like this. Each eventual solution needs to be tailored based on each program's unique requirements and purpose. Just one possibility would be a dedicated execution thread that handles all socket input/output, and all your other execution threads sending their messages to the socket thread, instead of writing to the socket directly. This would avoid having all execution thread wedged by a hung socket, at expense of grown memory, that's holding all unsent data.
But that's just one possible approach. The number of possible, alternative solutions has no limit. You will need to figure out which logic/algorithm based solution will work best for your specific program. There is no operating system/kernel level indication that will give you any kind of a guarantee as to the amount of a send() or write() call on a socket will accept.
|
71,199,868 | 71,204,101 | C++ Use a class non-static method as a function pointer callback in freeRTOS xTimerCreate | I am trying to use marvinroger/async-mqtt-client that in the provided examples is used together with freertos timers that use a callback that gets invoked whenever the timer expire. The full example is here.
I wanted to create a singleton class to enclose all the connection managing part and just expose the constructor (through a getInstance) and a begin function that other than setting the callbacks, creates the timers for reconnection.
The class looks like (I simplified by removing useless parts):
class MqttManager : public Singleton<MqttManager> {
public:
virtual ~MqttManager() = default;
void begin();
protected:
MqttManager();
void connectToMqtt(TimerHandle_t xTimer);
void WiFiEvent(WiFiEvent_t event);
void onConnect(bool sessionPresent);
std::unique_ptr<AsyncMqttClient> client;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
};
While my issue is when I try to pass the connectToMqtt callback to the timer.
MqttManager::MqttManager() {
this->client = std::unique_ptr<AsyncMqttClient>(new AsyncMqttClient());
// use bind to use a class non-static method as a callback
// (works fine for mqtt callbacks and wifi callback)
this->client->onConnect(std::bind(&MqttManager::onConnect, this, std::placeholders::_1));
WiFi.onEvent(std::bind(&MqttManager::WiFiEvent, this, std::placeholders::_1));
// Here it fails
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)nullptr, &MqttManager::connectToMqtt, this, std::placeholders::_1);
The error is:
cannot convert 'void (MqttManager::)(TimerHandle_t) {aka void (MqttManager::)(void*)}' to 'TimerCallbackFunction_t {aka void ()(void)}' for argument '5' to 'void* xTimerCreate(const char*, TickType_t, UBaseType_t, void*, TimerCallbackFunction_t)'
Now, from here, having in mind that the problem is around having a pointer to a non-static method that needs somehow to be casted to a free function pointer, three doubts arise:
Why on earth the std::bind "approach" works for WiFi.onEvent but not for xTimerCreate? They seem pretty similar to me... WiFi is typedef void (*WiFiEventCb)(system_event_id_t event); while the timer typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
How can I make this work? Is there a cast or a better approach?
Is this bad practice? My goal here was to enclose mqtt and wifi functions and callbacks in a neat class easily recognizable, organized and maintainable; but I guess that sometimes you just obtain the opposite result without noticing...
|
FreeRTOS code is plain old C. It knows nothing about C++, instance methods, function objects, etc. It takes a pointer to a function, period. As Armandas pointed out, WiFi.onEvent on the other hand is C++, lovingly written by someone to accept output from std::bind().
There is a workaround. When you read the xTimerCreate API docs, there is a sneaky little parameter pvTimerID which is effectively user-specified data. You can use this to pass a pointer to your class and later retrieve it from inside the callback function using pvTimerGetTimerID(). With a class pointer you can then forward the callback to your C++ class. See example below.
It's good practice to try to hide private class methods and data. Unfortunately this only works well if you're working entirely in C++ :) If calling into C libraries (like FreeRTOS) I find myself breaking such idealistic principles occasionally.
Here's how I'd do it. I use a lambda (without context) as the actual callback function because it's throwaway wrapper code, and the C libraries happily accept it as a plain old function pointer.
auto onTimer = [](TimerHandle_t hTmr) {
MqttManager* mm = static_cast<MqttManager*>(pvTimerGetTimerID(hTmr)); // Retrieve the pointer to class
assert(mm); // Sanity check
mm->connectToMqtt(hTmr); // Forward to the real callback
}
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, static_cast<void*>(this), onTimer);
|
71,200,268 | 71,200,313 | What causes this code to trigger implicit int narrowing? | The following code makes clang to fail when -Wc++11-narrowing is specified
#include <stdint.h>
extern uint8_t numbers[];
extern int n;
uint8_t test(int num) {
uint8_t a{n > 0 ? *numbers : 2};
return a;
}
(Same code in godbolt: https://godbolt.org/z/nTKqT7WGd)
8:15: error: non-constant-expression cannot be narrowed from type 'int' to 'uint8_t' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]
uint8_t a{n > 0 ? *numbers : 2};
I read the standard and related issues but I cannot comprehend why a ternary operation with two results that are uint8_t or can be transparently narroweduint8_t (i.e: constant 2) result in a promotion to int that then wants to be explicitly narrowed.
Can someone explain why this happens? Thanks!
| The second operand to the conditional expression has type uint8_t. The third operand, the literal 2, has type int.
When the second and third operands to a conditional expression are of different arithmetic type, the usual arithmetic conversions are performed in order to bring them to their common type. [expr.cond]/7.2
In this case the usual arithmetic conversions involve the promotion of both types, namely uint8_t and int. [expr.arith.conv]/1.5
Because int can represent all values of type uint8_t, the result of the promotion of uint8_t is int. int is unaffected by integral promotions and remains int. [conv.prom]
The result of the conditional expression has type int. A conversion from int to uint8_t is narrowing, since uint8_t cannot represent all values of type int.
|
71,200,440 | 71,200,531 | Forward declaration of class and still Error: Variable has incomplete type | I have defined two classes : (1) class Point_CCS_xy , and (2) random_Point_CCS_xy_generator. I would like to define a function in Point_CCS_xy class which makes use of random_Point_CCS_xy_generator class to generate random points on a cartesian coordinate system within a range Min and Max, both of which have been defined as long double. I have already forward declared class random_Point_CCS_xy_generator, however I get an Variable has incomplete type random_Point_CCS_xy_generator error on this line random_Point_CCS_xy_generator rpg(Min, Max); and also this error Member reference base type 'vector<Point_CCS_xy> (size_t)' (aka 'vector<Point_CCS_xy> (unsigned long long)') is not a structure or union, on this line Point_CCS_xy_vec.push_back(p);.
MWE
#include<iostream>
#include<fstream>
#include<functional>
#include<algorithm>
#include<vector>
#include<deque>
#include<queue>
#include<set>
#include<list>
#include<limits>
#include<string>
#include<memory>
using namespace std;
typedef long double ld;
class random_Point_CCS_xy_generator;
class Point_CCS_xy{
private:
long double x_coordinate_ {0.0};
long double y_coordinate_ {0.0};
public:
Point_CCS_xy () = default;
Point_CCS_xy(long double x, long double y): x_coordinate_(x), y_coordinate_(y) {}
~Point_CCS_xy() = default;
// copy constructor through construction delegation method
Point_CCS_xy(const Point_CCS_xy& cpyObj) : Point_CCS_xy(cpyObj.x_coordinate_, cpyObj.y_coordinate_)
{
}
// Copy and Mover Assignment Operators,
// also setters and getters, and a few utility functions come here inlcuding:
friend ostream& operator<<(ostream& os, const Point_CCS_xy& pnt);
// Problematic Function -> source of ERRORS
vector<Point_CCS_xy> Random_Point_CCS_xy(long double Min, long double Max, size_t n) {
random_Point_CCS_xy_generator rpg(Min, Max);
vector<Point_CCS_xy> Point_CCS_xy_vec(size_t);
for (size_t i = 0; i < n; ++i){
Point_CCS_xy p = Point_CCS_xy(rpg());
Point_CCS_xy_vec.push_back(p);
}
return Point_CCS_xy_vec;
}
};
ostream& operator<<(ostream& os, const Point_CCS_xy& pnt) {
os << "X: " << setw(10)<< left << pnt.x_coordinate_ << " Y: " << setw(10)<< left << pnt.y_coordinate_;
return os;
}
class random_Point_CCS_xy_generator {
public:
random_Point_CCS_xy_generator(long double min, long double max)
: engine_(std::random_device()()), distribution_(min, max) {}
Point_CCS_xy operator()() {
long double x = distribution_(engine_);
long double y = distribution_(engine_);
return Point_CCS_xy(x, y);
}
std::mt19937 engine_;
std::uniform_real_distribution<double> distribution_;
};
As I am a newbie in programming, any idea would be highly appreciated.
| The type must be complete by the time you actually use it (e.g. constructing a value). Forward declaration will only help you specify pointer or reference types, not value types.
Your main issue here is that you're defining your functions inline in the class definition. Instead of that, move them out:
class Point_CCS_xy {
private:
long double x_coordinate_{ 0.0 };
long double y_coordinate_{ 0.0 };
public:
Point_CCS_xy() = default;
Point_CCS_xy(long double x, long double y) : x_coordinate_(x), y_coordinate_(y) {}
~Point_CCS_xy() = default;
Point_CCS_xy(const Point_CCS_xy& cpyObj);
vector<Point_CCS_xy> Random_Point_CCS_xy(long double Min, long double Max, size_t n);
friend ostream& operator<<(ostream& os, const Point_CCS_xy& pnt);
};
class random_Point_CCS_xy_generator {
public:
random_Point_CCS_xy_generator(long double min, long double max)
: engine_(std::random_device()()), distribution_(min, max) {}
Point_CCS_xy operator()() {
long double x = distribution_(engine_);
long double y = distribution_(engine_);
return Point_CCS_xy(x, y);
}
std::mt19937 engine_;
std::uniform_real_distribution<double> distribution_;
};
Then you can define the functions after:
Point_CCS_xy::Point_CCS_xy(const Point_CCS_xy& cpyObj)
: Point_CCS_xy(cpyObj.x_coordinate_, cpyObj.y_coordinate_)
{
}
vector<Point_CCS_xy> Point_CCS_xy::Random_Point_CCS_xy(long double Min, long double Max, size_t n)
{
random_Point_CCS_xy_generator rpg(Min, Max);
vector<Point_CCS_xy> Point_CCS_xy_vec;
Point_CCS_xy_vec.reserve(n);
for (size_t i = 0; i < n; ++i) {
Point_CCS_xy p = Point_CCS_xy(rpg());
Point_CCS_xy_vec.push_back(p);
}
return Point_CCS_xy_vec;
}
ostream& operator<<(ostream& os, const Point_CCS_xy& pnt)
{
os << "X: " << setw(10) << left << pnt.x_coordinate_ << " Y: " << setw(10) << left << pnt.y_coordinate_;
return os;
}
Note that I fixed another error where you used size_t instead of n as an argument to the constructor for your vector. As pointed out in the comments, that's actually incorrect to begin with because of the way you're populating the vector. Instead, I changed it to reserve the required size before pushing elements.
Also you're missing some headers and using loads of others. All you really need is:
#include <iostream>
#include <iomanip>
#include <vector>
#include <random>
|
71,200,746 | 71,200,803 | Error with befriending a function in a namespace in C++ | I've tried to befriend a function in a namespace but I don't know why there is an error:
Error C2653 'a': is not a class or namespace name
I've tried multiple times and I don't think it's a mistake on my part but take a look:
class plpl
{
private:
int m;
public:
plpl()
: m(3) {}
friend void a::abc();
};
namespace a {
void abc();
void abc()
{
plpl p;
std::cout << p.m << std::endl;
}
}
I use Visual Studio 2019. I don't know what to do, please help.
| As suggested in comments, you need to forward declare the namespace a and the function abc, as shown below.
#include <iostream>
namespace a {
void abc();
}
class plpl {
private:
int m;
public:
plpl() : m(3) {}
friend void a::abc();
};
namespace a {
void abc() {
plpl p;
std::cout << p.m << std::endl;
}
}
|
71,200,786 | 71,200,919 | recursive function for checking if the array is sorted not working | i wrote this isSorted function that will check if the array is sorted or not
if the array is sorted, it will return 0, else it will return 1,
but for some reason, the function keeps on returning 0 even if the array is not sorted. This is the full program with the function
struct array {
int A[10];
int size;
int length;
};
void displayArray(struct array arr) {
std::cout << "the elements are :-" << std:: endl << '\t';
for (int i = 0; i < arr.length; i++) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
int ifSorted(int *a, int n, int i) {
if (n >0) {
if (*(a + i) > *(a + 1 + i))
return -1;
else {
i++;
ifSorted(a, n - 1, i);
}
return 0;
}
}
int main()
{
struct array arr = {{1,2,3,10,5,6,7}, 10, 7};
int* p;
std::cout << ifSorted(&(arr.A[0]), arr.length, 0);
}
I tried to debug the program and It works how it is supposed to but instead of returning -1 , it is returning 0.
|
but instead of returning -1 , it is returning 0
When you write return -1; that value is only passed back to the caller. Now, at that point, you might be several calls deep into the recursion. The line from the call immediately before is this:
ifSorted(a, n - 1, i);
So, what happens is after that call returns, you discard the return value of -1 and continue executing from this call. You ultimately then return 0, because that is the next statement.
To fix this, you must pass back to the caller whatever the recursive call returned:
return ifSorted(a, n - 1, i);
Now, you have some other problems too. To begin with, let's see what happens if n is zero (or negative)...
int ifSorted(int *a, int n, int i) {
if (n > 0) {
// this code is never reached
}
// there is no return value
}
This is a problem. You have undefined behavior for a very important case. At some point, if everything is already in sorted order, your final recursion will ask whether an empty array is sorted. Of course, it is, but your function must return something. So let's fix that:
int ifSorted(int *a, int n, int i) {
if (n > 0) {
// this code is never reached
}
return 0;
}
Now, let's think about one other special case. What if there's only one element in the array (i.e. n is 1)? Well, you're doing this:
if (*(a + i) > *(a + 1 + i))
return -1;
But the problem is that *(a + 1 + i) is the element past the end of the array.
So actually, your "zero-size array is sorted" logic really should extend to "zero- or one-size array is sorted". That will solve that nasty problem.
On another note, I'd recommend you don't use pointer arithmetic for accessing your array elements. Use array indexing. The compiler will generate the same instructions, but the code is easier for humans to read.
if (a[i] > a[i + 1])
return -1;
Furthermore, it's not very "recursion-friendly" to add the parameter i. That's kinda showing that you're still thinking of it like a loop. Instead, recursion is about breaking a problem down into smaller problems. What you can do is advance the array pointer by 1 when you reduce its size by 1. That makes i utterly redundant.
Finally, because the function never intends to modify the array's contents, it's best to enforce that by declaring a as const. This way, your function can operate on arrays that are already const, and you can't accidentally write code that modifies the array because that will be a compiler error.
Phew.... Well, let's put all of this together:
int ifSorted(const int *a, int n)
{
if (n < 2)
return 0;
else if (a[0] > a[1])
return -1;
return ifSorted(a + 1, n - 1);
}
|
71,200,820 | 71,625,662 | CMake trying to link with 'vulkan.lib' | I am following a Vulkan tutorial and I choose CMake as my build system. However, the build fails every time because it is trying to link with a file called 'vulkan.lib' from what I know, there's no such file as vulkan.lib because the actual library file for Vulkan is 'vulkan-1.lib'
Here is my CMake script:
project(VulkanTutorial)
set(CMAKE_CXX_STANDARD 20)
add_executable(VulkanTutorial main.cpp VulkanWindow.cpp VulkanWindow.h FirstApp.h)
add_subdirectory(deps/glfw-3.3.6)
find_package(Vulkan REQUIRED)
include_directories(deps/glfw-3.3.6/include, ${Vulkan_INCLUDE_DIRS})
target_link_libraries(VulkanTutorial glfw ${GLFW_LIBRARIES})
target_link_libraries(VulkanTutorial vulkan ${Vulkan_LIBRARIES})
And here is the build log from Visual Studio:
Build started...
1>------ Build started: Project: ZERO_CHECK, Configuration: Debug x64 ------
1>Checking Build System
2>------ Build started: Project: glfw, Configuration: Debug x64 ------
2>Building Custom Rule C:/dev/c++/VulkanTutorial (Cmake)/deps/glfw-3.3.6/src/CMakeLists.txt
2>context.c
2>init.c
2>input.c
2>monitor.c
2>vulkan.c
2>window.c
2>win32_init.c
2>win32_joystick.c
2>win32_monitor.c
2>win32_time.c
2>win32_thread.c
2>win32_window.c
2>wgl_context.c
2>egl_context.c
2>osmesa_context.c
2>Generating Code...
2>glfw.vcxproj -> C:\dev\c++\VulkanTutorial (Cmake)\deps\glfw-3.3.6\src\Debug\glfw3.lib
3>------ Build started: Project: VulkanTutorial, Configuration: Debug x64 ------
3>Building Custom Rule C:/dev/c++/VulkanTutorial (Cmake)/CMakeLists.txt
3>main.cpp
3>VulkanWindow.cpp
3>Generating Code...
3>LINK : fatal error LNK1104: cannot open file 'vulkan.lib'
3>Done building project "VulkanTutorial.vcxproj" -- FAILED.
========== Build: 2 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
| Thanks to @Stephen Newell's comment I solved it by getting rid of the vulkan in the second target_link_libraries call and it worked.
|
71,201,005 | 71,203,546 | Why the sequence from the bitwise operator(~) would be this? Is that broken? | #include <stdio.h>
#include <stdlib.h>
int main() {
unsigned char a=100,b=50;
printf("%d & %d = %d\n",a,b,a&b);
printf("%d | %d = %d\n",a,b,a|b);
printf("%d ^ %d = %d\n",a,b,a^b);
printf(" ~%d = %d\n",a, ~a); /*the out come of this line would be this: ~100 = -101 */
printf(" %d >> 2= %d\n",a, a>>2);
printf(" %d << 2= %d\n",a, a<<2);
system("pause");
return 0;
}
/the out come should be 155 ,isn't it?/
| According to the standard, the operand of ~ will undergo integral promotion. So here we will first promote a to int.
[expr.unary.op]: The operand of ~ shall have integral or unscoped enumeration type; the result is the ones' complement of its operand. Integral promotions are performed.
If int is 4 bytes (for example), the value of the promoted a is 0x00000064. The result of ~a is 0xFFFFFF9B, which is exactly -101(If using two's complement to represent integers).
Please note that although variadic arguments will undergo integral promotion, here ~a is of type int and no additional promotion is required.
|
71,201,135 | 71,201,223 | Getting an error while using begin and end iterators | vector <vector<int> > v8;
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
int n;
cin >> n;
vector <int> temp;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
temp.push_back(x);
}
v8.push_back(temp);
}
vector <int> ::iterator it;
for (it = v8.begin(); it < v8.end(); it++)
{
cout << (*it) << " ";
}
I'm getting this error:
no operator "=" matches these operandsC/C++(349)
intro.cpp(161, 13): operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>> = __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int>> *, std::vector<std::vector<int, std::allocator<int>>, std::allocator<std::vector<int, std::allocator<int>>>>>
How should I solve this??
| The problem is that it is an iterator to 1D vector<int> while b8.begin() gives us an iterator to a 2D vector<vector<int>>. So these iterators are not compatible with each other. That is, you cannot use the iterator it to traverse a 2D vector.
You can solve this by changing vector <int> ::iterator it; as shown below:
vector <vector<int>> ::iterator it; //change made here. Now it is an iterator to a 2D vector
for (it = v8.begin(); it != v8.end(); it++)
{
for(auto i = (*it).begin(); i != (*it).end();++i) // i is an iterator to a 1D vector
{
cout << (*i) << " ";//it changed to i
}
}
Another option would be to use auto with range-based for loop as shown below:
for (auto &row: v8)
{
for(auto &col: row)
{
cout << col << " ";
}
}
|
71,201,745 | 71,201,892 | How can I sort two arrays in descending order? | I am trying to write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10).
I need to modify the program so that it outputs a list in order of number of pancakes eaten of all 10 people.
Example:
Person 4: ate 10 pancakes
Person 3: ate 7 pancakes
Person 8: ate 4 pancakes
...
Person 5: ate 0 pancakes
I have been able to sort the number of pancakes into descending order, however I am struggling to assign the correct Person to their number of pancakes.
Here is my code so far:
int main()
{
int person[10];
int i;
int input;
int n = sizeof(person) / sizeof(person[0]);
// store the number entered by the user in each array element
for(i = 0; i < 10; ++i)
{
cout << "How many pancakes did Person " << i + 1 << " eat? ";
cin >> person[i];
}
cout << endl;
cout << endl;
sort(person, person + n, greater<int>()); // sorts array in descending order. "greater()" puts larger numbers first
for(i = 0; i < n; i++)
{
cout << "Person " << i + 1 << " ate " << person[i] << " pancakes." << endl;
}
return 0;
}
Any help would be greatly appreciated!
| You can use a std::vector of std::pair to store the Person index and its corresponding value. Then, you can use a comparator function to sort by values.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<pair<int, int>> person(10);
// store the number entered by the user in each array element
for(int i = 0; i < person.size(); ++i)
{
person[i].first = i + 1;
cout << "How many pancakes did Person " << i + 1 << " eat? ";
cin >> person[i].second;
}
cout << endl;
cout << endl;
auto compare = [](const pair<int, int>& a, const pair<int, int>& b)
{
return a.second > b.second;
};
sort(person.begin(), person.end(), compare);
for(int i = 0; i < person.size(); i++)
{
cout << "Person " << person[i].first << " ate " << person[i].second << " pancakes." << endl;
}
return 0;
}
You can also encapsulate the person details in a struct and use that struct with std::vector:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct Person
{
int index;
int pancakesEaten;
};
int main()
{
vector<Person> person(10);
// store the number entered by the user in each array element
for(int i = 0; i < person.size(); ++i)
{
person[i].index = i + 1;
cout << "How many pancakes did Person " << i + 1 << " eat? ";
cin >> person[i].pancakesEaten;
}
cout << endl;
cout << endl;
auto compare = [](const Person& a, const Person& b)
{
return a.pancakesEaten > b.pancakesEaten;
};
sort(person.begin(), person.end(), compare);
for(int i = 0; i < person.size(); i++)
{
cout << "Person " << person[i].index << " ate " << person[i].pancakesEaten << " pancakes." << endl;
}
return 0;
}
|
71,202,529 | 71,202,678 | why is there written Process terminated with status -1073741510 on my logs | i was just trying code::blocks a few min ago and I just did a simple c out to see if it works
#include <iostream>
using namespace std;
int main()
{
cout << "first program" << endl;
return 0;
}
what`s wrong in this??
| It's a good habit to convert such negative output values from decimal to hexadecimal and to search online for information:
Decimal : -1073741510
Hexadecimal : FFFF FFFF C000 013A
So, you can search for "C000013A".
This link mentions something might be wrong with the way you start/stop your program. I would advise you to launch a command prompt and to launch your program from there. Like this, you should not have that entry in your logs.
|
71,203,108 | 73,068,951 | Enable the writing of ANSI escape codes on a file? | I am struggling with a problem. I searched all around the web and StackOverflow website and found similar questions, but none of them provided me the answer I am searching.
I am on a Linux system (Ubuntu) and basically want to know how to write an ANSI escape code in an output file. For example, if I want to write a red string on the terminal I do:
cout << "\033[31m" << "Red string";
and it works. But if I want to write it on a .rtf file for example:
#include <iostream>
#include <fstream>
using namespace std;
ofstream os( "this_file.rtf" );
os << "\033[31m" << "Red string";
os.close();
it doesn't work and output in the file something like:
#[31mRed string
is there a way to enable the writing of an ANSI escape code on an output file like that one? Thanks.
| After all your answers and weeks of practice, the solution for this answer is pretty obvious and is the following: file redirection of ANSI escape sequences manipulation depends on the kind of file you are writing in and you have to manually set the way in which you want to translate the ANSI into the output file, depending of course also on the file format you are considering.
|
71,203,472 | 71,213,036 | concatenate the images to single image using opencv C++ | I am creating a single image from the video. But I read the video and create frames, then after that rotate the frames and crop the frames and these cropped frames are saved.
These cropped frames should be combined to create a single image.
So I have appended them in the vector of Mat and then want to concatenate them horizontally.
Which I did but it doesn't show any image nor the image is saved.
I want to do something similar to python
list_images = []
for img in glob.glob(crop_dir + "*.jpg"):
n = cv2.imread(img,0)
list_images.append(n)
im_v = np.concatenate(list_images)
cv2.imwrite("finalimg.jpg",im_v)
My variable imglist is of type
class std::vector<class cv::Mat,class std::allocator<class cv::Mat> >
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <filesystem>
using namespace std;
using namespace cv;
namespace fs = std::filesystem;
string crop_dir = "Task2_Resources/CropImages/";
void delete_dir_content(const fs::path& dir_path) {
for (auto& path : fs::directory_iterator(dir_path)) {
fs::remove_all(path);
}
}
int main() {
system("CLS");
if (!fs::is_directory(crop_dir) || !fs::exists(crop_dir)) { // Check if folder exists
fs::create_directory(crop_dir); // create folder
}
delete_dir_content(crop_dir);
VideoCapture vid_capture("Task2_Resources/sample201.avi");
int count = 0;
Mat finalimg,mimg;
vector<cv::Mat> imglist;
Mat image;
int x = 190, y = 59, h = 1, w = 962;
if (!vid_capture.isOpened()){
std::cout << "Cannot open the video file" << endl;
return -1;
}
while (true) {
Mat frame , rimg;
vector<Mat> blocks;
bool isSuccess = vid_capture.read(frame);
if (!isSuccess){
std::cout << "Cannot read the frame from video file" << endl;
break;
}
//imshow("Frames", frame);
count++;
float width = frame.cols;
float height = frame.rows;
Point2f center = Point2f((width / 2), (height / 2));
double degree = -0.2;
double scale = 1.0;
Mat change = getRotationMatrix2D(center, degree, scale); // Rotate & scale
warpAffine(frame, rimg, change, frame.size(), cv::INTER_CUBIC, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0));
Mat cropped_image = rimg(Range(y,y+h), Range(x, x+w));
string fname = to_string(count) + ".jpg";
cv::imwrite(crop_dir + fname, cropped_image);
imglist.push_back(cropped_image);
}
hconcat(imglist,image);
cout << typeid(imglist).name() << endl;
cv::imwrite("final.jpg", image);
std::cout << "Total frames created " << count << endl;
return 0;
}
Visual Studio debug console
| The only issue I could notice is h = 1 - that makes the height of cropped_image to be only 1 pixel.
Since you are not reporting any error message, we can't really tell why it's not working.
I recommend you to use the debugger, and iterate the code step by step (use an IDE for that).
For building a working example, you may follow the stages described next.
There is a chance that one of issues is related to sample201.avi video file.
For making the answer reproducible, we may use FFmpeg CLI for creating synthetic video file:
Please execute the following command from the console (so we have the same input file):
ffmpeg -y -f lavfi -i testsrc=size=1280x720:duration=3:rate=1 sample.avi
The command creates a video file with 3 video frames and resolution 1280x720.
In case you are using Windows, you may need to download FFmpeg (in Linux ffmpeg is usually "built in").
Copy sample.avi to Task2_Resources folder.
Edit your C++ code:
Replace int x = 190, y = 59, h = 1, w = 962; with:
int x = 190, y = 59, h = 500, w = 962;
(Height of 500 pixels is used for example).
Replace VideoCapture vid_capture("Task2_Resources/sample201.avi"); with VideoCapture vid_capture("Task2_Resources/sample.avi");
Execute your code.
Make sure 3 JPG images are created in CropImages folder.
The output file final.jpg is created in the working folder (make sure you have write permissions).
Sample output (resized):
|
71,203,791 | 71,203,935 | Cpp Instance in Instance in... existance | I have some classes in hierarchy. So let's call first class Hardware, it recieves and sends data and each Instance of it wll have some unique parameters. Let it be:
class Hardware{
private:
SPI_TypeDef** Instance;
GPIO_Port* Port;
GPIO_Pin Pin;
int Settings;
public
Hardware();
Hardware(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx);
void TXRX_Data(Byte* TxBuf, Byte* RxBuf, int Length);
};
Then I have class, that controls external device,each device has its own CS (as it is SPI):
class Device{
private:
Hardware Sender;
Byte Parameter_Buffer;
public:
Device();
Device(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx);
void SendParameter(Byte Param);
Byte GetParameter();
};
It's constructor is just
Device::Device(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx){
this->Sender = Hardware(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx);
}
And after that all I have the main control class
class DeviceArray{
private:
Device Devices[DEVICE_QUANTITY];
Byte Parameters_Buff[DEVICE_QUANTITY];
public:
DeviceArray();
DeviceArray(GPIO_Port** Ports, GPIO_Pin* Pins, SPI_HandleTypeDef* SPIx);
void SendParameters(Byte* Params);
Byte* GetParameters();
}
It's constructor is:
DeviceArray::DeviceArray(GPIO_Port** Ports, GPIO_Pin* Pins, SPI_HandleTypeDef* SPIx){
for(uint8_t i = 0;i < DEVICE_QUANTITY; i++){
this->Devices[i] = Device(Ports[i], Pins[i],SPIx);
}
}
I'll have only one object of this class in my program and it will be global.
And I wonder if instances of Device and their parameters will not be deleted after DeviceArray constructor is closed. And the same is for Hardware (Sender) instances.
The given code is quite abstract, but it is very similar to program I'm trying to make.
|
And I wonder if instances of Device and their parameters will not be deleted after DeviceArray constructor is closed. And the same is for Hardware (Sender) instances.
Yes, instances of the two types will be destroyed, but that doesn't matter.
For example the line
this->Devices[i] = Device(Ports[i], Pins[i],SPIx);
creates a temporary Device object which will be destroyed at the end of the statement, but that doesn't matter because before that = will call the implicit move assignment operator of Device which will move the members of the temporary Device object into the this->Devices[i] object.
|
71,204,006 | 71,217,473 | dll loacation Error by running a testcode | I am learning how to use dlls and how to export them. I have created a small program that calls the different components(classes, methods, functions, ect.. ) of my dll file to use them. When I build the project I get no problem, but when I compile the test code I get this error.
Error translation: {The procedure entry point "?Start@K_WrapperTeigha_DXF_DWG@@QAEXXZ" was not found in the DLL "C:\Users\zboussaid\source\repos\WrapperTester\Debug"}.
The image shows that the start method, which is a function in my DLL file, cannot be found in the path where my test code is located. I have tried to configure my properties as shown in this drescription, but as I said, I get this error. I will be very grateful if you can help me
class definition:
extern "C" class KWRAPPERTEIG_API K_WrapperTeigha_DXF_DWG
{
private:
//create Data base
OdDbDatabase* pDb;
//tables
OdDbLinetypeTablePtr w_kOdLinetypeTablePtr;
OdDbLayerTablePtr w_kOdLayerTablePtr;
OdDbTextStyleTablePtr w_kOdTextStyleTablePtr;
OdDbBlockTablePtr w_kOdBlockTablePtr;
OdDbBlockTableRecordPtr w_kOdModelSpaceBlockRecPtr;
//OdDbTextStyleTableRecordPtr pTextStyle;
public:
OdDb::DwgVersion m_OdDwgVersion; // Dwg/Dxf Version
OdDb::SaveType m_OdSaveType; // DWG oder DXF
public:
K_WrapperTeigha_DXF_DWG();
~K_WrapperTeigha_DXF_DWG();
void Start();
}
macros:
#ifdef KWRAPPERTEIG_EXPORTS
#define KWRAPPERTEIG_API __declspec(dllexport)
#ifndef KWRAPPERTEIG__DLL
#define KWRAPPERTEIG__DLL
#endif
#else
#define KWRAPPERTEIG_API __declspec(dllimport)
#endif
| @YujianYao-MSFT & Kiner_shah I really appreciate your help. I have solved the problem. My problem was that I created the dll file on Friday and then got the idea to change the location of creating the dll file and forgot about it. Then on Monday I copied the old file which does not contain my start() method. So the problem was the wrong parameterization of the dll file setting.
|
71,204,200 | 71,205,459 | std::cout print all digits of float value | I have this function:
template<typename T> // T can be float, double or long double
void printAllDigits(T value)
{
std::cout << std::fixed << std::setprecision(999) << value;
}
It's a dumb implementation to print all digits of a floating point value.
This has some problems:
I can't guarantee that it works for all float types. It seems to work for float (999 digits is probably enough), and maybe works for double, but certainly does not work for long double (std::numeric_limits<long double>::min() is printed as "0.", followed by 999 zeros).
It is extremely wasteful, because e.g. for float it always prints a ton of trailing zeros, even though those can never be non-zero.
But it does some things right:
I never want scientific notation, so std::fixed makes sense.
I have code that strips the trailing zeros (akin to what is sugessted in Remove trailing zero in C++), which works well with this approach.
I don't have to write down separate code paths or constants for the different float types.
If the argument to setprecision is large enough, this actually prints all digits without rounding.
I can copy the output, plonk it back into a code file (and make sure to add ".0f" and such where necessary) and get the same floating point value.
"Unnecessary" digits are not rounded away. printAllDigits(0.1f) prints "0.100000001490116119384765625000000...". Printing "0.1" would be sufficient to get back to the original float value, but I still need the function to print all of those digits.
How can I make that function less wasteful while maintaining my requirements?
std::numeric_limits<T>::max_digits10 is incorrect, since it is too small! std::numeric_limits<float>::min() gets printed as "0.000000000" instead of "0.0000000000000000000000000000000000000117549435082228750796873653722224567781866555677208752150875170627841725945472717285156250000000..."
| Assuming that the implementation uses radix 2 for the floating point,
if (std::numeric_limits<T>::radix == 2)
then writing ALL the decimal digits for ALL possible values would require:
std::cout << std::setprecision(std::numeric_limits<T>::digits - std::numeric_limits<T>::min_exponent);
I suspect that the formulation would be the same for radix == 10, but I cannot check this (no implementation at hand).
I wonder why you want to print all the decimals. If it's just to reconstruct the value unchanged, this is not necessary. Using a mixture of scientific notation with a precision std::numeric_limits<T>::max_digits10 should do the job. Otherwise, there are well known algorithm to print just enough decimal digits. They are used in the main REPL languages (see python repr, or how java, javascript, some Smalltalk, etc... print the floating point values), unfortunately, they are not part of a standard C++ library AFAIK.
|
71,204,325 | 71,205,326 | How to assign variadic/variable arguments in C++ | I'm trying to create a function to assign default or input values to several (scalar) parameters using variadic/variable input arguments as:
void set_params(const vector<double> &input, int n, ...) {
va_list args;
va_start (args, n);
for (int i = 0; i < n; i++) {
if (i < input.size()) {
va_arg(args, int) = input[i];
}
}
va_end(args);
}
int a = 1, b = 2, c = 3;
set_params({10, 20}, 3, a, b, c);
However, I'm getting the error on the assignment va_arg(args, int) = input[i]. Is it possible somehow to do assignment with variable arguments, or is there a better way to achieve this?
| Instead of using C's va_ stuff, C++ has it's own variadic template arguments, which you should preferably use
I'm no expert on this, but it could look a little bit like
#include <vector>
#include <iostream>
template <typename... Arg>
void set_params(const std::vector<double> &input, Arg&... arg) {
unsigned int i{0};
(
[&] {
if (i < size(input)) {
arg = input[i++];
}
}(), // immediately invoked lambda/closure object
...); // C++17 fold expression
}
int main() {
int a = 1, b = 2, c = 3;
set_params({10, 20}, a, b, c);
std::cout
<< a << ' '
<< b << ' '
<< c << '\n';
}
|
71,204,468 | 71,204,817 | Problem with BME280 and char arrays on Arduino | I am trying to fill a char array with 1800 characters from digital pin 7 (data from a rain gauge) before reading the air pressure from a BME280 using Ardino UNO. The results are printed with Serial.println over USB.
#include <Adafruit_BME280.h>
#define DATA 7
Adafruit_BME280 bme;
void setup()
{
Serial.begin(9600);
bme.begin(0x76);
pinMode(DATA, INPUT);
}
void loop()
{
int rmax = 1800; //1460
char r[rmax+1]; // changed from r[rmax]
int i;
for (i = 0; i < rmax; i++)
{
if (digitalRead(DATA) == 1)
r[i] = '1';
else
r[i] = '0';
}
r[rmax] = '\0';
Serial.println(r);
Serial.println(bme.readPressure());
delay(1000);
}
If the size of the array is greater than 1460, the data is not read from BME280, and array is printed without lineshift.
Can anybody tell me why, and what can be done to get succeeded if the size of the array is 1800?
| Looks like you have a stack overflow problem.
As you can see in ATMega328 datasheet here or here, you have 2KB RAM only. ATMega328/ATMega328P is usually used as a base MCU for the Arduino UNO board.
To check that, you can make array char r[rmax]; as static & fix the buffer overflow problem, as Ian told.
Here you can find your code with fixes:
// ...
// you previous code here
// NOTE: next row was added
#define rmax 1800
void loop()
{
// NOTE: next row was changed
static char r[rmax + 1];
int i;
for (i = 0; i < rmax; i++)
{
if (digitalRead(DATA) == 1)
r[i] = '1';
else
r[i] = '0';
}
r[rmax] = '\0';
Serial.println(r);
Serial.println(bme.readPressure());
delay(1000);
}
If you have problems with code compiling, you have a stack overflow problem (RAM ends).
|
71,205,603 | 71,205,727 | int abs(int) vs double abs(double) | I'd like to understand the behavior of the following code, from the C++ Standard point of view (GCC 9.3, C++20):
#include <cstdlib>
template<class> struct type_tester;
int main() {
type_tester<decltype(abs(0.1))>{}; // int abs(int) overload is selected for some reason!
type_tester<decltype(std::abs(0.1))> {}; // double abs(double) overload is selected, as one would expect
}
So, int abs(int) is imported to the global namespace, while double abs(double) is not!
Why?
|
So, int abs(int) is imported to the global namespace,
Why?
Because the C++ standard allows it to be imported into the global namespace.
While double abs(double) is not!
Why?
Because the C++ standard doesn't require it to be imported into the global namespace.
Relevant standard quotes:
[headers]
Except as noted in [library] through [thread] and [depr], the contents of each header cname is the same as that of the corresponding header name.h as specified in the C standard library.
In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope of the namespace std.
It is unspecified whether these names (including any overloads added in [support] through [thread] and [depr]) are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations ([namespace.udecl]).
Evidently, the C++ standard library implementation that you use had chosen to use the strategy described in the last paragraph of the quoted rule for the C standard library function, while having chosen not to use that strategy for the C++ standard library overloads. This specific outcome isn't guaranteed by the standard but it is conforming.
Another possible outcome would be that abs(0.1) would fail as use of an undeclared identifier. You cannot rely on C++ standard library names to be declared in the global namespace (unless you use the deprecated <name.h> C standard headers).
|
71,205,695 | 71,207,949 | is lambda capture allowed in c++20 function trailing return type and noexcept operator? | Simple code as below or godbolt has different results from gcc, clang and Visual Studio.
auto foo1(int n) -> decltype(([n]() { return n+1; }()))
// gcc error: use of parameter outside function body before '+' token
{
return [n]() { return n+1; }();
}
auto foo2(int n) -> decltype(([&n]() { return n+1; }()))
// gcc error: use of parameter outside function body before '+' token
{
return [&n]() { return n+1; }();
}
auto foo3(int n) -> decltype(([&]() { return n+1; }()))
// gcc error: use of parameter outside function body before '+' token
// gcc and clang error: non-local lambda expression cannot have a capture-default
// VS2022 17.1 warning C5253: a non-local lambda cannot have a capture default
{
return [&]() { return n+1; }();
}
It seems that gcc does not allow any type of capture if the lambda is in function trailing return type (or noexcept(noexcept(...))). clang is OK with capture by value and capture by reference but not OK with capture default. Visual Studio up to 17.0 allows any type of capture. Visual Studio 17.1 gives a warning for capture default.
What is the correct behavior here? It seems gcc, clang and latest VS 17.1 all agree capture default is not allowed in trailing return type (or noexcept(noexcept(...))). But is it a correct design? It is very convenient to put the same expression in return statement, noexcept and trailing return type (often by a macro) if the function is one-liner. But it is not possible now if there is a lambda with capture (default?) in this expression.
| From [expr.prim.lambda.capture]/3:
A lambda-expression shall not have a capture-default or simple-capture in its lambda-introducer unless its innermost enclosing scope is a block scope ([basic.scope.block]) or it appears within a default member initializer and its innermost enclosing scope is the corresponding class scope ([basic.scope.class]).
Which means that captures such as [n], [&n] or [&] are not allowed in trailing return types or noexcept specifiers, but initialized captures such as [i = 1] are.
So GCC is right to reject the first two function definitions and GCC and Clang are right to reject the last one.
|
71,206,859 | 71,207,894 | Handling enum value 0 in protobuf c++ | I'm working on a C++17 project that uses protobuf for data serialization, but I come across a problem.
I tried to serialize an object defined in protobuf into std::string and the object has only one enum field, when accidentally the value of the field is set to 0, the function SerializeAsString() or SerializToString(std::string*) will return true but I always get an empty string.
I checked out google api reference but got nothing helpful, can any one help me? I wrote some code to illustrate the problem.
Suppose we want to define a kind of message in testProtobuf.proto
syntax = "proto3";
package pb;
message testPackage{
enum testEnums{
TEST_0=0;
TEST_1=1;
TEST_2=2;
}
testEnums enumValue=1;
}
I compile it using
protoc --cpp_out=./ testProtobuf.proto
And in testProtobuf.cpp we have:
#include<iostream>
#include<string>
#include "testProtobuf.pb.h"
int main(){
pb::testPackage t0,t1,t2;
t0.set_enumvalue(pb::testPackage::TEST_0);
t1.set_enumvalue(pb::testPackage::TEST_1);
t2.set_enumvalue(pb::testPackage::TEST_2);
std::cout<<t0.ShortDebugString()<<"\n"<<t1.ShortDebugString()<<"\n"<<t2.ShortDebugString()<<std::endl;
std::string temp;
std::cout<<"Success? "<<t0.SerializeToString(&temp)<<", Length: "<<temp.length()<<std::endl;
std::cout<<"Success? "<<t1.SerializeToString(&temp)<<", Length: "<<temp.length()<<std::endl;
std::cout<<"Success? "<<t2.SerializeToString(&temp)<<", Length: "<<temp.length()<<std::endl;
return 0;
}
Then we compile the files:
g++ testProtobuf.cpp testProtobuf.pb.cc -lprotobuf -lpthread -o test.exe
When running the executable, it prints out these with the first line left blank:
enumValue: TEST_1
enumValue: TEST_2
Success? 1, Length: 0
Success? 1, Length: 2
Success? 1, Length: 2
I doubt this has something to do with '\0', but I don't have a better idea to make it work.
Even SerializeToArray() returns true and leave the buffer I passed in untouched. All I need is to get the serialized form of the object. Can any one help me? Great thanks!!
The version of protoc is 3.6.1, the version of g++ is 9.3.0, and the host system is Ubuntu 20.04.3
| This is actually not a problem at all since the parsing will work as expected because this is part of how protobuf handles default values:
Also note that if a scalar message field is set to its default, the value will not be serialized on the wire.
So because protobuf does not differentiate between a field being set to its default value and a field not being set at all, it simply does not serialize default values and your string is empty in this case.
Also this does not apply for enums alone but for all scalar types:
message testPackage2 {
int32 intValue=1;
}
pb::testPackage2 in, out;
out.set_intvalue(0);
std::cout << "Success? " <<out.SerializeToString(&temp)<< ", Length: " << temp.length() << std::endl;
in.ParseFromString(temp);
std::cout<<"Parsed: " << in.intvalue() << std::endl;
will also result in an empty serialized string but still gets correctly parsed:
Success? 1, Length: 0
Parsed: 0
|
71,206,958 | 71,214,200 | Why wouldn't boost::icl::interval_map add up the value? | Consider the following program:
#include <iostream>
#include <boost/icl/interval_map.hpp>
struct Value
{
explicit Value(int v) : v(v), is_empty(false) {}
Value() : v(0), is_empty(true) {}
Value& operator+=(const Value& other)
{
v += other.v;
return *this;
}
bool operator==(const Value& other) const { return is_empty == other.is_empty; }
bool operator!=(const Value& other) const { return is_empty != other.is_empty; }
int v;
bool is_empty;
};
int main()
{
boost::icl::interval_map<int, Value> m;
m.add(std::make_pair(boost::icl::interval<int>::right_open(10, 20), Value(2)));
m.add(std::make_pair(boost::icl::interval<int>::right_open(15, 30), Value(3)));
std::cout << m.iterative_size() << '\n';
std::cout << m.begin()->first.lower() << '\n';
std::cout << m.begin()->first.upper() << '\n';
std::cout << m.begin()->second.v << '\n';
}
The output is
1
10
30
2
Questons:
Why is the last line 2?
Isn't the interval map expected to add up the value, so that it is 5?
How to achieve the behavior that intervals are added and the value from += is preserved?
I want the following results:
{([10,20)->(2))+
([15,30)->(3))+
([40,50)->(11))}
=
{([10,30)->(5))([40,50)->(11))}
That is, when intervals are added, they are merged, and the combined value is stored for entire merged interval.
There's may be no math sense in this operation, but this is what I need in my program. (Also, I don't to subtract intervals).
| The problem is that
bool operator==(const Value& other) const { return is_empty == other.is_empty; }
bool operator!=(const Value& other) const { return is_empty != other.is_empty; }
make it so that ANY value is "identical". That makes the behaviour unspecified, and likely ends up merging any touching intervals and keeping the previous value (because it was "equal" according to your own operator==).
Let's have C++ generate a more correct comparison:
struct Value {
explicit Value(int v) : value(v) {}
Value() : is_empty(true) {}
Value& operator+=(const Value& other) { value += other.value; return *this; }
auto operator<=>(Value const&) const = default;
bool is_empty = false;
int value = 0;
};
Now you can Live On Compiler Explorer
#include <iostream>
#include <boost/icl/interval_map.hpp>
int main()
{
namespace icl = boost::icl;
using I = icl::interval<int>;
using Value = int;
auto const a = std::make_pair(I::right_open(10, 20), Value(2));
auto const b = std::make_pair(I::right_open(15, 30), Value(3));
auto const c = std::make_pair(I::right_open(40, 50), Value(11));
icl::interval_map<int, Value> m;
m.add(a);
m.add(b);
m.add(c);
std::cout << m << "\n";
m.subtract(a);
std::cout << m << "\n";
}
Printing
{([10,15)->(2))([15,20)->(5))([20,30)->(3))([40,50)->(11))}
However, I'm struggling to understand what Value adds over optional<int> which, in fact is already the behaviour of the interval_map anyways:
int main()
{
namespace icl = boost::icl;
using I = icl::interval<int>;
auto const a = std::make_pair(I::right_open(10, 20), 2);
auto const b = std::make_pair(I::right_open(15, 30), 3);
auto const c = std::make_pair(I::right_open(40, 50), 11);
icl::interval_map<int, int> m;
m.add(a);
m.add(b);
m.add(c);
std::cout << m << "\n";
m.subtract(a);
std::cout << m << "\n";
}
Prints:
{([10,15)->2)([15,20)->5)([20,30)->3)([40,50)->11)}
{([15,30)->3)([40,50)->11)}
In fact, in some respects, your custom Value take seems "wrong" to me, evem with the fixed comparison:
Live On Compiler Explorer
#include <iostream>
#include <boost/icl/interval_map.hpp>
struct Value {
explicit Value(int v) : value(v) {}
Value() : is_empty(true) {}
Value& operator+=(const Value& other) { value += other.value; return *this; }
Value& operator-=(const Value& other) { value -= other.value; return *this; }
auto operator<=>(Value const&) const = default;
bool is_empty = false;
int value = 0;
friend std::ostream& operator<<(std::ostream& os, Value const& v) {
return v.is_empty ? os << "#EMPTY" : os << v.value;
}
};
int main()
{
namespace icl = boost::icl;
using I = icl::interval<int>;
auto const a = std::make_pair(I::right_open(10, 20), Value(2));
auto const b = std::make_pair(I::right_open(15, 30), Value(3));
auto const c = std::make_pair(I::right_open(40, 50), Value(11));
icl::interval_map<int, Value> m;
m.add(a);
m.add(b);
m.add(c);
std::cout << m << "\n";
m.subtract(a);
std::cout << m << "\n";
}
Printing
{([10,15)->2)([15,20)->5)([20,30)->3)([40,50)->11)}
{([10,15)->0)([15,30)->3)([40,50)->11)}
Is [10,15)->0 really intended, desired?
|
71,207,162 | 71,236,083 | Intercepting signals/mach exceptions in a C++ plugin on macOS | I'm working on a suite of plugins for a certain host application, targeting both Windows and Mac (OSX+). The plugins are written in C++. I would like to add crash & exception report handling to them in case the plugin goes rogue. This in order to not bring the whole host app down in case the plugin misbehaves, but get some feedback instead and just skip that one plugin call (and making follow-up plugin calls a sort of no-op). Think logging some state and slapping an error code + text on it. From then on the plugin switches into an error state where requesting details returns this state.
This is a big legacy code base which has been improved greatly over time, but there are still some rough edges here and there, so answers like "just don't crash" is not what I'm looking for :) It also doesn't help I'm much more of a Windows developer than a macOS developer, so I might have overlooked something completely obvious.
I've covered unhandled C++ exceptions in a cross-platform way by wrapping each host->plugin callback in a big C++ try/catch block right at the plugin entry points.
I'm also handling crashes, div-by-zero, access violations etc. for Windows at that same spot by using __try/__except and registering a SEH handler.
Now I want to do the latter as well for Mac. But here I'm struggling with finding out what my options are, if any.
I looked into signal handlers, but what I glean from that is that they are process-wide. I.e.: not plugin-friendly, especially when multiple of these plugins can be used by the host concurrently (who will catch and thus handle the signals first?). And the host app already has it's own crash handler, possibly using a signal handler, so installing our own would make it a fight over who's in charge I think? Plus that my reporting options are extremely limited in such handlers; if possible I'd like to have a bit more freedom here (like using std::strings with the new/delete they imply).
Then there's also Mach exception handling. But I totally fail to get informative results when googling this in combination with 'plugin'...
Does anyone have any advice on what route to go, or which option is better in my situation?
| The only options on macOS are signal handlers and Mach exception handlers.
Both of these mechanisms are process-wide, so would report problems wherever they occurred.
If a new signal handler is installed, the old one will not be run. The sigaction() API does return the previously installed one, so it's possible to have it run as well as your new one. Then again another signal handler might get installed and replace yours.
There's a very useful post here that goes into detail about implementing a signal handler - https://developer.apple.com/forums/thread/113742
The situation with Mach exception handlers is pretty much the same, calling task_set_exception_ports() will override the previously set handlers, so these have to be restored once your new handler has run if you want to propagate the exception. One big advantage of Mach exception handlers is that they can be run in a separate process, in which you're free to use std::strings etc. at the expense of it being more difficult to examine the crashed process's state.
There is little documentation around Mach exception handling, the best references are the various open-source crash reporting frameworks.
Overall it's difficult to properly implement crash detection, and I'd advise against doing it in a plugin. It's a LOT more complicated than SEH.
|
71,207,351 | 71,207,707 | Is it required to define all forward declarations? | In general, I'm wondering if a program like this, containing a forward-declaration of a class that is never defined, is technically well-formed?
class X;
int main() {}
More specifically, I'm wondering if having a pattern like this
// lib.h
#pragma once
struct X {
private:
friend class F;
};
is safe to write if lib.h belongs to a shared library that does not contain a definition of the class F, nor does it depend on another shared library that does.
Is it possible that someone using the header file ends up with a reference to symbol F that may cause a linker error when loading the shared library?
| According to the standard [basic.odr.def]:
Every program shall contain exactly one definition of every non-inline
function or variable that is odr-used in that program outside of a
discarded statement (8.5.1);
The key part is odr-used, which is determined by all the other places in code that may make use of the function. If it is not named in any (potentially evaluated) expression, it is not odr-used and does not need to have a definition.
Further:
A function is named by an expression or conversion if it is the unique
result of a name lookup or the selected member of a set of overloaded
functions (6.5, 12.4, 12.5) in an overload resolution performed as
part of forming that expression or conversion, unless it is a pure
virtual function and either the expression is not an id-expression
naming the function with an explicitly qualified name or the
expression forms a pointer to member (7.6.2.1).
Declaring function does not require it to be defined. Calling it, taking its address, or any other expression that needs to know the location of the function (to take its address or make a call to it) requires that the function exist, or the linker won't be able to link those uses to the definitions. If there are no uses, there is no dependency on those symbols.
Similarly, for classes, the same kind of reasoning applies. Again, from the standard:
A definition of a class is required to be reachable in every context
in which the class is used in a way that requires the class type to be
complete.
[Example: The following complete translation unit is well-formed,
even though it never defines X:
struct X; // declare X as a struct type
struct X* x1; // use X in pointer formation
X* x2; // use X in pointer formation
— end example]
And for completeness, the reasons the standard gives for when a class type T is required to be complete:
an object of type T is defined
a non-static class data member of type T is declared
T is used as the allocated type or array element type in a new-expression
an lvalue-to-rvalue conversion is applied to a glvalue referring to an object of type T
an expression is converted (either implicitly or explicitly) to type T
an expression that is not a null pointer constant, and has type other than cv void*, is converted to the type pointer to T or reference to T using a standard conversion, a dynamic_cast, or a
static_cast
a class member access operator is applied to an expression of type T
the typeid operator or the sizeof operator is applied to an operand of type T
a function with a return type or argument type of type T is defined or called
a class with a base class of type T is defined
an lvalue of type T is assigned to
the type T is the subject of an alignof expression
an exception-declaration has type T, reference to T, or pointer to T
|
71,207,477 | 71,207,503 | What does this header mean in c++? | #if defined(UNICODE) && !defined(_UNICODE)
#define _UNICODE
#elif defined(_UNICODE) && !defined(UNICODE)
#define UNICODE
#endif
this is the header for the default win32 c++ app on codeblocks
| It ensures that both UNICODE and _UNICODE are defined if one of them is.
|
71,207,967 | 71,208,303 | Arduino sketch with header and code file added with template methods. Caught between 'undefined reference to' and 'redefinition of' | I have a header file declaring a method, and a code file with the implementation. On compile, the compiler errors out with 'undefined reference to...'. If I copy the implementation of the method to the header, it then tells me the method is being redefined in the code file. Surely if it can find the method in the cpp file to call a duplicate, then it can use it. Since it can't be found, adding it to the header shouldn't cause a redefinition.
All headers are protected. In the code below, if I uncomment the header implementation, the method is redefined, if I leave it commented, the method is undefined. If I use only the header implementation, everything compiles fine but is bad architecture. The cpp file is being correctly copied to the output folder. Example code:
test.ino
math.h
math.cpp
test.ino
#include "math.h"
void setup() {
int result = Math::Double((int)2);
}
void loop() {}
math.h
#ifndef MATH_H
#define MATH_H
namespace Math {
template <typename U>
U Double(U value);
// template <typename U>
// U Interpolate(U value) {
// return value * 2;
// }
}
#endif
math.cpp
#include "math.h"
template <typename U>
U Math::Double(U value) {
return value * 2;
}
| You have a few C++ syntax errors in your code.
Templates have to be declared and defined inside header files (there is rare syntax that provides an exception to this, but I won't discuss that here).
You are missing parentheses before your 'loop' function definition.
You are declaring your Double parameter with the name "value" but then attempting to use it with the name "result"
Here's the corrected code:
EDIT Changed this to separate template declarations/definitions. The original answer will be below the row of asterisks after this revised answer.
math.h
#ifndef MATH_H
#define MATH_H
namespace Math {
template <typename U>
U Double(U value);
}
#include "math_ipp.h"
#endif
math_ipp.h
#ifndef MATHIPP_H
#define MATHIPP_H
#include "math.h"
namespace Math {
template <typename U>
U Double(U value) {
return value * 2;
}
}
#endif
test.ino
#include "math.h"
void setup() {
int result = Math::Double((int)2);
}
void loop() {}
********** ORIGINAL ANSWER BELOW
math.h
#ifndef MATH_H
#define MATH_H
namespace Math {
template <typename U>
U Double(U value) {
return value * 2;
}
}
#endif
test.ino
#include "math.h"
void setup() {
int result = Math::Double((int)2);
}
void loop() {}
|
71,208,273 | 71,208,464 | Dereference pointer from unnamed namespace not working | For a Wii homebrew game engine I'm working on, I have this (shortened) script that handles printing text:
#include <grrlib.h>
#include "graphics.hpp"
#include "Vera_ttf.h"
namespace {
GRRLIB_ttfFont *font = GRRLIB_LoadTTF(Vera_ttf, Vera_ttf_size);
}
namespace graphics {
namespace module {
void print(const char *str, int x, int y) {
GRRLIB_PrintfTTF(x, y, font, str, 12, 0xFFFFFFFF);
}
} // module
} // graphics
This code compiles, however, when trying to call the print function above, nothing is rendered. Weirdly enough, removing the unnamed namespace and changing the print function to this:
void print(const char *str, int x, int y) {
static GRRLIB_ttfFont *font = GRRLIB_LoadTTF(Vera_ttf, Vera_ttf_size);
GRRLIB_PrintfTTF(x, y, font, str, 12, 0xFFFFFFFF);
}
works fine. However, I would like the font variable to be changeable by another setFont function. How can I achieve this?
Here's is the GRRLIB_PrintfTTF function code if anyone needs it: https://github.com/GRRLIB/GRRLIB/blob/master/GRRLIB/GRRLIB/GRRLIB_ttf.c
| Since you have to initialize the library with GRRLIB_Init(), you can provide a similar init function to ensure that your variables are initialized after the library.
#include <grrlib.h>
#include "graphics.hpp"
#include "Vera_ttf.h"
namespace {
GRRLIB_ttfFont *font = NULL;
}
namespace graphics {
void InitGraphics() {
font = GRRLIB_LoadTTF(Vera_ttf, Vera_ttf_size);
}
namespace module {
void print(const char *str, int x, int y) {
GRRLIB_PrintfTTF(x, y, font, str, 12, 0xFFFFFFFF);
}
} // module
} // graphics
Call graphics::InitGraphics() after you call GRRLIB_Init()
|
71,208,777 | 71,209,144 | Why am I getting an undefined reference error while using separate .cpp and .h files for a class? | I am using a simple function to add to integers, the class is declared in the Adder.h file as below
class Adder
{
public:
int add (int x, int y);
};
Then I have the Adder.cpp file which has the function definition
int add (int x, int y)
{
return x + y;
}
Then the main.cpp file which calls the function
# include "Adder.h"
# include <iostream>
using namespace std;
int main()
{
Adder adder1;
int result = adder1.add (2, 3);
cout << result;
}
I ran g++ -c Adder.cpp to create Adder.o file beforehand.
Then I ran g++ main.cpp but go the following error
main.cpp:(.text+0x2d): undefined reference to `Adder::add(int, int)'
Where am I going wrong?
| In your second and final step, you didn't instruct the compiler (linker more exactly) to take into account Adder.o, so your final executable still doesn't know the implementation of Adder::add
Try, after getting Adder.o, to run g++ main.cpp Adder.o
Also, this may be relevant : Difference between compiling with object and source files
Also, if that is the complete code, as others have pointed out, in the Adder.cpp, you are just defining a simple function, not the one from the Adder class.
|
71,208,820 | 71,212,872 | C++ polymorphism: how to create derived class objects | I have an abstract base class called BaseStrategy. It contains one pure virtual function calculateEfficiency(). There are two classes ConvolutionStrategy and MaxPoolStrategy which derive from this base class and implement their own specific version of calculateEfficiency().
Here is some code:
class BaseStrategy {
public:
explicit BaseStrategy();
virtual ~BaseStrategy() = default;
private:
virtual double calculateEfficiency(mlir::Operation* op) = 0;
};
class ConvolutionStrategy : public BaseStrategy {
private:
double calculateEfficiency(mlir::Operation* op)
{
//some formula for convolution
return 1;
}
};
class MaxPoolStrategy : public BaseStrategy {
private:
double calculateEfficiency(mlir::Operation* op)
{
//some formula for MaxPool
return 1;
}
};
Now I have another class called StrategyAssigner. It has method calculateAllLayerEfficiencies() whose purpose is to iterate over all layers in a network. Depending on the type of layer there is a switch statement and should call the correct calculateEfficiency() depending on the layer type.
class StrategyAssigner final {
public:
explicit StrategyAssigner(){};
public:
void calculateAllLayerEfficiencies() {
// Logic to iterate over all layers in
// a network
switch (layerType) {
case Convolution:
// Call calculateEfficiency() for Convolution
break;
case MaxPool:
// Call calculateEfficiency() for MaxPool
break;
}
};
}
int main ()
{
StrategyAssigner assigner;
assigner.calculateAllLayerEfficiencies();
}
My question is, should I store references of objects Convolution and MaxPool in the class StrategyAssigner so that I can call the respective calculateEfficiency().
Or could you suggest a better way to call calculateEfficiency(). I don't really know how to create the objects (stupid as that sounds).
I can't make calculateEfficiency() static as I need them to be virtual so that each derived class can implemented its own formula.
| You can indeed use runtime polymorphism here:
Declare ~BaseStrategy virtual (you are already doing it ;-)
If you are never going to instantiate a BaseStrategy, declare one of its methods as virtual pure, e.g. calculateEfficiency (you are already doing it as well!). I would make that method const, since it doesn't look it's going to modify the instance. And it will need to be public, because it will need to be accessed from StrategyAnalyser.
Declare calculateEfficiency as virtual and override in each of the subclasses. It could also be final if you don't want subclasses to override it.
I'd keep a std::vector of smart pointers to BaseStrategy at StrategyAssigner. You can use unique_ptrs if you think this class is not going to be sharing those pointers.
The key point now is that you create heap instances of the subclasses and assign them to a pointer of the base class.
class StrategyAssigner final {
public:
void addStrategy(std::unique_ptr<BaseStrategy> s) {
strategies_.push_back(std::move(s));
}
private:
std::vector<std::unique_ptr<BaseStrategy>> strategies_{};
};
int main()
{
StrategyAssigner assigner;
assigner.addStrategy(std::make_unique<ConvolutionStrategy>());
}
Then, when you call calculateEfficiency using any of those pointers to BaseStrategy, the runtime polymorphism will kick in and it will be the method for the subclass the one that will be actually called.
class ConvolutionStrategy : public BaseStrategy {
private:
virtual double calculateEfficiency() const override {
std::cout << "ConvolutionStrategy::calculateEfficiency()\n";
return 10;
}
};
class MaxPoolStrategy : public BaseStrategy {
private:
virtual double calculateEfficiency() const override {
std::cout << "MaxPoolStrategy::calculateEfficiency()\n";
return 20;
}
};
class StrategyAssigner final {
public:
void calculateAllLayerEfficiencies() {
auto sum = std::accumulate(std::cbegin(strategies_), std::cend(strategies_), 0,
[](auto total, const auto& strategy_up) {
return total + strategy_up->calculateEfficiency(); });
std::cout << "Sum of all efficiencies: " << sum << "\n";
};
};
int main()
{
StrategyAssigner assigner;
assigner.addStrategy(std::make_unique<ConvolutionStrategy>());
assigner.addStrategy(std::make_unique<MaxPoolStrategy>());
assigner.calculateAllLayerEfficiencies();
}
// Outputs:
//
// ConvolutionStrategy::calculateEfficiency()
// MaxPoolStrategy::calculateEfficiency()
// Sum of all efficiencies: 30
[Demo]
|
71,209,541 | 71,209,823 | QtConcurrent error: attempting to reference a deleted function | I'd like to run simple method in a different thread than the GUI thread inside my Qt application. To do this I'm using QFuture and Qt Concurrent. However, I ran into a compile error:
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent/qtconcurrentstoredfunctioncall.h(58): error C2280: 'QtConcurrent::RunFunctionTask<T>::RunFunctionTask(void)': attempting to reference a deleted function
with
[
T=Error
]
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent/qtconcurrentrunbase.h(121): note: compiler has generated 'QtConcurrent::RunFunctionTask<T>::RunFunctionTask' here
with
[
T=Error
]
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent/qtconcurrentrunbase.h(121): note: 'QtConcurrent::RunFunctionTask<T>::RunFunctionTask(void)': function was implicitly deleted because a data member 'QtConcurrent::RunFunctionTask<T>::result' has either no appropriate default constructor or overload resolution was ambiguous
with
[
T=Error
]
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent/qtconcurrentrunbase.h(120): note: see declaration of 'QtConcurrent::RunFunctionTask<T>::result'
with
[
T=Error
]
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent/qtconcurrentstoredfunctioncall.h(58): note: while compiling class template member function 'QtConcurrent::StoredFunctorCall0<T,T (__cdecl *)(void)>::StoredFunctorCall0(FunctionPointer)'
with
[
T=Error,
FunctionPointer=Error (__cdecl *)(void)
]
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent\qtconcurrentrun.h(74): note: see reference to function template instantiation 'QtConcurrent::StoredFunctorCall0<T,T (__cdecl *)(void)>::StoredFunctorCall0(FunctionPointer)' being compiled
with
[
T=Error,
FunctionPointer=Error (__cdecl *)(void)
]
C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent\qtconcurrentrun.h(74): note: see reference to class template instantiation 'QtConcurrent::StoredFunctorCall0<T,T (__cdecl *)(void)>' being compiled
with
[
T=Error
]
C:\Users\dalji\Documents\Dev\TestQtConcurrent\main.cpp(37): note: see reference to function template instantiation 'QFuture<Error> QtConcurrent::run<Error>(T (__cdecl *)(void))' being compiled
with
[
T=Error
]
ninja: build stopped: subcommand failed.
16:14:59: The process "C:\Qt\Tools\CMake_64\bin\cmake.exe" exited with code 1.
Error while building/deploying project TestQtConcurrent (kit: Desktop Qt 5.15.2 MSVC2019 64bit)
When executing step "Build"
Here is a simple test application that reproduces the issue I'm having
#include <QCoreApplication>
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
class Error
{
public:
enum class ErrorType {
NoError,
FileSavingError,
FileLoadingError
};
Error(ErrorType errorType, const QString &errorMessage = "") :
m_errorType(errorType),
m_errorMessage(errorMessage)
{
}
const QString &errorMessage() const { return m_errorMessage; }
ErrorType errorType() const { return m_errorType; }
private:
ErrorType m_errorType;
QString m_errorMessage;
};
Error testMethod(){
return Error(Error::ErrorType::NoError, "No Error");
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFuture<Error> errorFuture = QtConcurrent::run(testMethod);
return a.exec();
}
What am I doing wrong?
| As noted in the comments, and as indicated in the error message itself, the problem is that your Error class has no default constructor.
While there is nothing explicit in the documentation for QtConcurrentRun that indicates this requirement, there is the following in the documentation for QFuture (bold emphasis mine)1:
QFuture allows threads to be synchronized against one or more results
which will be ready at a later point in time. The result can be of
any type that has a default constructor and a copy constructor. …
The simplest way to add the required default constructor to your Error class is to add a default value for the first argument (you already have one for the second argument) in your currently-defined constructor (I've assumed that the ErrorType::NoError enumeration is a sensible value for this default):
Error(ErrorType errorType = ErrorType::NoError, const QString& errorMessage = "") :
m_errorType(errorType),
m_errorMessage(errorMessage)
{
}
1 Note that, for your Error class, the (also required) copy constructor is implicitly declared and will be generated for you, by the compiler.
|
71,210,227 | 71,210,282 | Full emulation of `intptr_t` with `ptrdiff_t` and `nullptr`? | Given that intptr_t is optional and ptrdiff_t is mandatory, would p - nullptr be a good substitute for (intptr_t)p, to be converted back from a result denoted by n with nullptr + n instead of (decltype(p))n? It's IIUC semantically equivalent on implementations with intptr_t defined, but also works as intended otherwise.
If I'm right in the above, why does the standard allow not implementing intptr_t? It seems the liberty thus afforded isn't particularly valuable, just a set of two simple local source code transforms (or an optimized equivalent) to shave off.
| No. ptrdiff_t only needs to be large enough to encompass a single object, not the entire memory space. And (char*)p - (char*)nullptr causes undefined behavior if p is not itself a null pointer.
p - nullptr without the casts is ill-formed.
|
71,210,491 | 71,210,647 | C++ in containered Linux environment: why does attempting to allocate large vector causes SIGABRT or neverending loop instead of bad_alloc? | I am writing in C++ on a Windows machine in three environments:
Docker Linux container with Ubuntu - g++ compiler (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
WSL Ubuntu enviornment on Windows - g++ compiler (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Windows - gcc compiler (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0
I am working with enormous datasets and basically need to be able to break them down into as-large-as-possible chunks to manipulate in memory. To find the size of blocks, I imagined something like the following:
size_t findOptimalSize(long long beginningSize) {
long long currentSize = beginningSize;
while (currentSize > 0) {
try {
std::vector<double> v(currentSize);
return currentSize;
} catch (std::bad_alloc &ex) {
currentSize /= 10;
}
}
return 0;
}
int main() {
long long size(50000000000000);
try {
std::vector<double> v(size);
std::cout << "success" << std::endl;
} catch (std::bad_alloc &ex){
std::cout << "badAlloc" << std::endl;
}
size_t optimal = findOptimalSize(size);
std::cout << "optimal size: " + std::to_string(optimal);
return 0;
}
The above code behaves perfectly as expected in the Windows environment. In the two Linux environments, however, while it is always able to throw the first bad_alloc exception, it then either does one of two things:
Throws a SIGABRT with the following message:
new cannot satisfy memory request.
This does not necessarily mean you have run out of virtual memory.
It could be due to a stack violation caused by e.g. bad use of pointers or an out-of-date shared library
After a few iterations, seems to fall into an endless loop at the line std::vector<double> v(currentSize); (My best guess there is that it gets close to the amount of memory the Linux environment has available and it gets stuck waiting for that extra little bit of extra memory to be freed to satisfy my request)
Is there some way to accomplish what I'm attempting and sidestep these issues in the Linux environments? I'm guessing that the containers complicate matters and muddy up my simple allocation checks with their complex memory management logic.
How can I check whether I can allocate the memory in these circumstances?
| Containers don't have complex memory management logic. What you're seeing is a result of a surprising Linux policy known as memory overcommit.
In Linux large allocations do not fail; malloc() always succeeds. The memory isn't actually allocated until you actually attempt to use it. If the OS can't satisfy the need it invokes the OOM killer, killing processes until it frees up enough memory.
Why does this exist?
A Linux computer typically has a lot of heterogeneous processes running in different stages of their lifetimes. Statistically, at any point in time, they do not collectively need a mapping for every virtual page they have been assigned (or will be assigned later in the program run).
A strictly non-overcommitting scheme would create a static mapping from virtual address pages to physical RAM page frames at the moment the virtual pages are allocated. This would result in a system that can run far fewer programs concurrently, because a lot of RAM page frames would be reserved for nothing.
(source)
You might find this ridiculous. You wouldn't be alone. It's a highly controversial system. If your initial reaction is "this is stupid," I encourage you to read up on it and suspend judgment for a bit. Ultimately, whether you like overcommit or not, it's a fact of life that all Linux developers have to accept and deal with.
|
71,210,560 | 71,214,240 | Flattened Int array C++ (the ends of each integer is translated wrongly) | There is an array of integers, and I want to turn them into an array of separated digits and print them back out as the same sets of integers.
ps: reason being, I want to do lots of individual digit calculations, and I want to use this method to separate the digits, and store their "separating indexes" to turn them back to different integers afterward.
However, there is a problem, almost all the digits are translated correctly but some of them at each individual ends are wrong.
CODE:
#include <iostream>
using std::cout; using std::endl;
int* charArrToIntArray(char** input, int* sizeofnumbers, int sizeofarray) {
int* output = new int[100];
cout << input[0][0] << endl;
cout << sizeofnumbers[0] << endl;
cout << sizeofarray << endl;
for (int counter = 0; counter < sizeofarray; counter++) {
int i;
sscanf_s(input[counter], "%d", &i);
output[counter] = i;
}
return output;
}
int* intToIntArray(int input, int length) {
static int output[20];
for (int i = 0; i < length; i++) {
output[i] = input % 10;
input /= 10;
}
return output;
}
int main()
{
const int arraySize = 5;
int NumSize[arraySize] = { 6, 7, 5, 9, 8 };
int NumSizeFlatten[arraySize + 1] = { 0 };
static int IntArray[arraySize] = {345678, 6543210, 11101, 110010001, 00011100};
static int arr2D[500]; //The flat 2D array...
for (int counter = 0; counter < arraySize; counter++) {
int* arr1D = intToIntArray(IntArray[counter], NumSize[counter]);
for (int i = 0; i <= counter; i++) {
NumSizeFlatten[counter + 1] += NumSize[i]; //Get the values of positions of flattened array's separation points
}
for (int i = NumSize[counter] - 1; i >= 0; i--) {
printf("%d", arr1D[i]); //Directly Print from the arrays
}printf("\n");
for (int i = 0; i < NumSize[counter]; i++) {
arr2D[NumSizeFlatten[counter] + i - 1] = arr1D[NumSize[counter] - i]; //PUT arrays into a Flattened array //warning C6386: buffer overrun
}
}
for (int i = 0; i < 50; i++) {
printf("%d", arr2D[i]); //Directly print the Flattened array in a flattened from.
}
for (int j = 1; j <= arraySize; j++) {
printf("NumSizeFlatten[%d] = %d\n", j, NumSizeFlatten[j]); //Print the values of positions of flattened array's separation points
}
for (int i = 0; i < arraySize; i++) {
for (int j = NumSizeFlatten[i]; j < NumSizeFlatten[i + 1]; j++) {
//printf("%d.", j);
printf("%d", arr2D[j]); //Print From the Flattened Array
}printf("\n");
}
}
OUTPUT:
345678
6543210
11101
110010001
00004672
34567065432151110011001000100004670000000000000000NumSizeFlatten[1] = 6
NumSizeFlatten[2] = 13
NumSizeFlatten[3] = 18
NumSizeFlatten[4] = 27
NumSizeFlatten[5] = 35
345670
6543215
11100
110010001
00004670
and also the last integer is wrong.
I know this code is really trash, I am doing what I can...
| Can you use the STL data structures and algorithms?
Here's some code:
Starting from a vector of ints.
Creating a vector of strings from it.
Flattening the vector of strings into a vector of int digits.
Transforming the vector of strings back into a vector of ints.
[Demo]
#include <algorithm> // for_each, transform
#include <fmt/ranges.h>
#include <sstream> // ostringstream
#include <string> // to_string
#include <vector>
#include "range/v3/all.hpp"
int main()
{
// Ints
const std::vector<int> vi{345678, 6543210, 11101, 110010001, 00011100};
fmt::print("vi = {}\n", vi);
// Ints to strings
std::vector<std::string> vs{};
std::ranges::transform(vi, std::back_inserter(vs), [](int i) {
return std::to_string(i);
});
fmt::print("vs = {}\n", vs);
// Strings to flat ints
std::vector<int> flat_vi{};
std::ranges::for_each(vs, [&flat_vi](const auto& s) {
std::ranges::transform(s, std::back_inserter(flat_vi), [](unsigned char c){
return c - '0';
});
});
fmt::print("flat_vi = {}\n", flat_vi);
// Strings to flat ints (using ranges)
auto flat_vi_2 = vs
| ranges::view::join
| ranges::view::transform([](unsigned char c) { return c - '0'; })
| ranges::to_vector;
fmt::print("flat_vi_2 = {}\n", flat_vi_2);
// Strings back to ints
std::vector<int> vo{};
std::ranges::transform(vs, std::back_inserter(vo), [](const auto& s){
return std::atoi(s.c_str());
});
fmt::print("vo = {}\n", vo);
}
// Outputs:
//
// vi = [345678, 6543210, 11101, 110010001, 4672]
// vs = ["345678", "6543210", "11101", "110010001", "4672"]
// flat_vi = [3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 4, 6, 7, 2]
// flat_vi_2 = [3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 4, 6, 7, 2]
// vo = [345678, 6543210, 11101, 110010001, 4672]
Updating my answer after your comment.
You may still be able to do most of your work on data structures like std::vector and then, pass an array of int digits around.
This is quite a not recommended practice because you have to take care you don't modify the std::vector while other code is operating on its data. Otherwise, you would get undefined behaviour (basically, the modification may cause a relocation of the contents, so the pointer to those contents would no longer be valid).
Also, if you think of executing code in parallel, notice many of the STL algorithms already offer that capability. E.g. check std::transform's overloads using an ExecutionPolicy.
[Demo]
#include <span>
void operate_on_flat_vector_data(int* data, size_t size)
{
std::cout << "flat_vi.data() = [";
bool first{true};
for (size_t i{0}; i < size; ++i) {
std::cout << (first ? "" : ", ") << data[i];
first = false;
}
std::cout << "]\n";
}
void operate_on_flat_vector_data(std::span<const int> data)
{
std::cout << "flat_vi.data() = [";
bool first{true};
for (const int i : data) {
std::cout << (first ? "" : ", ") << i;
first = false;
}
std::cout << "]\n";
}
int main()
{
// Passing flat vector's data around
operate_on_flat_vector_data(flat_vi.data(), flat_vi.size());
// Passing flat vector's data around (using span)
operate_on_flat_vector_data({flat_vi.data(), flat_vi.size()});
}
|
71,210,999 | 71,211,943 | can't get the right answer when multiplying two large numbers using Karatsuba multiplication(recursive Gauss "trick") | I have been trying to implement integer-multiplication problems using strings. The product of smaller numbers is always right but for larger numbers the results are wrong.
Can anyone tell me which part of the code is causing the problem?
a: 3141592653589793238462643383279502884197169399375105820974944592
b: 2718281828459045235360287471352662497757247093699959574966967627
answer: 8539734222646569768352026223696548756537378365658178539814559622482948999279606844390394705148206869490910283679048366582723184
correct answer: 8539734222673567065463550869546574495034888535765114961879601127067743044893204848617875072216249073013374895871952806582723184
int getEquallength(string &a,string &b)
{
int n1=a.length();
int n2=b.length();
if(n1>n2)
{
for(int i=0;i<n1-n2;i++)
{
b='0'+b;
}
}
else if(n2>n1)
{
for(int i=0;i<n2-n1;i++)
{
a='0'+a;
}
}
return n1;
}
string addstrings(string a,string b)
{
int n=getEquallength(a,b);
n=a.length();
string result="";
int carry=0;
for(int i=n-1;i>=0;i--)
{
int f=a[i]-'0';
int s=b[i]-'0';
int sum=f+s+carry;
carry=sum/10;
sum=sum%10+'0';
result=char(sum)+result;
}
if(carry) result=char(carry+'0')+result;
return result;
}
string substract_str(string a,string b)
{
int n=getEquallength(a,b);
int carry=0;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
string result;
for(int i=0;i<a.length();i++)
{
int f=a[i]-'0';
int s=b[i]-'0';
int sub=0;
sub=f-s-carry;
if(sub<0)
{
sub+=10;
carry=1;
}
else
carry=0;
result=char(sub+'0')+result;
}
return result;
}
string karatsuba(string a,string b)
{
int n=getEquallength(a,b);
if(n==0) return "0";
if(n==1)
{
return to_string(atoi(a.c_str())*atoi(b.c_str()));
}
int fh=n/2;
int sh=n-n/2;
string Xl=a.substr(0,fh);
string Xr=a.substr(fh,sh);
string Yl=b.substr(0,fh);
string Yr=b.substr(fh,sh);
string P1=karatsuba(Xl,Yl);
string P2=karatsuba(Xr,Yr);
string res=addstrings(P1,P2);
string P3=karatsuba(addstrings(Xl,Xr),addstrings(Yl,Yr));// (Xl+Xr)*(Yl+Yr)
P3=substract_str(P3,res);//P3=Xl*Yr+Xr.Yl
for(int i=0;i<2*sh;i++)
{
P1.push_back('0');
}
for(int i=0;i<sh;i++)
{
P3.push_back('0');
}
P1= addstrings(P1,P2);
string result=addstrings(P1,P3);
return result;
}
| You have a simple error in getEqualLength. It should return a.length() or b.length(). Here's the corrected code:
//#include <bits/stdc++.h>
#include <string>
#include <iostream>
using namespace std;
int getEquallength(string& a, string& b)
{
int n1 = a.length();
int n2 = b.length();
if (n1 > n2)
{
for (int i = 0; i < n1 - n2; i++)
{
b = '0' + b;
}
}
else if (n2 > n1)
{
for (int i = 0; i < n2 - n1; i++)
{
a = '0' + a;
}
}
return a.length();
}
string addstrings(string a, string b)
{
int n = getEquallength(a, b);
n = a.length();
string result = "";
int carry = 0;
for (int i = n - 1; i >= 0; i--)
{
int f = a[i] - '0';
int s = b[i] - '0';
int sum = f + s + carry;
carry = sum / 10;
sum = sum % 10 + '0';
result = char(sum) + result;
}
if (carry) result = char(carry + '0') + result;
return result;
}
string substract_str(string a, string b)
{
int n = getEquallength(a, b);
int carry = 0;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string result;
for (int i = 0; i < a.length(); i++)
{
int f = a[i] - '0';
int s = b[i] - '0';
int sub = 0;
sub = f - s - carry;
if (sub < 0)
{
sub += 10;
carry = 1;
}
else
carry = 0;
result = char(sub + '0') + result;
}
return result;
}
string karutsuba(string a, string b)
{
int n = getEquallength(a, b);
if (n == 0) return "0";
if (n == 1)
{
return to_string(atoi(a.c_str()) * atoi(b.c_str()));
}
int fh = n / 2;
int sh = n - n / 2;
string Xl = a.substr(0, fh);
string Xr = a.substr(fh, sh);
string Yl = b.substr(0, fh);
string Yr = b.substr(fh, sh);
string P1 = karutsuba(Xl, Yl);
string P2 = karutsuba(Xr, Yr);
string res = addstrings(P1, P2);
string P3 = karutsuba(addstrings(Xl, Xr), addstrings(Yl, Yr));// (Xl+Xr)*(Yl+Yr)
P3 = substract_str(P3, res);//P3=Xl*Yr+Xr.Yl
for (int i = 0; i < 2 * sh; i++)
{
P1.push_back('0');
}
for (int i = 0; i < sh; i++)
{
P3.push_back('0');
}
P1 = addstrings(P1, P2);
string result = addstrings(P1, P3);
return result;
}
int main()
{
string a, b;
cout << "a:" << '\n';
cin >> a;
cout << "b:" << '\n';
cin >> b;
int n = getEquallength(a, b);
cout << karutsuba(a, b);
}
|
71,211,009 | 71,211,385 | Error in setting in event filter : Can not cast to its private base class QObject | I am trying to set event filter for rubber band rectangle zoom in. But getting the following error
widget.cpp:29:42: error: cannot cast 'SchematicDesign' to its private
base class 'QObject' schematicdesign.h:13:68: note: constrained by
implicitly private inheritance here
widget.h
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QGraphicsView
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
QGraphicsScene* scene;
QGraphicsView* view;
};
#endif // WIDGET_H
widget.cpp
Widget::Widget(QWidget *parent)
: QGraphicsView(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
view = new QGraphicsView(this);
view->setScene(scene);
view->setContextMenuPolicy(Qt::CustomContextMenu);
view->setDragMode(QGraphicsView::RubberBandDrag);
view->setBackgroundBrush(Qt::gray);
view->viewport()->installEventFilter(new SchematicDesign()); //Error
}
SchematicDesign.h
class SchematicDesign : public QGraphicsRectItem
public:
explicit SchematicDesign();
explicit SchematicDesign(qreal x, qreal y, qreal width, qreal height,QGraphicsItem *parent = nullptr)
: QGraphicsRectItem(x, y, width, height, parent)
{}
public:
bool eventFilter(QObject *watched, QEvent *event);
};
Schematicdesign.cpp
SchematicDesign::SchematicDesign(){}
bool SchematicDesign::eventFilter(QObject *watched, QEvent *event)
{
bool filterEvent = false;
switch(event->type()) {
case QEvent::MouseButtonPress:
{
QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
rubberBandOrigin = mouseEvent->pos();
rubberBandActive = true;
break;
}
case QEvent::MouseButtonRelease:
{
if (rubberBandActive) {
QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
QPoint rubberBandEnd = mouseEvent->pos();
QGraphicsView * view = static_cast<QGraphicsView *>(watched->parent());
QRectF zoomRectInScene = QRectF(view->mapToScene(rubberBandOrigin),
view->mapToScene(rubberBandEnd));
view->fitInView(zoomRectInScene, Qt::KeepAspectRatio);
rubberBandActive = false;
}
break;
}
}
return filterEvent;
}
How to solve this issue ? Any help will be appreciated.
| QGraphicsRectItem does not inherit from QObject, so installEventFilter will not work.
You'll want to override sceneEvent (or sceneEventFilter, if you actually want a filter, but it seems like you may just want SchematicDesign to handle the events itself) and use installSceneEventFilter. From the documentation:
You can filter events for any other item by installing event filters. This functionality is separate from Qt's regular event filters (see QObject::installEventFilter()), which only work on subclasses of QObject. After installing your item as an event filter for another item by calling installSceneEventFilter(), the filtered events will be received by the virtual function sceneEventFilter(). You can remove item event filters by calling removeSceneEventFilter().
|
71,211,395 | 71,232,114 | visual studio code not running code cause of ofstream | I have set up my Visual Studio Code and it works fine, but when I want to use fstream functions, it doesn't run. Here's an example:
#include <iostream>
#include <math.h>
#include <conio.h>
#include <fstream>
#include <string>
using namespace std;
void createfile();
int main(){
int choice;
cout << "Enter 1 to create file" << endl;
cin >> choice;
switch (choice){
case 1:
createfile();
break;
case 2:
break;
}
return 0;
}
void createfile(){
ofstream file ("file.txt");
file.close();
}
The terminal says:
PS D:\vs code cpp> cd "d:\vs code cpp\" ; if ($?) { g++ test.cpp -o test } ; if ($?) { .\test }
And then after trying to run, it says:
PS D:\vs code cpp>
Literally nothing. I even reinstalled Visual Studio Code, but it didn't work.
Does anyone know what the problem is?
| I installed mingw again and it worked.
|
71,211,646 | 71,211,826 | c++ std vector initialize with existing objects | Below is some code that contains some already created Location objects and updates them. Then it needs to construct a std::vector of those objects to pass to other functions.
The way I construct the vector looks cleaner as it is a initializer list and is one line, instead of using 3 push_back calls after initializing an empty vector. Since we know all the elements that are going in to the vector already at construction time.
However, this leads to 2 copies being made per element. Firstly, why are there two copies being made in this line? Is the initializer list first constructor with copies, and then the vector constructor is called, therefore a second copy?
std::vector<Location> pointsVec {l1, l2, l3};
And secondly, is there a vector constructor or another technique to initialize the vector with only 1 copy? (I want to make exactly 1 copy as I still want to use the local objects)
struct Location
{
Location(int x, int y, std::string frame)
: x(x)
, y(y)
, frame(std::move(frame))
{
std::cout << "ctor" << std::endl;
}
Location(const Location & other)
: x(other.x)
, y(other.y)
, frame(other.frame)
{
std::cout << "copy ctor" << std::endl;
}
Location(Location && other)
: x(std::move(other.x))
, y(std::move(other.y))
, frame(std::move(other.frame))
{
std::cout << "move ctor" << std::endl;
}
int x;
int y;
std::string frame;
};
int main ()
{
// local objects
Location l1 {1, 2, "local"};
Location l2 {3, 4, "global"};
Location l3 {5, 6, "local"};
// code that updates l1, l2, l3
// .
// .
// .
// construct vector
std::vector<Location> pointsVec {l1, l2, l3}; // 2 copies per element
std::vector<Location> pointsVec1;
pointsVec1.push_back(l1);
pointsVec1.push_back(l2);
pointsVec1.push_back(l3); // 1 copy per element
return 0;
}
edit: this question was in general for objects that are expensive to copy. adding a string to this struct to demonstrate that point
edit: adding sample move ctor
|
Is there a vector constructor or another technique to initialize the vector with only 1 copy?
If you move the local objects into an array, you can construct the vector from that array, eg:
// local objects
Location locs[3]{ {1, 2}, {3, 4}, {5, 6} };
// code that updates locs ...
// construct vector
std::vector<Location> pointsVec {locs, locs+3};
Online Demo
Another option would be to simply get rid of the local objects altogether, construct them inside the vector to begin with, and then just refer to those elements, eg:
// construct vector
std::vector<Location> pointsVec{ {1, 2}, {3, 4}, {5, 6} };
// local objects
Location &l1 = pointsVec[0];
Location &l2 = pointsVec[1];
Location &l3 = pointsVec[2];
// code that updates l1, l2, l3 ...
|
71,212,596 | 71,214,266 | OpenMP parallel calculating for loop indices | My parallel programming class has the program below demonstrating how to use the parallel construct in OpenMP to calculate array bounds for each thread to be use in a for loop.
#pragma omp parallel
{
int id = omp_get_thread_num();
int p = omp_get_num_threads();
int start = (N * id) / p;
int end = (N * (id + 1)) / p;
if (id == p - 1) end = N;
for (i = start; i < end; i++)
{
A[i] = x * B[i];
}
}
My question is, is the if statement (id == p - 1) necessary? From my understanding, if id = p - 1, then end will already be N, thus the if statement is not necessary. I asked in my class's Q&A board, but wasn't able to get a proper answer that I understood. Assumptions are: N is the size of array, x is just an int, id is between 0 and p - 1.
| You are right. Indeed, (N * ((p - 1) + 1)) / p is equivalent to
(N * p) / p assuming p is strictly positive (which is the case since the number of OpenMP thread is guaranteed to be at least 1). (N * p) / p is equivalent to N assuming there is no overflow. Such condition is often useful when the integer division cause some truncation but this is not the case here (it would be the case with something like (N / p) * id).
Note that this code is not very safe for large N because sizeof(int) is often 4 and the multiplication is likely to cause overflows (resulting in an undefined behaviour). This is especially true on machines with many cores like on supercomputer nodes. It is better to use the size_t type which is usually an unsigned 64-bit type meant to be able to represent the size of any object (for example the size of an array).
|
71,212,959 | 71,213,957 | How to deal with the sign bit of integer representations with odd bit counts? | Let's assume we have a representation of -63 as signed seven-bit integer within a uint16_t. How can we convert that number to float and back again, when we don't know the representation type (like two's complement).
An application for such an encoding could be that several numbers are stored in one int16_t. The bit-count could be known for each number and the data is read/written from a third-party library (see for example the encoding format of tivxDmpacDofNode() here: https://software-dl.ti.com/jacinto7/esd/processor-sdk-rtos-jacinto7/latest/exports/docs/tiovx/docs/user_guide/group__group__vision__function__dmpac__dof.html --- but this is just an example). An algorithm should be developed that makes the compiler create the right encoding/decoding independent from the actual representation type. Of course it is assumed that the compiler uses the same representation type as the library does.
One way that seems to work well, is to shift the bits such that their sign bit coincides with the sign bit of an int16_t and let the compiler do the rest. Of course this makes an appropriate multiplication or division necessary.
Please see this example:
#include <iostream>
#include <cmath>
int main()
{
// -63 as signed seven-bits representation
uint16_t data = 0b1000001;
// Shift 9 bits to the left
int16_t correct_sign_data = static_cast<int16_t>(data << 9);
float f = static_cast<float>(correct_sign_data);
// Undo effect of shifting
f /= pow(2, 9);
std::cout << f << std::endl;
// Now back to signed bits
f *= pow(2, 9);
uint16_t bits = static_cast<uint16_t>(static_cast<int16_t>(f)) >> 9;
std::cout << "Equals: " << (data == bits) << std::endl;
return 0;
}
I have two questions:
This example uses actually a number with known representation type (two's complement) converted by https://www.exploringbinary.com/twos-complement-converter/. Is the bit-shifting still independent from that and would it work also for other representation types?
Is this the canonical and/or most elegant way to do it?
Clarification:
I know the bit width of the integers I would like to convert (please check the link to the TIOVX example above), but the integer representation type is not specified.
The intention is to write code that can be recompiled without changes on a system with another integer representation type and still correctly converts from int to float and/or back.
My claim is that the example source code above does exactly that (except that the example input data is hardcoded and it would have to be different if the integer representation type were not two's complement). Am I right? Could such a "portable" solution be written also with a different (more elegant/canonical) technique?
| Your question is ambiguous as to whether you intend to truly store odd-bit integers, or odd-bit floats represented by custom-encoded odd-bit integers. I'm assuming by "not knowing" the bit-width of the integer, that you mean that the bit-width isn't known at compile time, but is discovered at runtime as your custom values are parsed from a file, for example.
Edit by author of original post:
The assumption in the original question that the presented code is independent from the actual integer representation type, is wrong (as explained in the comments). Integer types are not specified, for example it is not clear that the leftmost bit is the sign bit. Therefore the presented code also contains assumptions, they are just different (and most probably worse) than the assumption "integer representation type is two's complement".
Here's a simple example of storing an odd-bit integer. I provide a simple struct that let's you decide how many bits are in your integer. However, for simplicity in this example, I used uint8_t which has a maximum of 8-bits obviously. There are several different assumptions and simplifications made here, so if you want help on any specific nuance, please specify more in the comments and I will edit this answer.
One key detail is to properly mask off your n-bit integer after performing 2's complement conversions.
Also please note that I have basically ignored overflow concerns and bit-width switching concerns that may or may not be a problem depending on how you intend to use your custom-width integers and the maximum bit-width you intend to support.
#include <iostream>
#include <string>
struct CustomInt {
int bitCount = 7;
uint8_t value;
uint8_t mask = 0;
CustomInt(int _bitCount, uint8_t _value) {
bitCount = _bitCount;
value = _value;
mask = 0;
for (int i = 0; i < bitCount; ++i) {
mask |= (1 << i);
}
}
bool isNegative() {
return (value >> (bitCount - 1)) & 1;
}
int toInt() {
bool negative = isNegative();
uint8_t tempVal = value;
if (negative) {
tempVal = ((~tempVal) + 1) & mask;
}
int ret = tempVal;
return negative ? -ret : ret;
}
float toFloat() {
return toInt(); //Implied truncation!
}
void setFromFloat(float f) {
int intVal = f; //Implied truncation!
bool negative = f < 0;
if (negative) {
intVal = -intVal;
}
value = intVal;
if (negative) {
value = ((~value) + 1) & mask;
}
}
};
int main() {
CustomInt test(7, 0b01001110); // -50. Would be 78 if this were a normal 8-bit integer
std::cout << test.toFloat() << std::endl;
}
|
71,213,295 | 71,213,585 | HTTP requests via proxy with boost beast | Is it possible to set a proxy when making HTTP requests using Boost Beast?
Using CURL is straighforward. Anyone has done this?
Thank you,
| Depends on the kind of proxy. There's a socks4 sample in the Asio library distribution (asio/example/cpp{03,11}/socks4).
I've written a socks4 client (sync/async) on here: socks4 with asynchronous boost::asio.
More recently I extended that for socks5: Is there a native support for proxy connection via socks5 for boost::asio?
Which I also put on github: https://github.com/sehe/asio-socks45-client. I intend to take some time to rework them at least adding basic authentication. They might get added to the Beast libraries.
|
71,213,495 | 71,213,782 | how do you define an exact case constant with a switch statement in c++ | I'm learning C++ and I don't fully understand how case works in switch statements. I have the following code:
bool accept3() {
int tries = 1;
while (tries<4) {
std::cout<<"Do you want to proceed (y or n)?\n";
char answer = 0;
std::cin>>answer;
switch(answer) {
case 'y':
return true;
case 'n':
return false;
default:
std::cout<<"Sorry, but I don't understand that.\n";
tries ++;
}
}
std::cout << "I'll take that as a no.\n";
return false;
}
int main()
{
//accept();
//accept2();
accept3();
}
It works as expected when you input, 'y', 'n', or any other single character that does not meet the two defined cases.
When you input any string of characters that begins with n, it still takes that as the 'n' case. Why does it do this? How can I make this more exact, so that it ONLY accepts 'n' and not 'no', 'no way' or any other string beginning with 'n'.
Thank you!
|
When you input any string of characters that begins with n, it still takes that as the 'n' case. Why does it do this?
Because you are asking cin to read a single char, so that is what it does. operator>>(char&) ignores leading whitespace, if any, and then reads 1 char. Any subsequent characters, if any, are left in the input buffer for later reads.
How can I make this more exact, so that it ONLY accepts 'n' and not 'no', 'no way' or any other string beginning with 'n'.
Use cin.getline() or std::getline() instead, and then compare the entire line, eg:
bool accept3() {
int tries = 1;
std::string answer;
do {
std::cout << "Do you want to proceed (y or n)?\n";
std::getline(std::cin >> std::ws, answer);
if (answer == "y")
return true;
if (answer == "n")
return false;
std::cout << "Sorry, but I don't understand that.\n";
++tries;
}
while (tries < 4);
std::cout << "I'll take that as a no.\n";
return false;
}
|
71,213,831 | 71,213,848 | C++ char* as a function parameter | How can I pass a char pointer (char*) to the function func()?
#include <iostream>
using namespace std;
void func(char *var)
{
cout << var;
}
int main()
{
char* test = "Hello World";
func(test);
}
The compiler says:
Initialization: const char[12] cannot be converted to char *
| A string literal is a const char[N] array in read-only memory (where N is the number of characters in the literal, plus 1 for the null terminator, so in your case 11+1=12). You can't point a char* pointer (ie, a pointer to non-const data) at a string literal, as that would allow for the possibility of altering read-only data, which is undefined behavior.
Simply change your pointer type to const char* instead (ie a pointer to const data), eg.
#include <iostream>
using namespace std;
void func(const char *var)
{
cout << var;
}
int main()
{
const char* test = "Hello World";
func(test);
}
Otherwise, as you say you have no control over the function declaration, then if you really want to pass a string literal to a char* pointer, you should copy the characters into a separate writable char[] buffer first, and then point at that instead, eg:
#include <iostream>
using namespace std;
void func(char *var)
{
cout << var;
}
int main()
{
char test[] = "Hello World";
func(test);
}
Or, if you know for sure that the function will never modify the characters, you can just cast off the const-ness using const_cast (though this is highly NOT recommended, I'm including it for completeness), eg:
#include <iostream>
using namespace std;
void func(char *var)
{
cout << var;
}
int main()
{
char* test = const_cast<char*>("Hello World");
func(test);
/* alternatively:
const char* test = "Hello World";
func(const_cast<char*>(test));
*/
}
|
71,215,301 | 71,215,373 | 0xC0000005: Access violation reading location 0x005EF9E4 | I am having issues with Handles. I have Bytebeat (music in bytes) playing inside of a DWORD WINAPI function. When I try to terminate and close the thread, it straight up gives me the error in the title. This is my code:
#include <windows.h>
#pragma comment(lib, "Winmm.lib")
DWORD WINAPI bytebeat1(LPVOID) {
while (1) {
HWAVEOUT hwo = 0;
WAVEFORMATEX wfx = { WAVE_FORMAT_PCM, 1, 11000, 11000, 1, 8, 0 };
waveOutOpen(&hwo, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL);
char buffer[11000 * 6];
for (DWORD t = 0; t < sizeof(buffer); t++)
buffer[t] = static_cast<char>(t & t + t / 256) - t * (t >> 15) & 64;
WAVEHDR hdr = { buffer, sizeof(buffer), 0, 0, 0, 0, 0, 0 };
waveOutPrepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutWrite(hwo, &hdr, sizeof(WAVEHDR));
waveOutUnprepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutClose(hwo);
Sleep(6000);
}
}
DWORD WINAPI bytebeat2(LPVOID) {
while (1) {
HWAVEOUT hwo = 0;
WAVEFORMATEX wfx = { WAVE_FORMAT_PCM, 1, 8000, 8000, 1, 8, 0 };
waveOutOpen(&hwo, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL);
char buffer[8000 * 6];
for (DWORD t = 0; t < sizeof(buffer); t++)
buffer[t] = static_cast<char>(t, t / 5) >> t / 25 & t / 55 ^ t & 255 ^ (t / 150) ^ 2508025 * 24240835810 & (t / 100) * t / 6000 ^ 5000 * t / 2500 ^ 25 * t / 24;
WAVEHDR hdr = { buffer, sizeof(buffer), 0, 0, 0, 0, 0, 0 };
waveOutPrepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutWrite(hwo, &hdr, sizeof(WAVEHDR));
waveOutUnprepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutClose(hwo);
Sleep(6000);
}
}
int main() {
HANDLE beat1 = CreateThread(0, 0, bytebeat1, 0, 0, 0);
Sleep(6000);
TerminateThread(beat1, 0); CloseHandle(beat1);
Sleep(1000);
HANDLE beat2 = CreateThread(0, 0, bytebeat2, 0, 0, 0);
Sleep(6000);
TerminateThread(beat2, 0); CloseHandle(beat2);
}
I do not know why this is happening. The only fix is compiling it with G++ but I want it so I could just build it. Any help is appreciated. Thanks!
| When you call TerminateThread, you are basically force-crashing your threads. They still have their own stack allocated and handles to Windows resources. They aren't cleaned up properly, causing your crash.
Here's a simple example of how to close your threads without any error. In a real-world scenario this is an unprofessional solution, but it shows the bare minimum that you need to do.
#include <windows.h>
#pragma comment(lib, "Winmm.lib")
volatile bool quit1 = false;
volatile bool quit2 = false;
DWORD WINAPI bytebeat1(LPVOID) {
while (!quit1) {
HWAVEOUT hwo = 0;
WAVEFORMATEX wfx = { WAVE_FORMAT_PCM, 1, 11000, 11000, 1, 8, 0 };
waveOutOpen(&hwo, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL);
char buffer[11000 * 6];
for (DWORD t = 0; t < sizeof(buffer); t++)
buffer[t] = static_cast<char>(t & t + t / 256) - t * (t >> 15) & 64;
WAVEHDR hdr = { buffer, sizeof(buffer), 0, 0, 0, 0, 0, 0 };
waveOutPrepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutWrite(hwo, &hdr, sizeof(WAVEHDR));
waveOutUnprepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutClose(hwo);
Sleep(6000);
}
return 0;
}
DWORD WINAPI bytebeat2(LPVOID) {
while (!quit2) {
HWAVEOUT hwo = 0;
WAVEFORMATEX wfx = { WAVE_FORMAT_PCM, 1, 8000, 8000, 1, 8, 0 };
waveOutOpen(&hwo, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL);
char buffer[8000 * 6];
for (DWORD t = 0; t < sizeof(buffer); t++)
buffer[t] = static_cast<char>(t, t / 5) >> t / 25 & t / 55 ^ t & 255 ^ (t / 150) ^ 2508025 * 24240835810 & (t / 100) * t / 6000 ^ 5000 * t / 2500 ^ 25 * t / 24;
WAVEHDR hdr = { buffer, sizeof(buffer), 0, 0, 0, 0, 0, 0 };
waveOutPrepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutWrite(hwo, &hdr, sizeof(WAVEHDR));
waveOutUnprepareHeader(hwo, &hdr, sizeof(WAVEHDR));
waveOutClose(hwo);
Sleep(6000);
}
return 0;
}
int main() {
HANDLE beat1 = CreateThread(0, 0, bytebeat1, 0, 0, 0);
Sleep(6000);
quit1 = true;
WaitForSingleObject(beat1, INFINITE);
CloseHandle(beat1);
Sleep(1000);
HANDLE beat2 = CreateThread(0, 0, bytebeat2, 0, 0, 0);
Sleep(6000);
quit2 = true;
WaitForSingleObject(beat2, INFINITE);
CloseHandle(beat2);
}
|
71,215,477 | 71,215,533 | C++ rvalue assignment what caused this program to crash but lvalue assignment not | I am studying C++ rvalue reference by example. It was like this:
Intvec::~Intvec()
{
log("destructor");
if (m_data) {
delete[] m_data;
m_data = 0;
}
}
Intvec::Intvec(const Intvec& other)
:m_size(other.m_size), m_data(new int[m_size])
{
log("copy constructor");
for(size_t i = 0; i<m_size; ++i)
m_data[i] = other.m_data[i];
}
Intvec& Intvec::operator=(const Intvec& other)
{
log("copy assignment operator");
Intvec tmp(other);
std::swap(m_size, tmp.m_size);
std::swap(m_data, tmp.m_data);
return *this;
}
Then I changed it to be following. When debugging step by step, it calls delete[] many times until it crashes: read access violation at: 0x3f7a2f91
Intvec& Intvec::operator=(const Intvec& other)
{
log("copy assignment operator");
size_t othersize = other.m_size;
int* otherdata = other.m_data;
std::swap(m_size, othersize);
std::swap(m_data, otherdata);
return *this;
}
I am confused at:
In example, Intvec tmp(other) returns a tmporary tmp object, it would be destroyed after return *this, it does not crash.
In my code, other is an rvalue, it is also destroyed after return *this, why it crashes because of read access at wrong memory.
It only happens to rvalue, not lvalue.
Intvec v1 = Intvec(10);
Intvec v2;
cout << "assigning lvalue...\n";
v2 = v1;
cout << "ended assigning lvalue...\n";
Intvec v2;
cout << "assigning rvalue...\n";
v2 = Intvec(33);
cout << "ended assigning rvalue...\n";
| You are deleting the same m_data pointer twice. The problem starts here:
Intvec& Intvec::operator=(const Intvec& other)
{
log("copy assignment operator");
size_t othersize = other.m_size;
int* otherdata = other.m_data;
std::swap(m_size, othersize);
std::swap(m_data, otherdata);
return *this;
}
Decide if you want to transfer ownership, or duplicate. If you want to transfer ownership, then you need to set other.m_data = NULL after swapping it so that the r-value temporary object doesn't delete its own m_data when it destructs. You also need to delete the original m_data in the destination object PRIOR to swapping if it's not NULL (Apparently it is not NULL because otherwise the swap function would set other.m_data to NULL for you and there would be no problem).
If instead you'd rather duplicate it, then you need to structure your assignment operator more similarly to your copy constructor.
|
71,215,683 | 71,216,224 | Understanding a custom sort comparator - How to know what a true return means | I came across this sort comparator for a vector std::vector<foo>
bool comp(foo& x, foo& y)
{
return x.a < y.a;
}
Can someone explain what this does ? Does this mean that if a function returns false. foo x will be on the top and y at the bottom. Basically I am trying to understand is how do i know which element gets to be on the top ?
| Consider a vector composing of student records like name, age, score. Now you want to sort the vector according to name of students so you pass a custom compare function to the pre-defined sort function which will sort according to the name of student which will look like.
bool comp(foo& x, foo& y)
{
return x.name < y.name;
}
so, it covers on what it does then lets come to second part of your question.
If name in x is alphabetically smaller than y, then it will return a true and x records will come before y record, else vice versa.
|
71,215,776 | 71,243,149 | list does not provide a subscript operator | In C++ I got this error:
main.cpp:34:15: error: type 'list<std::string>' (aka 'list<basic_string<char>>') does not provide a subscript operator
cout << code[0];
~~~~^~
1 error generated.
make: *** [<builtin>: main.o] Error 1
Why? I thought square brackets were meant to get the data of an item of an list by index.
(code is an list)
|
list does not provide a subscript operator
That's correct, std::list does not provide operator[]. (std::vector and std::array both do so.)
It would have been possible for std::list to provide an indexing operator, so that lst[10] gives you the 10th (counting from 0) element of the list. But the operation would be O(N), so that lst[100] would take about 10 times as long as lst[10], because it would have to traverse the list from the beginning to find the requested element. It would allow you to write code that's very inefficient while hiding the inefficiency.
If you're going to need indexing, use a std::vector, std::array, or something similar.
The C++ standard library provides an indexing operator only when the element can be accessed directly, without traversing the container.
|
71,215,918 | 71,216,843 | Wrapper over a templated class with more than one template parameter pack | I'm writting a thin wrapper over a class from a third-party library.
My code looks like this:
template<typename TArg1, typename... TPack1, typename... TPack2>
class MyWrapper<TArg1, TPack1..., TPack2...> : protected ThirdParty<TArg1, TPack1..., TPack2...>
{
// class is empty
};
Where the template parameters of my wrapper mimic the ones in the third party class.
However, my code doesn't compile. The first compiler error I get is:
error C3856: 'MyWrapper': symbol is not a class template
I think it's a problem of my code not giving enough context to the compiler for deducting the template parameter packs. Therefore, they're ambiguous at the MyWrapper level even if they aren't at the ThirdParty level. I've been trying to understand how ThirdParty guarantees it but I haven't so far (and I don't even know if that's the issue).
For full context, the specific case of this problem is me trying to wrap a struct from an ECS library called entt: entt::basic_view.
| You don't declare a class template, but something like partial specilization.
The correct way should be
template <typename T>
class MyWrapper : protected ThirdParty<T>;
I don't use your template parameters since it contains 2 template parameter pack. The compiler can't know how to split the template arguments.
So I go to see the source code.
template<typename, typename, typename, typename = void>
class basic_view;
template<typename Entity, typename... Component, typename... Exclude>
class basic_view<Entity, get_t<Component...>, exclude_t<Exclude...>> {
}; // get_t / exclude_t is a struct template type.
You can use multiple template parameter packs in the partial specialization.
template <typename T, typename T, typename T, typename T = void>
class MyWrapper; // without definition neither
template<typename Entity, typename... Component, typename... Exclude>
class MyWrapper<Entity, get_t<Component...>, exclude_t<Exclude...>>: protected basic_view<Entity, get_t<Component...>, exclude_t<Exclude...>> {
};
It works fine, see demo.
|
71,216,428 | 71,216,470 | Why one statement calls copy constructor while the other one call calls copy-assignment operator? | #include<bits/stdc++.h>
using namespace std;
class numbered{
public:
int value;
numbered(){}
numbered& operator= (const numbered& n){
this->value=n.value+1;
return *this;
}
numbered (const numbered& n){
this->value=n.value+2;
}
};
int main(void){
numbered n1;
n1.value=15;
numbered n2=n1;
numbered n3;
n3=n1;
cout << n2.value <<endl;
cout << n3.value <<endl;
return 0;
}
Above this code segment, why does numbered n2=n1 call copy constructor while numbered3 n3;n3=n1; calls copy-assignment operator. Both of two variables, n2 and n3, are assigned by =. So what is the difference between two of them?
| Statement 1
When you wrote:
numbered n2 = n1; //this is initialization and so this uses copy constructor
The above statement is initialization of variable n2 using variable n1. And from copy constructor's documentation:
The copy constructor is called whenever an object is initialized (by direct-initialization or copy-initialization) from another object of the same type...
Since in this case we are doing initialization so according to the above quoted statement, this will use copy constructor.
Statement 2
On the other hand, when you wrote:
n3=n1; //this is assignment expression and so this uses copy assignment operator
The above statement is an assignment of n1 to n3. And from copy assignment operator's documentation:
The copy assignment operator is called whenever selected by overload resolution, e.g. when an object appears on the left side of an assignment expression.
Since the object n3 appears on the left side of the assignment expression, therefore according to the quoted statement above, this uses copy assignment operator.
|
71,217,084 | 71,217,319 | Call constructor without object name | In this code (assuming T can be any value type):
T foo;
T(std::move(foo)); // <---
Is T(std::move(foo)) the construction of an unnamed T from a T&&, or a C-style cast? I think both have the same effect, but I want to know what the expression means in the eyes of the compiler. In particular, it seems the expression SomeType(someExpression()) in general can be parsed as a C-style cast.
|
what the expression means in the eyes of the compiler
Both mean the same thing.
The standard calls (T)x an "Explicit type conversion (cast notation)", and T(x) an "Explicit type conversion (functional notation)".
"C-style cast" is not an official term, and it's moot whether T(x) (with a single argument) counts as a C-style cast or not. IMO it does.
|
71,217,152 | 71,217,254 | gcc can't take constexpr address of attribute through member pointer? | I'm trying to take the address of an object's attribute through a member pointer at compile-time. The following code compiles fine on MSVC but not on GCC:
#include <optional>
struct S {
int i = 42;
};
int main() {
constexpr S obj;
constexpr auto member = &S::i;
constexpr auto ptr = std::optional(member);
// OK
constexpr auto value = obj.*(*ptr);
static_assert(value == 42);
// Doesn't compile on gcc, can't take address through member pointer
constexpr auto & attr = obj.*(*ptr);
static_assert(attr == obj.i);
}
GCC gives the following error:
<source>:17:39: error: '(const int&)(& obj)' is not a constant expression
17 | constexpr auto & attr = obj.*(*ptr);
Here's the code on compiler explorer: https://godbolt.org/z/4WhW3qd7c
I haven't been able to find information about which compiler is wrong here. Can anyone shed some light on this?
| The result of a glvalue constant expression can only refer to an object with static storage duration.
obj doesn't have static storage duration, because it is declared at block scope.
You can give obj static storage duration by adding the static keyword at block scope:
static constexpr S obj;
or by declaring it at namespace scope.
|
71,217,413 | 71,217,480 | Why assignment operator working even when it was forbidden? | I'm struggling with OOP again. I tried to implement signgly linked list, here's the code:
template <typename T>
class node
{
T value;
node* next;
public:
node(const T& n)
{
this->value = n;
this->next = nullptr;
}
~node()
{
//is it ok to leave destructor empty in my case?
}
};
template <typename T>
class list
{
node<T>* head;
node<T>* tail;
public:
list()
{
this->head = nullptr;
this->tail = nullptr;
}
list(const list& arr)
{
*this = list(); //<================== the line I mentioned
node* current_this = this->head;
node* current_arr = this->arr;
while (current_arr != nullptr)
{
current_this = new node(current_arr);
current_arr = current_arr->next;
current_this = current_this->next;
}
}
list(list&& arr)
{
this->head = arr.head;
this->tail = arr.tail;
arr = list(); //<================== the line I mentioned
}
~list()
{
node* current = this->head;
while (current != nullptr)
{
node* next = current->next;
delete current;
current = next;
}
}
};
I wrote some lines without thinking, i.e. arr = list() and *this = list(). I didn't implemented operator= so there should be some troubles. I thought compiler has decided to generate copy/move assigment for me, so I decided to add these lines, just for curiosity sake:
list& operator=(const list& arr) = delete;
list& operator=(list&& arr) = delete;
But it still compiled and I don't understand why. What's the deal here? Shoudn't assignment be forbidden and therefore arr = list() and *this = list() be illegal?
| Templates aren't evaluated unless/until you instantiate them. If you don't use the copy or move constructor, then their bugs don't produce errors.
|
71,217,529 | 71,218,085 | How to expand the initializer list parameters pack? | Codes like:
template <typename... type>
void print(type... pack) {
((std::cout << pack << " "), ...);
}
But I have parameters like:
{ {1, 2, 3}, {4, 5, 6} }
So how can I pass this to the function ?
Or, how to expand the parameters pack like this ?
|
But I have parameters like: { {1, 2, 3}, {4, 5, 6} }
You can pack them into std::tuples
#include<iostream>
#include<tuple>
template <typename... Tuples>
void print_tuples(Tuples... tuples) {
(std::apply([](auto... args) {
((std::cout << args << " "), ...);
}, tuples), ...);
}
Then
print_tuples(std::tuple{1, 2, 3}, std::tuple{4, 5, 6});
Demo
|
71,217,631 | 71,217,821 | How can I read REG_NONE value in C++? | I want to read REG_NONE value from regedit with C++.
Here are my codes:
#include <iostream>
#include <windows.h>
using namespace std;
//--- Değişkenler ---//
//DWORD
DWORD dw_Rn_Boyut = MAX_PATH;
DWORD dw_Rn_Deger;
DWORD dw_Rn_DegerTipi = REG_NONE;
//HKEY
HKEY hkey_Rn;
//LONG
LONG long_Rn_Sonuc;
int main()
{
long_Rn_Sonuc = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\DownloadManager\\FoldersTree\\Compressed", 0, KEY_READ | KEY_WOW64_64KEY, &hkey_Rn);
if(long_Rn_Sonuc == ERROR_SUCCESS)
{
long_Rn_Sonuc = RegQueryValueEx(hkey_Rn, "pathW", 0, &dw_Rn_DegerTipi, (LPBYTE)&dw_Rn_Deger, &dw_Rn_Boyut);
if(long_Rn_Sonuc == ERROR_SUCCESS)
{
cout << dw_Rn_Deger;
}
}
getchar();
return 0;
}
My app shows 3801156 as result. This value is decimal version of that reg value. It equals to 3A 00 44
Here is the reg value which I want to read:
But why does not my app read other hex values?
How can I fix my problem?
| There is no such thing as a REG_NONE value. On success, your dw_Rn_DegerTipi variable will be updated with the actual value type (in this case, REG_BINARY), and your dw_Rn_Boyut variable will be updated with the number of actual bytes read.
Your problem is that you are using the wrong data type for your dw_Rn_Dege variable. The data in question is not a DWORD value, it is a WCHAR character string, so you need a WCHAR character buffer to receive it. You are telling RegQueryValueEx() that you allocated a buffer to hold MAX_PATH bytes, but you really didn't. So you have a buffer overflow error in your code when RegQueryValueEx() tries to write more than 4 bytes to the memory address of dw_Rn_Deger.
Try this instead:
#include <iostream>
#include <windows.h>
using namespace std;
//--- Değişkenler ---//
WCHAR sz_Rn_Deger[MAX_PATH+1] = {};
DWORD dw_Rn_Boyut = MAX_PATH * sizeof(WCHAR);
//HKEY
HKEY hkey_Rn;
//LONG
LONG long_Rn_Sonuc;
int main()
{
long_Rn_Sonuc = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\DownloadManager\\FoldersTree\\Compressed", 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &hkey_Rn);
if (long_Rn_Sonuc == ERROR_SUCCESS)
{
long_Rn_Sonuc = RegQueryValueExW(hkey_Rn, L"pathW", NULL, NULL, reinterpret_cast<LPBYTE>(&sz_Rn_Deger), &dw_Rn_Boyut);
if (long_Rn_Sonuc == ERROR_SUCCESS)
{
wcout << sz_Rn_Deger;
}
RegCloseKey(hkey_Rn);
}
getchar();
return 0;
}
|
71,218,222 | 71,218,494 | Partial template specialization with auto template argument | I have two enums
#include <iostream>
enum class E1 : unsigned int
{
E11 = 1
};
enum class E2 : unsigned int
{
E21 = 1
};
which have identical underlying values (1) in this case. Next, I have a class C which has two template parameters, an integer j and a value i with type auto.
template<int j, auto i>
struct C
{ C() { std::cout << "none\n"; } };
I want to partially specialize this class for both E1::E11 and E2::E21 like this:
template<int j>
struct C<j, E1::E11>
{ C() { std::cout << j << "E11\n"; } };
template<int j>
struct C<j, E2::E21>
{ C() { std::cout << j << "E21\n"; } };
And for completeness sake here is main that instantiates two objects:
int main()
{
C<0,E1::E11> e11;
C<1,E2::E21> e21;
return 0;
}
The code above works absolutely fine on gcc and icc as can be verified on Godbolt (full code)
But it fails with any other compiler (clang, msvc). With the following message
<source>:27:18: error: ambiguous partial specializations of 'C<0, E1::E11>'
C<0,E1::E11> e11;
^
<source>:18:8: note: partial specialization matches [with j = 0]
struct C<j, E1::E11>
^
<source>:22:8: note: partial specialization matches [with j = 0]
struct C<j, E2::E21>
It's kind of clear to me why this happens. The question that I can't seem to answer though is whether it is possible to solve this in a standard compatible way (if this is some gcc or icc feature) or if there's a workaround for the failing compilers (clang, msvc).
Btw. if I remove the int j template argument and just leave the auto i the code compiles with all compilers.
Thanks in advance,
Arno
| The auto template argument can be replaced by
template<int j,typename T,T i>
struct C
{ C() { std::cout << "none\n"; } };
If you are fine with more typing you can explicitly specify the type of the enum:
#include <iostream>
enum class E1 : unsigned int
{
E11 = 1
};
enum class E2 : unsigned int
{
E21 = 1
};
template<int j,typename T,T i>
struct C
{ C() { std::cout << "none\n"; } };
template<int j>
struct C<j,E1, E1::E11>
{ C() { std::cout << j << "E11\n"; } };
template<int j>
struct C<j,E2, E2::E21>
{ C() { std::cout << j << "E21\n"; } };
int main()
{
C<0,E1,E1::E11> e11;
C<1,E2,E2::E21> e21;
return 0;
}
And for less typing you can use a helper function:
template <int j,auto i>
auto make_C(){
return C<j,decltype(i),i>();
}
int main()
{
auto e11 = make_C<0,E1::E11>();
auto e21 = make_C<1,E2::E21>();
}
... or a type trait:
template <int j,auto i>
struct C_helper {
using type = C<j,decltype(i),i>;
};
int main()
{
C_helper<0,E1::E11>::type e11;
C_helper<1,E2::E21>::type e21;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.