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
69,663,059
69,666,073
C++/OpenGL/GLSL Blending two textures edges
Firstly here is the screenshot: I am trying to blend in multiple textures on the mesh based on the height of the point on mesh. Now what i want to achieve is a smooth blend at the borders(unlike what is currently a sharp line). Also i would like the border to be slightly random and have a factor to control the randomness. Here is my current code : #version 430 core out vec4 FragColor; #define NUM_TEXTURE_LAYERS 8 uniform vec3 _LightPosition; uniform vec3 _LightColor; in float height; in vec3 FragPos; in vec3 Normal; in vec2 TexCoord; uniform sampler2D _DiffuseTextures[NUM_TEXTURE_LAYERS]; uniform vec3 _DiffuseTexturesHeights[NUM_TEXTURE_LAYERS]; vec4 GetTextureColorBasedOnHeight(vec2 coord){ for(int i=0;i<NUM_TEXTURE_LAYERS;i++){ if(height > _DiffuseTexturesHeights[i].x && height < _DiffuseTexturesHeights[i].y){ return texture(_DiffuseTextures[i], coord*_DiffuseTexturesHeights[i].z); } } return vec4(0.0f); } void main() { vec3 objectColor = vec3(1, 1, 1); objectColor = GetTextureColorBasedOnHeight(TexCoord).xyz; vec3 norm = normalize(Normal); vec3 lightDir = normalize(_LightPosition - FragPos); float diff = max(dot(norm, lightDir), 0.0f); vec3 diffuse = diff * _LightColor; vec3 result = (vec3(0.2, 0.2, 0.2) + diffuse) * objectColor; FragColor = vec4(result, 1.0); } I did try the random boundaries but that was not very good and still blending is the issue! Here is the code with randomness: vec2 hash( vec2 p ) // replace this by something better { p = vec2( dot(p,vec2(127.1,311.7)), dot(p,vec2(269.5,183.3)) ); return -1.0 + 2.0*fract(sin(p)*43758.5453123); } float noise( in vec2 p ) { const float K1 = 0.366025404; // (sqrt(3)-1)/2; const float K2 = 0.211324865; // (3-sqrt(3))/6; vec2 i = floor( p + (p.x+p.y)*K1 ); vec2 a = p - i + (i.x+i.y)*K2; float m = step(a.y,a.x); vec2 o = vec2(m,1.0-m); vec2 b = a - o + K2; vec2 c = a - 1.0 + 2.0*K2; vec3 h = max( 0.5-vec3(dot(a,a), dot(b,b), dot(c,c) ), 0.0 ); vec3 n = h*h*h*h*vec3( dot(a,hash(i+0.0)), dot(b,hash(i+o)), dot(c,hash(i+1.0))); return dot( n, vec3(70.0) ); } vec4 GetTextureColorBasedOnHeight(vec2 coord){ for(int i=0;i<NUM_TEXTURE_LAYERS;i++){ float nv=noise(coord*0.01f); if(height+nv > _DiffuseTexturesHeights[i].x && height+nv < _DiffuseTexturesHeights[i].y){ return texture(_DiffuseTextures[i], coord*_DiffuseTexturesHeights[i].z); } } return vec4(0.0f); }
Thanks to Frank's answer, I am able to finally have something i like, Here is the result: https://youtu.be/DSkJqPhdRYI The Code : #version 430 core out vec4 FragColor; #define NUM_TEXTURE_LAYERS 8 uniform vec3 _LightPosition; uniform vec3 _LightColor; in float height; in vec3 FragPos; in vec3 Normal; in vec2 TexCoord; uniform sampler2D _DiffuseTextures[NUM_TEXTURE_LAYERS]; uniform vec3 _DiffuseTexturesHeights[NUM_TEXTURE_LAYERS]; vec2 hash( vec2 p ) // replace this by something better { p = vec2( dot(p,vec2(127.1,311.7)), dot(p,vec2(269.5,183.3)) ); return -1.0 + 2.0*fract(sin(p)*43758.5453123); } float noise( in vec2 p ) { const float K1 = 0.366025404; // (sqrt(3)-1)/2; const float K2 = 0.211324865; // (3-sqrt(3))/6; vec2 i = floor( p + (p.x+p.y)*K1 ); vec2 a = p - i + (i.x+i.y)*K2; float m = step(a.y,a.x); vec2 o = vec2(m,1.0-m); vec2 b = a - o + K2; vec2 c = a - 1.0 + 2.0*K2; vec3 h = max( 0.5-vec3(dot(a,a), dot(b,b), dot(c,c) ), 0.0 ); vec3 n = h*h*h*h*vec3( dot(a,hash(i+0.0)), dot(b,hash(i+o)), dot(c,hash(i+1.0))); return dot( n, vec3(70.0) ); } float getTextureInfluence(int i, vec2 coord) { float h = height + noise(coord*5)*2; float midVal = (_DiffuseTexturesHeights[i].x + _DiffuseTexturesHeights[i].y)/2; float p = 0; if(height < midVal) p = _DiffuseTexturesHeights[i].x - height; if(height >= midVal) p =height - _DiffuseTexturesHeights[i].y; return pow(2.713, -1.0*p); } vec4 GetTextureColorBasedOnHeight(vec2 coord){ vec4 accum = vec4(0.0); float total_influence = 0.0; for(int i=0; i < NUM_TEXTURE_LAYERS ; i++){ float texture_influence = getTextureInfluence(i, coord*_DiffuseTexturesHeights[i].z); total_influence += texture_influence; accum += texture(_DiffuseTextures[i], coord*_DiffuseTexturesHeights[i].z) * texture_influence; } if(total_influence > 0) { accum /= total_influence ; } return accum; } void main() { vec3 objectColor = vec3(1, 1, 1); objectColor = GetTextureColorBasedOnHeight(TexCoord).xyz; vec3 norm = normalize(Normal); vec3 lightDir = normalize(_LightPosition - FragPos); float diff = max(dot(norm, lightDir), 0.0f); vec3 diffuse = diff * _LightColor; vec3 result = (vec3(0.2, 0.2, 0.2) + diffuse) * objectColor; FragColor = vec4(result, 1.0); } If you are interested in the full source : https://github.com/Jaysmito101/TerraGen3D
69,663,253
69,663,664
Segmentation Fault in dynamically array creation
I was making a cpp program in which it takes two input from the user which determine the size of the 2d array and pass the values to the mat class constructor and dynamically create an array of the user's defined size. But, I don't know why it is not working and showing segmentation fault #include<iostream> using namespace std; class mat{ int **a; int r, c; public: mat(int row, int col){ r = row; c = col; for(int i = 0; i < r; i++){ *a = new int[r]; *a++; } } void input(){ for(int i = 0; i < r; i++){ for(int j = 0; i < c; j++){ cin >> a[i][j]; } } } void display(){ for(int i = 0; i < r; i++){ for(int j = 0; i < c; j++){ cout << a[i][j] << "\t"; } cout << endl; } } }; int main() { int r, c; cout << "enter row :"; cin >> r; cout << "enter column :"; cin >> c; mat m(r, c); m.input(); cout << "array \n"; m.display(); } I can feel that the issue is with the for loop in the constructor or maybe I am doing it wrong.
The class contains several errors. The variable a is never initialized. When we try to address the memory pointed to by a we get a segmentation fault. We can initialize it like this a = new int*[r] We should not change where a point's to, so don't use a++. Otherwise a[i][j] will not refer to the i'th row and the j'th column. We would also want to release the memory at some point. The inner loop for the columns for(int j = 0; i < c; j++) once entered will never terminate and will eventually produce a segmentation fault. We need to change i < c to j < c. If we fix these errors, it looks like this: class mat { int** a; int r, c; public: mat(int row, int col) { r = row; c = col; a = new int*[r]; for (int i = 0; i < r; i++) { a[i] = new int[c]; } } void input() { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> a[i][j]; } } } void display() { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cout << a[i][j] << "\t"; } cout << endl; } } };
69,663,943
69,664,066
C++ template with condition for type
I have class with template. I want to add template condition for one of the class methods. The idea is for float types I want separate passed method to call this with some epsillon value. Is it possible? The example what I want: template<typename ValueType> class Comparator { public: ... bool passed(ValueType actualValue); template< typename ValueType, typename = std::enable_if_t< std::is_floating_point<std::remove_reference_t<ValueType>>::value > > bool passed(ValueType actualValue, ValueType eps) { ... } ... }; Environment: Debian 11, C++14, gcc (Debian 10.2.1-6) 10.2.1 20210110
You are most of the way there already. In order to overload SFINAE, you need to use a non-type template parameter with an assigned default value instead of using defaulted type template parameter. So, we change both functions to use a non-type paramere with a default value, and just negate the condition like: template<typename ValueType> class Comparator { public: ... template< typename T = ValueType, std::enable_if_t< !std::is_floating_point<std::remove_reference_t<ValueType>>::value, // ^- not here, so only non-floating point types allowed bool> = true // set the bool to true, this lets us call the function without providing a value for it > bool passed(T actualValue) { non floating point code here } template< typename T = ValueType, std::enable_if_t< std::is_floating_point<std::remove_reference_t<T>>::value, bool> = true // set the bool to true, this lets us call the function without providing a value for it > bool passed(T actualValue, T eps) { floating point code here }
69,663,947
69,664,034
Get the common value between 2 vectors from the reverse order
So I need the common value between the 2 vectors from the end or in the reverse order. AND once I find the common value, I don't care whether there exists more common values or not. Okay, It sounded pretty easy to me also at first, but now I've looked at more vector syntaxes than ever in a single day. So, finally I'm asking for help here. Example: Input v1: 32, 64, 90 v2: 32, 64, 78 Output: 64 First try which I took from python syntax: vector<int>::iterator it1 ; vector<int>::iterator it2 ; for(it1 = v1.end() && it2 = v2.end(); it1!=v1.begin() && it2!=v2.begin(); it1-- && it2--){ if (*it1==*it2) { //please ignore if the inner syntax is wrong res=*it1; //because I already tried a lot of syntaxes so really confused right now break; //Please look at the for loop } This, didn't work. So, I thought maybe I'm not iterating 2 vectors correctly. I checked out google for the same and stackoverflow site showed me to use zip which doesn't work on my contest page. Next thing, I tried, was, vector<int>::iterator it1 = v1.end(); vector<int>::iterator it2 = v2.end(); while(it1 != v1.begin() || it2 != v2.begin()) { if (*it1 == *it2){ cout<<*it1<<" "<<*it2<<endl; //Output for the same is below res=*it1; break; } if(it1 != v1.begin()) { ++it1; } if(it2 != v2.begin()) { ++it2; } } It compiles successfully, and outputs, 0 0 So, Can you please help me with the same? Whether there exists a built-in function that could help me or there's a minor error and I can go ahead by improving that Thanks in advance.
With reverse iterators, iterating backwards is as simple as iterating forwards. You just need a loop that increments two iterators in parallel and check whether the elements are equal: #include <iostream> #include <vector> int main() { std::vector<int> v1{32, 64, 90}; std::vector<int> v2{32, 64, 78}; auto it1 = v1.rbegin(); auto it2 = v2.rbegin(); auto it_result = v1.rend(); for (; it1 != v1.rend() && it2 != v2.rend(); ++it1,++it2){ if (*it1 == *it2) { it_result = it1; break; } } if (it_result != v1.rend()) std::cout << *it_result; }
69,664,192
69,664,290
Swapping elements efficiently in C++ vector
Basically, I have a vector vect. I want to move part of vect from the end, to the start, efficiently. Example: vect before = {1,2,3,4,5,6,7} Moving the last two elements from end to start: vect after = {6,7,1,2,3,4,5} Now, I have the following function: template <class ElementType> void endToStart(std::vector<ElementType>& vect, size_t startPos) { std::vector<ElementType> temp; temp.reserve(vect.size()); for (auto i = startPos; i < vect.size(); ++i) { temp.push_back(vect[i]); } for (auto i = 0; i < startPos; ++i) { temp.push_back(vect[i]); } vect.swap(temp); } Is there a more efficient way of doing this?
It looks like you need std::rotate: #include <algorithm> // std::rotate #include <iostream> int main() { std::vector<int> vect = {1,2,3,4,5,6,7}; std::rotate(vect.begin(), vect.begin() + 5, vect.end()); // ^^^^^^^^^^^^^^^^ // the new first position for(auto v : vect) std::cout << v << ' '; } Demo
69,664,215
69,664,789
Access child in nested vector of unknown depth using vector of indexes
My goal is to be able to have a vector of indexes and navigate to that in a class with a vector of variants of vectors and that class. Say I have an "index vector" of unknown size with {0, 4, 7, 2} I would want to somehow use that to access someVector[0][4][7][2]. someVector is of a class node defined as: class node { public: node operator[](unsigned int index) { return std::get<node>(children[index]); } private: std::vector<std::variant<node, std::string>> children; } I had the idea of using a loop and a reference but couldn't figure that out. My idea was something along the lines of node elementRef = &nodeObject; for (int i = 0; i < vector.size(); i++) { tempElementRef = &elementRef[indexVector[I]]; elementRef = tempElementRef; }
With C++20 you can do it like this: node accessNode(node n, std::span<unsigned int> span) { return span.size() ? accessNode(n[span[0]], span.subspan(1)) : n; } example usage: std::vector<unsigned int> coordinates = {0, 4, 7, 2}; accessNode(someNode, coordinates); note: Handling exceptions from bad indices or children that are not nodes is left up to you.
69,664,337
69,665,821
Max value 2d array using pointer arithmetic
I'm trying to write a programm to find a maximum value in column in a initialized 5x5 matrix, and change it to -1. I found out the way to do it, but i want to find a better solution. Input: double array2d[5][5]; double *ptr; ptr = array2d[0]; // initializing matrix for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (j % 2 != 0) { array2d[i][j] = (i + 1) - 2.5; } else { array2d[i][j] = 2 * (i + 1) + 0.5; } } } This is my solution for the first column : // Changing the matrix using pointer arithmetic for (int i = 0; i < (sizeof(array2d) / sizeof(array2d[0][0])); ++i) { if (i % 5 == 0) { if (maxTemp <= *(ptr + i)) { maxTemp = *(ptr + i); } } } for (int i = 0; i < (sizeof(array2d) / sizeof(array2d[0][0])); ++i) { if (i % 5 == 0) { if (*(ptr + i) == maxTemp) { *(ptr + i) = -1; } } } I can repeat this code 5 times, and get the result, but i want a better solution. THX.
Below is the complete program that uses pointer arithmetic. This program replaces all the maximum values in each column of the 2D array -1 as you desire. #include <iostream> int main() { double array2d[5][5]; double *ptr; ptr = array2d[0]; // initializing matrix for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (j % 2 != 0) { array2d[i][j] = (i + 1) - 2.5; } else { array2d[i][j] = 2 * (i + 1) + 0.5; } } } //these(from this point on) are the things that i have added. //Everything above this comment is the same as your code. double (*rowBegin)[5] = std::begin(array2d); double (*rowEnd)[5] = std::end(array2d); while(rowBegin != rowEnd) { double *colBegin = std::begin(rowBegin[0]); double *colEnd = std::end(rowBegin[0]); double lowestvalue = *colBegin;//for comparing elements //double *pointerToMaxValue = colBegin; while(colBegin!= colEnd) { if(*colBegin > lowestvalue) { lowestvalue = *colBegin; //pointerToMaxValue = colBegin ; } colBegin = colBegin + 1; } double *newcolBegin = std::begin(rowBegin[0]); double *newcolEnd = std::end(rowBegin[0]); while(newcolBegin!=newcolEnd) { if(*newcolBegin == lowestvalue) { *newcolBegin = -1; } ++newcolBegin; } ++rowBegin; } return 0; } The program can be checked here. You can add print out all the element of the array to check whether the above program replaced all the maximum value in each column with -1.
69,664,366
69,664,467
Change in temperature file not detected
I'm writing a C++ program to run on my raspberry pi 3b+ that monitors the temperature of the CPU in real-time.In order to avoid polling, I'm using the sys/inotify library to watch /sys/class/thermal/thermal_zone0/temp for file updates. However, this doesn't seem to pick up changes to the file. To test this: I polled the file repeatedly (using cat) while running main, and I saw that the value in the file did change, but the change was not detected by main. I tried tail -f /sys/class/thermal/thermal_zone0/temp, but this did not detect any changes either. I created a script to periodically write to another file, and had my program watch this file, and it detected changes there. Is it possible that this file is being updated without propagating an event that is detectable by inotify? I am trying to avoid having to implement a periodic polling of this file to monitor for changes at all cost. temperatureMonitor.cpp #include <iostream> #include <unistd.h> #include <sys/inotify.h> #include <sys/types.h> #include "./temperatureMonitor.hpp" #define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) namespace Performance { void TemperatureMonitor::monitor_temperature(void(*callback)(double)){ }; void TemperatureMonitor::monitor_temperature_file(){ int length, i = 0; int fd; int wd; char buffer[BUF_LEN]; fd = inotify_init(); wd = inotify_add_watch(fd,"/sys/class/thermal/thermal_zone0/temp" , IN_MODIFY|IN_CREATE|IN_DELETE); while (true){ length = read(fd, buffer, BUF_LEN); std::cout << "detected file change\n"; }; }; }; main.cpp #include "Performance/temperatureMonitor.hpp" #define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUF_LEN ( 1024 ∗ ( EVENT_SIZE + 16 ) ) int main(){ Performance::TemperatureMonitor tm = Performance::TemperatureMonitor(); tm.monitor_temperature_file(); return 0; }; fwriter.go package main import ( "os" "time" ) func main() { f, err := os.Create("foo.txt") if err != nil { panic(err) } for { f.Write([]byte("test\n")) time.Sleep(time.Second) } }
It's not a real file, whenever you read it, the driver is asked to produce the data in it. There is no way to get notified when its contents would change. Polling is the answer. https://www.kernel.org/doc/html/latest/filesystems/sysfs.html On read(2), the show() method should fill the entire buffer. Recall that an attribute should only be exporting one value, or an array of similar values, so this shouldn’t be that expensive. This allows userspace to do partial reads and forward seeks arbitrarily over the entire file at will. If userspace seeks back to zero or does a pread(2) with an offset of ‘0’ the show() method will be called again, rearmed, to fill the buffer. You don't have to open and close it every time, seeking to the beginning should refresh it. Although this will probably not save much.
69,664,392
69,664,427
How to Have Preprocessor Statements in Header File Depend on Which C++ File is Including It
How can I exclude certain #include statements in my .h file depending on which .cpp is including the .h file? Example: main.cpp file <tell the header.h file that main.cpp is including it> #include "header.h" other.cpp file <tell the header.h file that other.cpp is including it> #include "header.h" header.h file <if called by main.cpp> #include "some_file_which_fails_when_used_with_OTHER_CPP.h" <end if>
The typical way to do this is to expect source files to #define a macro prior to including the header: // the_header.h #ifndef MY_HEADER_H_INCLUDED #define MY_HEADER_H_INCLUDED #ifdef MY_PROJECT_MAIN // ... #else // ... #endif #endif In files using the header's "default" behavior // some_code.cpp // Just use the header #include "the_header.h" In files using the header's activated behavior: // main.cpp // Make sure this is BEFORE the #include #define MY_PROJECT_MAIN #include "the_header.h"
69,664,451
69,664,625
Explicit instantiation of template class with templated member functions
With a class defined as follows: template <typename T> class A { private: T a; public: A(T& a) : a_(a) { } template <typename D> void Eval(D& arg) { // ... } }; template A<int>; I want to explicitly instantiate one instance of the class, and I want this class to have one explicit instantiation of Eval. The intention here is to get a member function pointer that avoids ambiguity: auto eval_ptr = &A<int>::Eval;
The ambiguity is not coming from anything to do with template instantiation of the class, it's caused by Eval also being a templated function. &A<int>::Eval does not point to a function, it points to a template. And there is just no such type as a "pointer to a template". If you want a pointer to A<int>::Eval, you need to specify D as well. auto eval_ptr = &A<int>::Eval<int>; works just fine for example. Addendum: Pointers-to-templates do exist in the grammatical sense, but there is no type an object can have to hold one of them. They must be immediately casted/decayed to a specific overload in order to be used, which doesn't come into play here since you want to store it in an auto. For example: The following is fine because there's clearly only one "version" of Eval that can be meant: void bar(void (A<int>::*arg)(int&)) {} void foo() { bar(&A<int>::Eval); }
69,664,773
69,665,608
Illegal operand error on a function pointer iterator
I am getting the following errors: '<': illegal, left operand has type 'const_Ty' '>: illegal, right operand has type 'const_Ty' in the below code. It's a relative simple iterator on a function pointer map where the functions are of the form void (Game::*)(UINT). I check the value against a float, then run the function. The problem seems to be in the for line, although I've got another substantially similar for loop somewhere else that works without a problem. using FuncPtr = void (Game::*)(UINT); std::map<FuncPtr, float> funcDelayedTriggerMap; void Game::PollProcessDelayedTriggers() { for (std::map<FuncPtr, float>::iterator it = funcDelayedTriggerMap.begin(); it != funcDelayedTriggerMap.end(); ++it) { float currentS = m_timer.GetElapsedSeconds(); if (it->second < currentS) { (this->*(it->first))(UINT_MAX); funcDelayedTriggerMap.erase(it->first); } } }
Member function pointers don't implement operator<, which is the default sorting function std::map uses. Member function pointers only implement operator== and operator!= . An easy way to fix this woud be to have a separate key and put the function pointer into the value of the map, e.g.: std::map<int, std::pair<FuncPtr, float>> or if you don't need the fast lookup of std::map, a simple vector would also work: std::vector<std::pair<FuncPtr, float>> An alternative approach would be to use the function pointer type as key: using FuncPtr = void (Game::*)(int); // Just a helper to get a unique type for each function pointer template<FuncPtr ptr> struct Tag {}; struct DelayedTrigger { FuncPtr ptr; float value; DelayedTrigger() : ptr(nullptr), value(0.0f) {} DelayedTrigger(FuncPtr _ptr, float _value) : ptr(_ptr), value(_value) {} }; std::map<std::type_index, DelayedTrigger> funcDelayedTriggerMap; void Game::PollProcessDelayedTriggers() { for (std::map<std::type_index, DelayedTrigger>::iterator it = funcDelayedTriggerMap.begin(); it != funcDelayedTriggerMap.end(); ++it) { float currentS = 1.0; if (it->second.value < currentS) { (this->*(it->second.ptr))(0); funcDelayedTriggerMap.erase(it->first); } } } This essentially uses the specific function pointer as a unique key. You could then add new entries like this: funcDelayedTriggerMap.emplace(typeid(Tag<&Game::DoIt>), DelayedTrigger{&Game::DoIt, 1.0f}); // or funcDelayedTriggerMap[typeid(Tag<&Game::DoIt>)] = {&Game::DoIt, 1.0f}; And check if a function is present: if(funcDelayedTriggerMap.contains(typeid(Tag<&Game::DoIt>))) { // ... } This however only works if you know all the functions you want to use with the map at compile time.
69,664,848
69,665,023
How do this program but in reverse, pattern
so i want output like this 1 123 12345 123 1 i already make the program but it only output these, and im confused how to output the bottom triangle 1 123 12345 here's my program #include <iostream> using namespace std; int main() { int n = 3 ; int i, j, k; for (i = 1; i <= n; i++) { for (j = n; j > i; j--) { cout << " "; } for (k = 1; k <= (2 * i - 1); k++) { cout << k; } cout <<endl; } return 0; }
I added another for loop exactly like yours with different order from n-1. I modified your code to this: int main() { int n = 3 ; int i, j, k; for (i = 1; i <= n; i++) { for (j = n; j > i; j--) { cout << " "; } for (k = 1; k <= (2 * i - 1); k++) { cout << k; } cout <<endl; } for (i = n - 1; i >= 1; i--) { for (j = n; j > i; j--) { cout << " "; } for (k = 1; k <= (2 * i - 1); k++) { cout << k; } cout <<endl; } return 0; } Now it returns: 1 123 12345 123 1
69,664,907
69,664,988
using a shared_ptr object in constructor works but not in destructor
I have a class where the construction is like: class CLSS { public: CLSS(const std::shared_ptr<someType>& pobj) { std::shared_ptr<someType> obj = pobj; obj->somefunc("DDDD") } ~CLSS() { } }; which works with now problem. However when I put the same function of obj->info("DDDD") in the diconstructor, it returns error, that is: ... ~CLSS() { obj->info("DDDD") } .... ---------------edit I tried class CLSS { public: std::shared_ptr<someType> obj; CLSS(const std::shared_ptr<someType>& pobj) { obj = pobj; obj->somefunc("DDDD") } ~CLSS() { } }; but still does not compile, the errors are not very readble.
obj is a local variable in the constructor. It is destroyed when the constructor ends. You need to declare it as a member of your class.
69,664,927
69,665,260
how to write this function in C++ using meta programming
What are you trying to achieve I want to convert RetType ClassA::MemberFunc(Args...) to mem_fn(&ClassA::MemberFunc) but it is like a function in order to avoid write lambda or function for every member functions What did you get out (include error messages) no matching function for call to ‘regisAdd(std::_Mem_fn<int (ABC::*)(int, int)>)’ Here is my code. #include <functional> #include <iostream> using namespace std; struct ABC { int value; int add(int a, int b) { return a + b * value; } int other(int a) { return a * value; } }; int doAdd(void* data, int a, int b) { ABC* p = (ABC*)data; return p->add(a, b); } typedef int (*TYPE_ADD)(void* data, int a, int b); TYPE_ADD gAdd = nullptr; void regisAdd(TYPE_ADD a) { gAdd = a; } void callAdd() { if (!gAdd) return; ABC abc; abc.value = 10; cout << gAdd(&abc, 1, 2) << endl; } typedef int (*TYPE_OTHER)(void* data, int a); TYPE_OTHER gOther = nullptr; void regisOther(TYPE_OTHER a) { gOther = a; } void callOther() { if (!gOther) return; ABC abc; abc.value = 10; cout << gOther(&abc, 12) << endl; } int main() { regisAdd(doAdd); // this is GOOD callAdd(); // call regisAdd([](void* data, int a, int b) { // < this is also GOOD return static_cast<ABC*>(data)->add(a, b); // < GOOD }); // < GOOD callAdd(); // call // how to write a general function work like mem_fn // to avoid write doAdd and lambda for every function signatures // regisAdd(mem_fn(&ABC::add)); // regisOther(mem_fn(&ABC::other)); // callAdd(); return 0; }
As I understand, you want something like: template <auto mem> // C++17, else <typename T, T mem> struct mem_to_func; template <typename C, typename Ret, typename ... Args, Ret (C::*m)(Args...)> struct mem_to_func<m> { static Ret func_ptr(C* c, Args... args) { return (c->*m)(std::forward<Args>(args)...); } static Ret func_ref(C& c, Args... args) { return (c.*m)(std::forward<Args>(args)...); } static Ret func_voidp(void* p, Args... args) { auto* c = static_cast<C*>(p); return (c->*m)(std::forward<Args>(args)...); } }; template <typename C, typename Ret, typename ... Args, Ret (C::*m)(Args...) const> struct mem_to_func<m> { static Ret func(const C* c, Args... args) { return (c->*m)(std::forward<Args>(args)...); } static Ret func_ref(const C& c, Args... args) { return (c.*m)(std::forward<Args>(args)...); } static Ret func_voidp(const void* p, Args... args) { const auto* c = static_cast<const C*>(p); return (c->*m)(std::forward<Args>(args)...); } }; // Others specializations for combination with // - volatile, // - reference to this, // - and C-ellipsis... and then regisAdd(mem_to_func<&ABC::add>::func_voidp);
69,665,119
69,669,576
How to define boost tokenizer to return boost::iterator_range<const char*>
I am trying to parse a file where each line is composed by attributes separated by ;. Each attribute is defined as key value or key=value, where key and value can be enclosed in double quotes " to allow for key and value containing special characters such as whitespace , equal sign = or semi-colon ;. To do so, I use first boost::algorithm::make_split_iterator, and then, to allow for double quotes, I use boost::tokenizer. I need to parse every key and value as a boost::iterator_range<const char*>. I tried coding as the code below, but I am unable to build it. It might be that the definition of the tokenizer is correct, but the error comes from the printing of the iterator_range. I can provide more information if necessary. #include <boost/algorithm/string.hpp> #include <boost/range/iterator_range.hpp> #include <boost/tokenizer.hpp> boost::iterator_range<const char*> line; const auto topDelim = boost::token_finder( [](const char c) { return (c == ';'); }, boost::token_compress_on); for (auto attrIt = make_split_iterator(line, topDelim); !attrIt.eof() && !attrIt->empty(); attrIt++) { std::string escape("\\"); std::string delim(" ="); std::string quote("\""); boost::escaped_list_separator<char> els(escape, delim, quote); boost::tokenizer< boost::escaped_list_separator<char>, boost::iterator_range<const char*>::iterator, // how to define iterator for iterator_range? boost::iterator_range<const char*> > tok(*attrIt, els); for (auto t : tok) { std::cout << t << std::endl; } Build errors: /third_party/boost/boost-1_58_0/include/boost/token_functions.hpp: In instantiation of 'bool boost::escaped_list_separator<Char, Traits>::operator()(InputIterator&, InputIterator, Token&) [with InputIterator = const char*; Token = boost::iterator_range<const char*>; Char = char; Traits = std::char_traits<char>]': /third_party/boost/boost-1_58_0/include/boost/token_iterator.hpp:70:36: required from 'void boost::token_iterator<TokenizerFunc, Iterator, Type>::initialize() [with TokenizerFunc = boost::escaped_list_separator<char>; Iterator = const char*; Type = boost::iterator_range<const char*>]' /third_party/boost/boost-1_58_0/include/boost/token_iterator.hpp:77:63: required from 'boost::token_iterator<TokenizerFunc, Iterator, Type>::token_iterator(TokenizerFunc, Iterator, Iterator) [with TokenizerFunc = boost::escaped_list_separator<char>; Iterator = const char*; Type = boost::iterator_range<const char*>]' /third_party/boost/boost-1_58_0/include/boost/tokenizer.hpp:86:33: required from 'boost::tokenizer<TokenizerFunc, Iterator, Type>::iter boost::tokenizer<TokenizerFunc, Iterator, Type>::begin() const [with TokenizerFunc = boost::escaped_list_separator<char>; Iterator = const char*; Type = boost::iterator_range<const char*>; boost::tokenizer<TokenizerFunc, Iterator, Type>::iter = boost::token_iterator<boost::escaped_list_separator<char>, const char*, boost::iterator_range<const char*> >]' test.cpp:21:23: required from here /third_party/boost/boost-1_58_0/include/boost/token_functions.hpp:188:19: error: no match for 'operator+=' (operand types are 'boost::iterator_range<const char*>' and 'const char') 188 | else tok+=*next; | ~~~^~~~~~~
As I said, you want parsing, not splitting. Specifically, if you were to split the input into iterator ranges, you would have to repeat the effort of parsing e.g. quoted constructs to get the intended (unquoted) value. I'd go by your specifications with Boost Spirit: using Attribute = std::pair<std::string /*key*/, // std::string /*value*/>; using Line = std::vector<Attribute>; using File = std::vector<Line>; A Grammar Now using X3 we can write expressions to define the syntax: auto file = x3::skip(x3::blank)[ line % x3::eol ]; Within a file, blank space (std::isblank) is generally skipped. The content consists of one or more lines separated by newlines. auto line = attribute % ';'; A line consists of one or more attributes separated by ';' auto attribute = field >> -x3::lit('=') >> field; auto field = quoted | unquoted; An attribute is two fields, optionally separated by =. Note that each field is either a quoted or unquoted value. Now, things get a little more tricky: when defining the field rules we want them to be "lexemes", i.e. any whitespace is not to be skipped. auto unquoted = x3::lexeme[+(x3::graph - ';' - '=')]; Note how graph already excludes whitespace (see std::isgraph). In addition we prohibit a naked ';' or '=' so that we don't run into a next attribute/field. For fields that may contain whitespace, and or those special characters, we define the quoted lexeme: auto quoted = x3::lexeme['"' >> *quoted_char >> '"']; So, that's just "" with any number of quoted characters in between, where auto quoted_char = '\\' >> x3::char_ | ~x3::char_('"'); the character can be anything escapped with \ OR any character other than the closing quote. TEST TIME Let's exercise *Live On Compiler Explorer for (std::string const& str : { R"(a 1)", R"(b = 2 )", R"("c"="3")", R"(a=1;two 222;three "3 3 3")", R"(b=2;three 333;four "4 4 4" c=3;four 444;five "5 5 5")", // special cases R"("e=" "5")", R"("f=""7")", R"("g="="8")", R"("\"Hello\\ World\\!\"" '8')", R"("h=10;i=11;" bogus;yup "nope")", // not ok? R"(h i j)", // allowing empty lines/attributes? "", "a 1;", ";", ";;", R"(a=1;two 222;three "3 3 3" n=1;gjb 222;guerr "3 3 3" )", }) // { File contents; if (parse(begin(str), end(str), parser::file, contents)) fmt::print("Parsed:\n\t- {}\n", fmt::join(contents, "\n\t- ")); else fmt::print("Not Parsed\n"); } Prints Parsed: - {("a", "1")} Parsed: - {("b", "2")} Parsed: - {("c", "3")} Parsed: - {("a", "1"), ("two", "222"), ("three", "3 3 3")} Parsed: - {("b", "2"), ("three", "333"), ("four", "4 4 4")} - {("c", "3"), ("four", "444"), ("five", "5 5 5")} Parsed: - {("e=", "5")} Parsed: - {("f=", "7")} Parsed: - {("g=", "8")} Parsed: - {(""Hello\ World\!"", "'8'")} Parsed: - {("h=10;i=11;", "bogus"), ("yup", "nope")} Not Parsed Not Parsed Not Parsed Not Parsed Not Parsed Not Parsed Allowing empty elements Is as simple as replacing line with: auto line = -(attribute % ';'); To also allow redundant separators: auto line = -(attribute % +x3::lit(';')) >> *x3::lit(';'); See that Live On Compiler Explorer Insisting on Iterator Ranges I explained above why I think this is a bad idea. Consider how you would correctly interpret the key/value from this line: "\"Hello\\ World\\!\"" '8' You simply don't want to deal with the grammar outside the parser. However, maybe your data is a 10 gigabyte memory mapped file: using Field = boost::iterator_range<std::string::const_iterator>; using Attribute = std::pair<Field /*key*/, // Field /*value*/>; And then add x3::raw[] to the lexemes: auto quoted = x3::lexeme[x3::raw['"' >> *quoted_char >> '"']]; auto unquoted = x3::lexeme[x3::raw[+(x3::graph - ';' - '=')]]; See it Live On Compiler Explorer
69,665,447
69,665,498
Read in arrays from a files and store them into struct members
Suppose I have a struct like this: struct Person { string fName; string lName; int age; }; And I want to read in a file(ppl.log) like this: Glenallen Mixon 14 Bobson Dugnutt 41 Tim Sandaele 11 How would I read in the file and store them? This is what I have int main() { Person p1, p2, p3; ifstream fin; fin.open("ppl.log"); fin >> p1; fin >> p2; fin >> p3; return 0; } Does that read in the entire line? Or do I have to use the getline()?
I recommend overloading operator>>: struct Person { string fName; string lName; int age; friend std::istream& operator>>(std::istream& input, Person& p); }; std::istream& operator>>(std::istream& input, Person& p) { input >> p.fName; input >> p.lName; input >> p.age; input.ignore(10000, '\n'); // Align to next record. return input; } This allows you to do things like this: std::vector<Person> database; Person p; //... while (fin >> p) { database.push_back(p); } Your fields are space separated, so you don't need to use getline. The operator>> for strings will read until a whitespace character.
69,665,485
69,695,741
Replace C++ class/static method with preprocessor?
I'd like to use the built-in compiler checks to verify format strings of a custom logging framework to catch the odd runtime crash due to mismatching format string <-> parameters in advance. Arguments of the custom C++ logging methods are identical to the printf() family so I was attempting to replace all calls to MyLogger::Error( with fprintf(stderr, Though unfortunately the (clang) preprocessor chokes on the scope resolution operator (::), i.e. instead of ULog::Warn( only the ULog substring is recognized: #define MyLogger::Error( fprintf(stderr, Any suggestions on how to make this work much appreciated.
Elaborating on the approach suggested by @Someprogrammerdude I've extended the custom logging class to use the clang/gcc format attribute to enable compiler format checking. The declaration simply becomes static void Error(const char *format,...) __attribute__ ((format (printf, 1, 2))); It's even better than the original idea to use the preprocessor to temp. enable checks by replacing calls to the custom formatter with calls to printf() as it's enabled all the time catching argument mismatches immediately! (FWIW - already fixed dozens of issues and couple potential crashes on our 120+ LOC code base)
69,665,635
69,665,997
How to use std::ranges on a vector for a function that needs two arguments?
I have been trying to understand the new ranges library and try to convert some of the more traditional for loops into functional code. The example code given by cppreference is very straight forward and readable. However, I am unsure how to apply Ranges over a vector of Points that needs to have every x and y values looked at, calculated, and compared at the end for which is the greatest distance. struct Point { double x; double y; } double ComputeDistance(const Point& p1, const Point& p2) { return std::hypot(p1.x - p2.x, p1.y - p2.y); } double GetMaxDistance(const std::vector<Point>& points) { double maxDistance = 0.0; for (int i = 0; i < points.size(); ++i) { for(int j = i; j < points.size(); ++j) { maxDistance = std::max(maxDistance, ComputeDistance(points.at(i),points.at(j))); } } return maxDistance; } GetMaxDistance is the code that I would love to try and clean up and apply ranges on it. Which I thought would be as simple as doing something like: double GetMaxDistance(const std::vector<Point>& points) { auto result = points | std::views::tranform(ComputeDistance); return static_cast<double>(result); } And then I realized that was not correct since I am not passing any values into the function. So I thought: double GetMaxDistance(const std::vector<Point>& points) { for(auto point : points | std::views::transform(ComputeDistance)) // get the max distance somehow and return it? // Do I add another for(auto nextPoint : points) here and drop the first item? } But then I realized that I am applying that function to every point, but not the point next to it, and this would also not work since I am still only passing in one argument into the function ComputeDistance. And since I need to compute the distance of all points in the vector I have to compare each of the points to each other and do the calculation. Leaving it as an n^2 algorithm. Which I am not trying to beat n^2, I would just like to know if there is a way to make this traditional for loop take on a modern, functional approach. Which brings us back to the title. How do I apply std::ranges in this case? Is it even possible to do with what the standard has given us at this point? I know more is to be added in C++23. So I don't know if this cannot be achieved until that releases or if this is not possible to do at all. Thanks!
The algorithm you're looking for is combinations - but there's no range adaptor for that (neither in C++20 nor range-v3 nor will be in C++23). However, we can manually construct it in this case using an algorithm usually called flat-map: inline constexpr auto flat_map = [](auto f){ return std::views::transform(f) | std::views::join; }; which we can use as follows: double GetMaxDistance(const std::vector<Point>& points) { namespace rv = std::views; return std::ranges::max( rv::iota(0u, points.size()) | flat_map([&](size_t i){ return rv::iota(i+1, points.size()) | rv::transform([&](size_t j){ return ComputeDistance(points[i], points[j]); }); })); } The outer iota is our first loop. And then for each i, we get a sequence from i+1 onwards to get our j. And then for each (i,j) we calculate ComputeDistance. Or if you want the transform at top level (arguably cleaner): double GetMaxDistance(const std::vector<Point>& points) { namespace rv = std::views; return std::ranges::max( rv::iota(0u, points.size()) | flat_map([&](size_t i){ return rv::iota(i+1, points.size()) | rv::transform([&](size_t j){ return std::pair(i, j); }); }) | rv::transform([&](auto p){ return ComputeDistance(points[p.first], points[p.second]); })); } or even (this version produces a range of pairs of references to Point, to allow a more direct transform): double GetMaxDistance(const std::vector<Point>& points) { namespace rv = std::views; namespace hof = boost::hof; return std::ranges::max( rv::iota(0u, points.size()) | flat_map([&](size_t i){ return rv::iota(i+1, points.size()) | rv::transform([&](size_t j){ return std::make_pair( std::ref(points[i]), std::ref(points[j])); }); }) | rv::transform(hof::unpack(ComputeDistance))); } These all basically do the same thing, it's just a question of where and how the ComputeDistance function is called. C++23 will add cartesian_product and chunk (range-v3 has them now) , and just recently added zip_transform, which also will allow: double GetMaxDistance(const std::vector<Point>& points) { namespace rv = std::views; namespace hof = boost::hof; return std::ranges::max( rv::zip_transform( rv::drop, rv::cartesian_product(points, points) | rv::chunk(points.size()), rv::iota(1)) | rv::join | rv::transform(hof::unpack(ComputeDistance)) ); } cartesian_product by itself would give you all pairs - which both includes (x, x) for all x and both (x, y) and (y, x), neither of which you want. When we chunk it by points.size() (produces N ranges of length N), then we repeatedly drop a steadingly increasing (iota(1)) number of elements... so just one from the first chunk (the pair that contains the first element twice) and then two from the second chunk (the (points[1], points[0]) and (points[1], points[1]) elements), etc. The zip_transform part still produces a range of chunks of pairs of Point, the join reduces it to a range of pairs of Point, which we then need to unpack into ComputeDistance. This all exists in range-v3 (except zip_transform there is named zip_with). In range-v3 though, you get common_tuple, which Boost.HOF doesn't support, but you can make it work.
69,665,736
69,665,869
How to dynamically allocate 2D array of pointer that's 64B aligned using posix_memalign
I have two arrays, y_train which is a 1D array, and x_train which is a 2D array. I need to dynamically allocate these two arrays using posix_memalign. I did that for y_train correctly. where I convert int y_train[4344] into the following code. int* Y_train; posix_memalign((void**)(&Y_train), 64, sizeof(int) * 4344); Now, I want to convert int x_train[4344][20]; in the same way but not sure how.
Get a memory block of the complete size and assign it to a pointer of the correct type: void *ptr; posix_memalign(&ptr, 64, sizeof(int) * 4344); int *Y_train = (int*)ptr; posix_memalign(&ptr, 64, sizeof(int) * 20 * 4344); int (*x_train)[20] = (int (*)[20])ptr; Now the whole 2D array is correct aligned, but not all inner arrays are correct aligned, because the 20 * sizeof(int) is not a multiple of 64. When you need every inner array of 20 ints to be aligned correctly, you have to add padding bytes, 12 ints, then every inner array has 128 bytes. posix_memalign(&ptr, 64, sizeof(int) * 32 * 4344); int (*x_train)[32] = (int (*)[32])ptr; Just ignore the last 12 ints.
69,666,181
69,667,132
c++ sort and quick sort algorithm and for loop question
Please could you help me to understand the below code from a book? I am wondering why " swap(words, start, current); " is not part of the for loop within the below code? The final effect of the "for loop - check words against chosen word" should be to position all the words less than the chosen word before all the words that are greater than or equal to it. However, without swapping the "start" and the "current" after each I++ iteration,I don't understand how the comparison is done as "*words[i]" within the IF statement will always compare against the "*words[start]" which is always equal to index = 0 ( condition is iterated within the loop, meaning comparison is done always against the 0 index) // referring to "*words[i] < *words[start]") P.s. my initial assumption was that the swap line "swap(words, start, current);" should be part of the for loop, below as you can see it's not part of the loop but rather out of the for loop. void sort(Words& words, size_t start, size_t end) { // start index must be less than end index for 2 or more elements if (!(start < end)) return; // Choose middle address to partition set swap(words, start, (start + end) / 2); // Check words against chosen word size_t current {start}; for (size_t i {start + 1}; i <= end; i++) { if (*words[i] < *words[start]) swap(words, ++current, i); } swap(words, start, current); if (current > start) sort(words, start, current - 1); if (end > current + 1) sort(words, current + 1, end); } Below adding also the code defined for swap function ( in case you think it's relevant) #include <iostream> #include <iomanip> #include <memory> #include <string> #include <string_view> #include <vector> using Words = std::vector<std::shared_ptr<std::string>>; void swap(Words& words, size_t first, size_t second); void sort(Words& words); void sort(Words& words, size_t start, size_t end); void extract_words(Words& words, std::string_view text, std::string_view separators); void show_words(const Words& words); size_t max_word_length(const Words& words); int main() { Words words; std::string text; const auto separators{" ,.!?\"\n"}; std::cout << "Enter a string terminated by *:" << std::endl; getline(std::cin, text, '*'); extract_words(words, text, separators); if (words.empty()) { std::cout << "No words in text." << std::endl; return 0; } sort(words); show_words(words); } void extract_words(Words& words, std::string_view text, std::string_view separators) { size_t start {text.find_first_not_of(separators)}; size_t end {}; while (start != std::string_view::npos) { end = text.find_first_of(separators, start + 1); if (end == std::string_view::npos) end = text.length(); words.push_back(std::make_shared<std::string>(text.substr(start, end - start))); } } void swap(Words& words, size_t first, size_t second) { auto temp{words[first]}; words[first] = words[second]; words[second] = temp; } This just swaps the addresses in words at indexes first and second.
What's going on is that the middle value of the array is being chosen as the pivot value and move "out of the way" to the start of the array: swap(words, start, (start + end) / 2); The loop then process all values from start+1 to end inclusive so that once it is complete all values from start to current inclusive are less than the pivot value. Note the loop is from start+1 so we never change the pivot value. size_t current {start}; for (size_t i {start + 1}; i <= end; i++) { if (*words[i] < *words[start]) swap(words, ++current, i); } But, at this point the pivot is in the wrong place. For the recursive calls to work the value at words[current] must be contain the pivot value. So it needs to be swapped from where we put it (words[start]) to current swap(words, start, current); It may be useful to think about what would happen if you were sorting an simple, small array like [3,2,1] You choose the middle value and move it to the start... [2,3,1] You move all values less than the pivot... [2,1,3] ^ | current You move the pivot back into place [1,2,3] You sort the portion before current, [1], and after current [3] which involves no change since they are single elements. Notice that if you had not moved the pivot into the correct place, sorting the subarrays would not yield the correct answer.
69,666,375
69,669,120
Clang compilation : "Cannot execute binary file"
I am new to the clang++ compiler flags. I have an issue regarding compilation. Here is my cmd: clang++ -I ../llvm-project/llvm/include -I ../llvm-project/clang/include -I ../llvm-project/build/tools/clang/include -I ../llvm-project/build/include -O3 -c $(llvm-config-7 --cxxflags) projectToTestHeadersBuilding.cpp -o projectToTestHeadersBuilding I am getting error: ./projectToTestHeadersBuilding: cannot execute binary file: Exec format error After execution I have projectToTestHeadersBuilding file. But I can not run executable. Can you please help me to understand how to get executable, so I can run it using ./projectToTestHeadersBuilding ?
In your initial command you use the -c flag which makes clang output an object file. This is part of a compiled program but not a complete executable, in order to get the final executable you must perform a linking step, usually with other object files. A simple compilation can be done as so: clang++ projectToTestHeadersBuilding.cpp -c -o projectToTestHeadersBuilding.o clang++ projectToTestHeadersBuilding.o -o projectToTestHeadersBuilding ./projectToTestHeadersBuilding Generally we do not need to explicitly pass all those -I flags you have passed. If they are needed with your setup, add them to the commands I've included above.
69,667,470
69,668,438
C# Program Can't Get Byte Array Back From A C++ COM Program
I can't seem to get a byte array in a C# program filled from a COM C++ program. The C# program includes a reference to the C++ DLL and is instantiated by: _wiCore = new WebInspectorCoreLib.WICore(); Actual call uint imageSize = *image byte count*; // set to size of image being retrieved var arr = new byte[imageSize]; _wiCore.GetFlawImage(1, 0, ref imageSize, out arr); C++ IDL: [id(5)] HRESULT GetFlawImage([in] ULONG flawID, [in] USHORT station, [in, out] ULONG *pImageSize, [out] BYTE *pImageBytes); This returns the image size correctly, but nothing in the array. I've also tried the signature (extra level of indirection for pImageBytes): [id(5)] HRESULT GetFlawImage([in] ULONG flawID, [in] USHORT station, [in, out] ULONG *pImageSize, [out] BYTE **pImageBytes); and in C# passing in an IntPtr but this returns the address of memory that contains the address of the image bytes, not the image bytes. Any thoughts on what I'm doing wrong?
There are multiple ways to pass an array back from C++. For example, you can use a raw byte array like you were trying to do. It works but it's not very practical from .NET because it's not a COM automation type which .NET loves. So, let's say we have this .idl: interface IBlah : IUnknown { HRESULT GetBytes([out] int *count, [out] unsigned char **bytes); } Here is a sample native implementation: STDMETHODIMP CBlah::GetBytes(int* count, unsigned char** bytes) { if (!count || !bytes) return E_INVALIDARG; *count = numBytes; *bytes = (unsigned char*)CoTaskMemAlloc(*count); if (!*bytes) return E_OUTOFMEMORY; for (unsigned char i = 0; i < *count; i++) { (*bytes)[i] = i; } return S_OK; } And a sample C# calling code (note the .NET type lib importer doesn't know anything beyond pointers when it's not a COM automation type, so it just blindly defines the argument as an IntPtr): var obj = (IBlah)Activator.CreateInstance(myType); // we must allocate a pointer (to a byte array pointer) var p = Marshal.AllocCoTaskMem(IntPtr.Size); try { obj.GetBytes(out var count, p); var bytesPtr = Marshal.ReadIntPtr(p); try { var bytes = new byte[count]; Marshal.Copy(bytesPtr, bytes, 0, bytes.Length); // here bytes is filled } finally { // here, we *must* use the same allocator than used in native code Marshal.FreeCoTaskMem(bytesPtr); } } finally { Marshal.FreeCoTaskMem(p); } Note: this won't work in out-of-process scenario as the .idl is not complete to support this, etc. Or you can use a COM Automation type such as SAFEARRAY (or a wrapping VARIANT). which also would allow you to use it with other languages (such as VB/VBA, Scripting engines, etc.) So, we could have this .idl: HRESULT GetBytesAsArray([out] SAFEARRAY(BYTE)* array); This sample native implementation (a bit more complex, as COM automation was not meant for C/C++, but for VB/VBA/Scripting object...): STDMETHODIMP CBlah::GetBytesAsArray(SAFEARRAY** array) { if (!array) return E_INVALIDARG; // create a 1-dim array of UI1 (byte) *array = SafeArrayCreateVector(VT_UI1, 0, numBytes); if (!*array) return E_OUTOFMEMORY; unsigned char* bytes; HRESULT hr = SafeArrayAccessData(*array, (void**)&bytes); // check errors if (FAILED(hr)) { SafeArrayDestroy(*array); return hr; } for (unsigned char i = 0; i < numBytes; i++) { bytes[i] = i; } SafeArrayUnaccessData(*array); return S_OK; } And the sample C# code is much simpler, as expected: var obj = (IBlah)Activator.CreateInstance(myType); obj.GetBytesAsArray(out var bytesArray);
69,668,237
69,668,647
C++ primer template universal reference and argument deduction
Hello I have this example from C++ primer: template <typename T> void f(T&& x) // binds to nonconstant rvalues { std::cout << "f(T&&)\n"; } template <typename T> void f(T const& x) // lvalues and constant revalues { std::cout << "f(T const&)\n"; } And here is my attempt to test the output: int main(){ int i = 5; int const ci = 10; f(i); // f(T& &&) -> f(int&) f(ci); // f(T const&) -> f(int const&) f(5); // f(T &&) -> f(int&&) f(std::move(ci)); // f(T&&) -> f(int const&&) cout << '\n'; } The output: f(T&&) f(T const&) f(T&&) f(T&&) In the book the version of f taking a forwarding reference is said to bind only to non-constant rvalues but in main I've passed a constant rvalue f(5) and f(std::move(ci)) but still the first version called. Is there a way to call the second version f(T const&) passing an rvalue? I know I can do it explicitly: f<int const&>(5); or f<int const&>( std::move(ci) ); but I want to know where can be called passing in an rvalue? Thank you! I think the comment after the forwarding reference version of f is not correct: f(T&&) // binds to nonconstant rvalues because it can be bound to constant rvalues so for example: f(std::move(ci)); // f(int const&&) and not f(int const&)
The comments in the book are, evidently, not entirely correct. When you have the two overloads available of template <typename T> void f(T&& x); template <typename T> void f(T const& x); both of them can always be called with any argument (with some exceptions that I'll omit here), but the second one will be preferred if the argument is a const lvalue. The first one will be preferred under all other circumstances thanks to the reference collapsing rules that apply when deducing template arguments. However, let's say that T is fixed by an enclosing class: template <class T> struct S { void f(T&& x); void f(T const& x); }; and let's assume that T is a non-const object type. Now, the situation is different because T is not deduced when calling f. The comments in the book seem to be referring to this latter situation, where the first S::f now may be called with non-const rvalues of type T but not with const rvalues of type T nor lvalues of (possibly const) T. The code, unfortunately, doesn't match up with the comments. Let's go back to the actual code that's in the book. As I said, the function taking T const& will be preferred when the argument is a const lvalue. Let's say that the argument is 5, but you want to explicitly call the second function even though it would not normally be selected. There are a few ways to do this. The one that is easiest to read is to actually turn the argument into a const lvalue: f((const int&)5); Your suggestion of f<const int&>(5) also works, but is a bit more confusing. The reason why it is confusing is that it requires the reader of the code to actually do the reference collapsing mentally and then remember that the first overload is less specialized than the second one. A third method is: static_cast<void(*)(int const&)>(&f)(5); Although this one is the hardest to read, the part before the (5) can be used whenever one particular overload needs to be extracted and bound to a function pointer.
69,668,421
69,668,610
Is there any alternative to using if walls instead of something else in C++?
I'm doing some C++ and my app accepts subcommands, for example ./my_app test 123. I'm semi-new to C++ and I can't find anything on the internet so I don't know haha. For example in python I'd do: #!/usr/bin/env python3 import sys def test(num): print(f"Test {num}") subcommands = {"test": test} subcommands[sys.argv[1](sys.argv[2]) any C++ eq to this? if so, should I use it or stick to if-else_if-else?
Have a look at std::map/std::unordered_map, for example: #include <iostream> #include <map> #include <string> void test(const std::string &value) { std::cout << "Test " << value << std::endl; } using cmdFuncType = void(*)(const std::string &); const std::map<std::string, cmdFuncType> subcommands = { {"test": &test} }; int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "usage: program command value" << std::endl; return 0; } auto iter = subcommands.find(argv[1]); if (iter == subcommands.end()) { std::cerr << "unknown command: " << argv[1] << std::endl; return 0; } iter->second(argv[2]); return 0; }
69,668,650
69,668,744
Prevent the application from crashing if one of the threads crashed
Is there any way to prevent main thread from crashing? I want the main thread to keep running after this memory access violation exception happens. std::thread { []() { for (auto i = 0; i < 10; ++i) { std::cout << "Hello World from detached thread!\n"; std::this_thread::sleep_for(std::chrono::milliseconds(500)); } std::cout << "Boom!\n"; *(int*)(0) = 42; } }.detach(); while (true) { std::cout << "Hello World!\n"; std::this_thread::sleep_for(std::chrono::milliseconds(500)); }
You could use sigaction to install a handler for SIGSEGV that kept that thread busy while main kept running. static void handler(int sig, siginfo_t* si, void* unused) { sleep(100000); // or something similar that's async-signal-safe // on your operating system } int main(int argc, char *argv[]) { struct sigaction sa; sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); sa.sa_sigaction = handler; if (sigaction(SIGSEGV, &sa, NULL) == -1) perror("sigaction"); ... This is of course incredible fragile. For example, if the thread that generated the SIGSEGV was holding a lock, then it won't be released so other threads can acquire it. As Ulrich points out, the usual approach to be tolerant to such things is to spawn child processes. Google Chrome famously started doing this for its browser tabs years back, helping it have a higher level of resiliency than other browsers at the time (who then had to catch up themselves). Modern Operating Systems make it very efficient to have multiple processes, whereas in older ones threads may have used massively less resources....
69,668,851
69,668,876
Access every member of base template class
When you use template inheritence, you have to explicitly specify what members of base template class you intend to use: template <typename T> class base { protected: int x; }; template <typename T> class derived : public base<T> { public: int f() { return x; } protected: using base<T>::x; }; What if base template has a lot of members? Can I avoid writing using declaration for each member and specify that I want every member of base template?
No. There's no such mechanism in the language.
69,669,173
69,692,403
How to create an algorithm to find all possible pairings (referring to the chinese postman problem)?
When trying to solve the chinese postman problem you will have to find minimum cost of all possible pairings of all odd vertexes in the graph and add found edges (pairings), which my question is almost about. How to implement an algorithm, which returns all possible pairings? or how to fix mine. I got a starting point, but am not able to go or think further. I tried looking on following topics but they did'nt help me unfortunetly. How should I generate the partitions / pairs for the Chinese Postman problem? or Find the pairings such that the sum of the weights is minimized? std::vector<std::vector<int>> Postman::pairOdd(std::vector<int> vertices) { std::vector<std::vector<int>> pairs; if (vertices.empty()) { return std::vector<std::vector<int>>(); } else { auto it = std::min_element(vertices.begin(), vertices.end()); int i = *it; vertices.erase(it); for (int index = 0; index < vertices.size(); index++) { int j = vertices[index]; vertices.erase(vertices.begin() + index); pairs.push_back(std::vector<int>{i, j}); std::vector<std::vector<int>> returnValue = pairOdd(vertices); pairs.insert(pairs.end(), returnValue.begin(), returnValue.end()); vertices.insert(vertices.begin(), j); } vertices.insert(vertices.begin(), i); } return pairs; } Output with std::vector<std::vector<int>> res = pairOdd(std::vector<int>{1,2,3,4,5,6}); for (auto v : res) { for (auto u : v) { std::cout << u; } std::cout << std::endl; } should be: 1 2 3 4 5 6 1 2 3 5 4 6 1 2 3 6 4 5 1 3 2 4 5 6 1 3 2 5 4 6 1 3 2 6 4 5 1 4 2 3 5 6 1 4 2 5 3 6 1 4 2 6 3 5 1 5 2 3 4 6 1 5 2 4 3 6 1 5 2 6 3 4 1 6 2 3 4 5 1 6 2 4 3 5 1 6 2 5 3 4 But is: 12 34 56 35 46 36 45 13 24 56 25 46 26 45 14 23 56 25 36 26 35 15 24 36 23 46 26 34 16 25 34 24 35 23 45 I can't quite fix how I insert into the vector. When looking at the output, you can see that it is almost right (ignoring the formatting). First line 12 34 45 is correct. Second 35 46, when it has to be 12 35 36, seems that only the first pair is missing, which you will notice applies to every pairings. Update: So I came up with another algorithm which seems to be promising, but instead of missing some pairs, I get duplicates. A solution is highly appreciated. If I find one myself I will post it. std::vector<std::vector<int>> Postman::aaa(std::vector<int> vertices, std::vector<int> list, int in1, int in2) { std::vector<std::vector<int>> pairs; if (vertices.empty()) { list.push_back(in1); list.push_back(in2); pairs.push_back(list); return pairs; } else { auto it = std::min_element(vertices.begin(), vertices.end()); int i = *it; vertices.erase(it); for (int index = 0; index < vertices.size(); index++) { int j = vertices[index]; vertices.erase(vertices.begin() + index); if (in1 != 0 && in2 != 0) { list.push_back(in1); list.push_back(in2); } std::vector<std::vector<int>> returnValue = aaa(vertices, list, i, j); pairs.insert(pairs.end(), returnValue.begin(), returnValue.end()); vertices.insert(vertices.begin(), j); } vertices.insert(vertices.begin(), i); } return pairs; } Output: 123456 12123546 1212123645 132456 13132546 1313132645 142356 14142536 1414142635 152436 15152346 1515152634 162534 16162435 1616162345
So I found a solution for the second algorithm I mentioned. The problem was I send the pair to the next recursion step to be then added in this step. So when you returned from a recursion step the pairing would still be in there. So I just deleted this pair, so the new one can be added. Instead of just returning an int vector I made an pair vector. Visualizing the return value better. I am willing to listen to any improvements to this algorithm or any good practices. I am willing to listen to any improvements to this algorithm or any good practises. std::vector<std::vector<std::pair<int, int>>> Postman::pairing(std::vector<int> vertices, std::vector<std::pair<int, int>> list) { std::vector<std::vector<std::pair<int, int>>> pairs; if (vertices.empty()) { pairs.push_back(list); return pairs; } else { auto it = std::min_element(vertices.begin(), vertices.end()); int i = *it; vertices.erase(it); for (int index = 0; index < vertices.size(); index++) { int j = vertices[index]; vertices.erase(vertices.begin() + index); std::pair<int, int> pair(i, j); list.push_back(pair); std::vector<std::vector<std::pair<int, int>>> r = pairing(vertices, list); list.erase(list.end() - 1); pairs.insert(pairs.end(), r.begin(), r.end()); vertices.insert(vertices.begin(), j); } } return pairs; } std::vector<std::vector<std::pair<int, int>>> a = pairing(vertices, std::vector<std::pair<int, int>>()); for (auto v : a) { for (auto p : v) { std::cout << '(' << p.first << ' ' << p.second << ')'; } std::cout << std::endl; }
69,669,265
69,669,390
Incorrect checksum for freed object - problem with allocation
I'm trying to write a class in c++ that creates a dynamic array and I'm encountering this problem malloc: Incorrect checksum for freed object 0x7f9ff3c05aa8: probably modified after being freed. Corrupt value: 0x2000000000000 I implemented three constructors (default, parametrized and copy) and I think this is the one causing problem because the code breaks here CTable::CTable(string sName, int iTableLen) { s_name = sName; cout<<"parametr: "<<s_name<<endl; c_table = new int[iTableLen]; i_table_lenghth=iTableLen; } I also have to write a method changing the size of the array and returning true in case of the success and false in case of the failure. Maybe this method is causing the problem so this is how I implemented it. bool CTable :: bSetNewSize(int iTableLen) { int size; if(iTableLen < 0) return false; else if(iTableLen>=i_table_length) size = i_table_length; if(iTableLen < i_table_length) size = iTableLen; int *cTable; cTable = new int[iTableLen]; for (int ii = 0; ii < size; ii++) { cTable[ii] = c_table[ii]; } delete [] c_table; c_table = cTable; return true; } edit: The problem wasn't in any of those parts of the code. The method that was supposed to clone the object was causing the error. It happened because I allocated the object statically instead of dynamically. Here is the fixed method: CTable* CTable::pcClone() { CTable *obj_clone; obj_clone = new CTable(*this); return obj_clone; }
The problem is that you deleted c_table in bSetNewSize() and didn't set a new value to it, but used it in a later call. I Think you meant to put a c_table = cTable; to the end of bSetNewSize() function, as 500 - Internal Server Erro commented. Also it is faster if you take the string parameter as a const string& to the constructor. Edit: are you sure abaut if(iTableLen >= 0) return false; This means that you actually resize only if iTableLen is negative. Didn't you mean if(iTableLen < 0) return false;
69,669,438
69,669,510
meaning of inline const char * operator*(AnEnumClass aclassinstance)
What is the meaning of the following? inline const char * operator*(AnEnumClass aclassinstance) { ... } Is it a function call operator overloading of the '*' operator or of the '()' operator? What does it accomplish and what is it used for?
inline // function should be marked as inline. const char * // function returns this operator * // function is the multiplication operator (AnEnumClass aClassInstance) // RHS argument to operator The operator takes as LHS whatever the encapsulating class is. You invoke it with: const char * aString = aClass * aEnum; (Given instances of the encapsulating class and the enumeration type.) Both Wikipedia and cppreference.com have a whole page on operator precedence and argumentation that you should peruse.
69,669,468
69,669,494
Can't change the value of private member of a class using friend class
So I was trying to learn how to change the value of the private class member using friend class, but the friend class cannot change the value of the main class, here is the code I have done, I am new in the world of coding, please help me out :) #include <iostream> using namespace std; class A { private: int marks; public: show_marks() { cout <<marks; } set_marks( int num ) { marks =num; } friend class B; }; class B{ public: show_A_marks(A teacher, int num){ teacher.marks= num; } }; int main(){ A teacher; teacher.set_marks(10); teacher.show_marks(); cout <<endl; B student; student.show_A_marks(teacher,20); teacher.show_marks(); } -This was supposed to print: 10 20 but is printing: 10 10
In the function: show_A_marks(A teacher, int num) You are passing teacher by value. You are making a copy of the value, and editing that copy. When the function returns, the copy is gone. You need to pass it by reference: show_A_marks(A& teacher, int num) // ^ reference to A see What's the difference between passing by reference vs. passing by value? for more info.
69,669,712
70,104,229
gem5: Use xbar stat in BaseCPU
I have created a new stat of type Formula in the xbar.cc/hh files. There I aggregate all the different transDist types. I'd like to use this newly created stat to compute another stat in the BaseCPU object. What is the best way to have access to it (i.e., allTransactions stat) from BaseCPU? Is there any way to make it globally accessible?
I ended up having a direct line of comminication between the xbar and the CPU objects. I implemented a function in the Xbar object that returns the statistic that I want, called getAllTrans(). From the CPU object, I call that function and get the value of the statistic. The communication is implemented using the code below. // Research (Memory Boundedness) void BaseCPU::getAllTrans() { allTrans = 0; Cache *dCache = dynamic_cast<Cache*> (this->getPort("dcache_port", 0).getPeer().getOwner()); if (dCache) { Cache *l2Cache = dynamic_cast<Cache*> (dCache->getPort("mem_side", 0).getPeer().getOwner()-> getPort("mem_side_ports", 0).getPeer().getOwner()); if (l2Cache) { CoherentXBar *membus = dynamic_cast<CoherentXBar*> (l2Cache->getPort("mem_side", 0).getPeer().getOwner()); if (membus) { allTrans = membus->getAllTrans(); } } else { CoherentXBar *membus = dynamic_cast<CoherentXBar*> (l2Cache->getPort("mem_side", 0).getPeer().getOwner()); if (membus) { allTrans = membus->getAllTrans(); } } } } The code above assumes that the dcache exists. Cache *dCache = dynamic_cast<Cache*> (this->getPort("dcache_port", 0).getPeer().getOwner()); The code above points to the dcache object from the cpu. The hops are like this: CPU -> CPU port to dCache -> Peer of that port (i.e., dCache port to the CPU) -> Owner of that port (i.e., the dCache itself). I build on top of every object connecting the CPU to the Xbar until I reach the XBar. This isn't the most elegant solution but I haven't found a better one for getting information from one gem5 object to another one.
69,670,234
69,670,254
Multiple constructors in a C++ LinkedList class: non-class type "ClassName"
I have a LinkedList constructor where I can pass in an array and it builds. Then I can add additional nodes to it by passing in integers. However, I also want the option to construct the LinkedList, without any arguments. In my LinkedList.h file I've tried to create a constructor that sets the first and last pointers. My add method should construct a Node. But in my main() function, when I try to use this constructor, I get an error: request for member ‘add’ in ‘l’, which is of non-class type ‘LinkedList()’ Same error for the other methods called in the main.cpp. Where am I going wrong in how I structure my two constructors? main.cpp #include <iostream> #include <string> #include "LinkedList.h" using namespace std; int main() { //int A[] {1, 2, 3, 4, 5}; //LinkedList l(A, 5); LinkedList l(); l.add(8); l.add(3); cout << l.getCurrentSize()<<endl; l.display(); return 0; } LinkedList.h #ifndef LINKED_LIST_ #define LINKED_LIST_ #include "IList.h" class LinkedList: public IList { protected: struct Node { int data; struct Node *next; }; struct Node *first, *last; public: //constructor LinkedList(){first=nullptr; last=nullptr;} LinkedList(int A[], int n); //destructor virtual ~LinkedList(); //accessors void display(); virtual int getCurrentSize() const; virtual bool add(int newEntry); }; #endif LinkedList.cpp #include <iostream> #include <string> #include "LinkedList.h" using namespace std; //constructor LinkedList::LinkedList(int A[], int n) { Node *t; int i = 0; first = new Node; first -> data = A[0]; first -> next = nullptr; last = first; for(i = 1; i < n; i++) { t = new Node; t -> data = A[i]; t -> next = nullptr; last -> next = t; last = t; } }; //destructor LinkedList::~LinkedList() { Node *p = first; while (first) { first = first -> next; delete p; p = first; } } void LinkedList::display() { Node *p = first; while(p) { cout << p -> data << " "; p = p -> next; } cout <<endl; } int LinkedList::getCurrentSize() const { Node *p = first; int len = 0; while(p) { len++; p = p -> next; } return len; } bool LinkedList::add(int newEntry) { Node *temporary; temporary = new Node; temporary -> data = newEntry; temporary -> next = nullptr; if (first==nullptr) { first = last = temporary; } else { last -> next = temporary; last = temporary; } return true; }
The problem has nothing to do with your constructors themselves. LinkedList l(); is a declaration of a function named l that takes no arguments, and returns a LinkedList. That is why the compiler is complaining about l being a non-class type. To default-construct a variable named l of type LinkedList, drop the parenthesis: LinkedList l; Or, in C++11 and later, you can use curly-braces instead: LinkedList l{};
69,670,273
69,670,363
My result is not truly random; How can I fix this?
float genData(int low, int high); int main(){ srand(time(0)); float num = genData(40, 100); cout << fixed << left << setprecision(2) << num << endl; return 0; } float genData(int low, int high) { low *= 100; high *= 100 + 1; int rnd = rand() % (high - low) + low; float newRand; newRand = (float) rnd / 100; return newRand; } I'm expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00 What I get is the same number with different decimal values, slowly increasing every time I run the program.
Wrong range int rnd = rand() % (high - low) + low; does not generate the right range. float genData(int low, int high) { low *= 100; // high *= 100 + 1; high = high*100 + 1; expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00 That is [40.00 ... 100.00] or 10000-4000+1 different values int rnd = rand() % (100*(high - low) + 1) + low*100; float frnd = rnd/100.0f; rand() weak here when RAND_MAX is small With RAND_MAX == 32767, int rnd = rand() % (high - low) + low; is like [0... 32767] % 6001 + 40000. [0... 32767] % 6001 does not provide a very uniform distribution. Some values coming up 6 times and others 7-ish.
69,670,395
69,677,306
Modern CMake: is there a way to build external projects using a CMakePresets.json?
Disclaimer: I'm rather new to C++ development and handling bigger projects, so this might be a wrong approach or tool, so I am very open to different ideas. I want to be able to provide a sort of package that is a collection of prebuilt libraries / binaries for different platforms, to be used with our other software. I need to be able to add or remove targets independently without breaking anything. (as in, adding a new library should be as simple as creating a new directory libname and configuring a CMakePresets.json inside) Ideally, my thoughts were: create a repository with build instructions for each dependency have a CI/CD pipeline building all the different versions we need (linux x64, linux ARM, windows) provide a platform to download specific versions So, what I had in mind was something like this: ├── A │   └── CMakePresets.txt ├── B │   └── CMakePresets.txt ├── C │   └── CMakePresets.txt └── CMakeLists.txt (or something like a python script) A B and C being my dependencies and the way I want to build them, by using a script in the root directory. I have spent a bit of time trying to figure out a way of doing this cleanly and cross platform but no avail. I thought of using a CMakeLists.txt because of the FetchContent / ExternalProject_Add commands but haven't really found a way to pass variables that is not tedious. This is very frustrating because this seems like something that should be relatively common but I feel like i'm missing something... Perhaps I should be using something like a Python script for some of the tasks (for example cloning the sources, copying the presets in the new directories and build from there) but I really liked the idea of doing everything with CMake, considering it handles a lot of the things I want (cloning a specific git tag etc) Thank you
You have just described the goal and approach of Conan. It interfaces well with CMake, and uses your "build recipe" approach. You, and Conan, recognize that C++ packages are inherently different from, say, Python or Javascript, in that they have endless variations due to compiler version, libc version, build configuration, etc. The solution is to provide the build instructions, and cache the built result at multiple layers: local machine, private server, public server. The result is that you specify the packages with the versions you want. The package will just be downloaded if any match the configuration you have specified, else it will be built and cached. With the right CI setup, you can upload the result to your internal server so that most of the time, the necessary packages are all pre-built. Last time I tried it, I struggled with a few things like transitive dependencies, and you might find yourself maintaining your own internal branches of the build recipes for all the packages you need, so that you can control those transitive dependencies.
69,670,432
69,670,555
IAR EW for ARM 8.50 and oddball char array literal behavior in C++
I'm having some strange constant/literal generation happening in IAR EW for ARM 8.50 when I declare a specific string: const char g_string[]="?????-??"; When I look at it in the debugger, it's actually generating the following in memory: ???~?? If I break the string up like so: const char g_string[]="?????""-??"; I get the expected/desired output: ?????-?? Am I running afoul of some known standard? or is this some IAR specific bug? FWIW, the literal generated with MSVC and Xtensa/Clang doesn't require this weirdness to get the eight characters as expected. Edit: const char g_string[]=R"foo(?????-??)foo"; seems to generate the appropriate characters in memory, so maybe it is a character encoding issue?
I found my issue, and it's pretty obscure to an american programmer. Trigraphs: https://stackoverflow.com/a/1995134/550235 I guess IAR has them enabled by default and the other compilers I'm using don't. And good luck searching on google for "string literals with ???"
69,670,850
69,671,012
c++ pushing pointer onto pointer priority queue causes immediate valgrind errors
I'm working on a Huffman code implementation in c++, however during the construction pushing a pointer onto a priority queue of class pointers is causing several of the type of valgrind error shown below: ==1158== at 0x40508E: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, Node*, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, long, Node*, nodeCompare) (stl_heap.h:182) ==1158== by 0x4034B5: void std::push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, nodeCompare) (stl_heap.h:221) ==1158== by 0x4027AB: std::priority_queue<Node*, std::vector<Node*, std::allocator<Node*> >, nodeCompare>::push(Node* const&) (stl_queue.h:499) ==1158== by 0x40177A: HuffmanCode::HuffmanCode(std::map<char, int, std::less<char>, std::allocator<std::pair<char const, int> > >) (huffmanCodes.cpp:117) ==1158== by 0x401F78: main (huffmanCodes.cpp:188) ==1158== Uninitialised value was created by a stack allocation ==1158== at 0x404EF3: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, Node*, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, long, Node*, nodeCompare) (stl_heap.h:178) Here's the code that I believe to be relevant to the issue: struct nodeCompare{ bool operator()(Node const& n1, Node const& n2){ return n1.getFreq() > n2.getFreq(); } }; // huffman code constructor, takes in character frequency map HuffmanCode::HuffmanCode(map<char, int> m){ // creates priority_queue, creates leafs and adds them to the queue priority_queue<Node*, vector<Node*>, nodeCompare> PQ; for(auto item: m){ Node* temp = new Node(item.first, item.second, true); PQ.push(temp); // causes error } // builds rest of tree upward until there is only a single element left (the root) while(PQ.size() > 1){ Node* temp = new Node(false); Node* left = PQ.top(); // causes error PQ.pop(); Node* right = PQ.top(); PQ.pop(); temp->setLChild(left); temp->setRChild(right); temp->setFreq(left->getFreq() + right->getFreq()); PQ.push(temp); // causes error } There's more code below this in the project, but I think this is what's causing the issue. Any help/insight would be appreciated.
shoud use pointer in nodeCompare struct nodeCompare{ bool operator()(Node* n1, Node* n2){ return n1->getFreq() > n2->getFreq(); } };
69,671,144
69,681,472
"exited with code 255" when trying to call __device__ function within __global__ function
I have the following test.hpp which declares test(): #pragma once #include "cuda_runtime.h" #include "device_launch_parameters.h" __host__ __device__ void test(); and test.cpp which defines test(): #include "test.hpp" __host__ __device__ void test() { } The following kernel.cu fails to compile (with exit code 255, and no other info): #include "test.hpp" __global__ void gpu(int x) { test(); // compiles just fine if I comment out this line } int main() { // can be called multiple times from host with no problems test(); test(); test(); return 0; } Like the comment states, if I remove the test() call from the gpu function, then the code compiles and runs without error. Why is this? How can I fix it? Edit: I should mention that my environment and compilation commands are correct, I managed to compile many of the sample projects without issues.
A comment by @Robert Crovella set me on the right track to solving this issue. I moved test.cpp into test.cu, and test.hpp to test.cuh. Then, I was able to enable separable compilation and device code linking by following these answers: https://stackoverflow.com/a/31006889/9816919 https://stackoverflow.com/a/63431536/9816919
69,671,155
69,671,238
C++ understanding constructors in inheritance
I'm currently learning C++ and would like to understand how constructors work in the context of inheritance. Here's my parent and child classes: #include <iostream> #include <string> enum COLOR { Green, Blue, White, Black, Brown, }; class Animal { protected: std::string _name; COLOR _color; public: Animal(): _name("unknown"){ std::cout << "constructing Animal object " << _name << std::endl; } Animal(std::string animalName, COLOR animalColor){ _name = animalName; _color = animalColor; std::cout << "constructing "; std::cout<< _color; std::cout << " Animal object " << _name << std::endl; } ~Animal(){ std::cout << "destructing Animal object " << _name << std::endl; } void speak(){ std::cout << "Animal speaks" << std::endl; } void move() const {} private: }; class Mammal: public Animal{ public: Mammal():Animal(){} Mammal(std::string mammalName, COLOR animalColor) :Animal(mammalName, animalColor){} ~Mammal(){ std::cout << "Destructing Mammal object " << _name << std::endl; } void eat() const{ std::cout << "Mammal eat" << std::endl; } private: }; class Dog: public Mammal{ public: Dog():Mammal(){} Dog(std::string dogName, COLOR dogColor) :Mammal(dogName, dogColor){} ~Dog(){ std::cout << "Destructing Dog object " << _name << std::endl; } private: }; And here is my main: int main(){ Animal a; a.speak(); Animal b("Boar", Blue); b.speak(); Mammal m("Monkey", Black); m.speak(); Dog d("Panda", Brown); std::cout << "Program exiting..." << std::endl; return 0; } This is how the output looks like: constructing Animal object unknown Animal speaks constructing 1 Animal object Boar Animal speaks constructing 3 Animal object Monkey Animal speaks constructing 4 Animal object Panda Program exiting... Destructing Dog object Panda Destructing Mammal object Panda destructing Animal object Panda Destructing Mammal object Monkey destructing Animal object Monkey destructing Animal object Boar destructing Animal object unknown Process returned 0 (0x0) execution time : 1.102 s What I am curious about is the destructor statements. It seems like if I add a destructor to a subclass (the same seems to go for constructors as well), you see that the destructor for the subclass runs, and then the destructor for the parent class also runs. Hence you have destructors in sequence Dog -> Mammal -> Animal. What does this mean? Does this mean that C++ has initialized 3 instanced objects just to make 1 Dog object? How does the flow of destructors (and constructors) work here?
There's a specific sequence used for constructing objects, and the inverse sequence is used for destroying them. For construction: Initialization order The order of member initializers in the list is irrelevant: the actual order of initialization is as follows: If the constructor is for the most-derived class, virtual bases are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists) Then, direct bases are initialized in left-to-right order as they appear in this class's base-specifier list Then, non-static data member are initialized in order of declaration in the class definition. Finally, the body of the constructor is executed And for destruction: Destruction sequence For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases. Even when the destructor is called directly (e.g. obj.~Foo();), the return statement in ~Foo() does not return control to the caller immediately: it calls all those member and base destructors first. Essentially construction builds the base class part first and then the derived class, and then destruction destroys it in reverse order. In your code, first the body of the Dog destructor executes, then the Mammal destructor executes. First its body executes, and then the destructor of the Animal base executes.
69,671,381
69,671,478
Why do I need the extra pair of curly braces when defining an array of pairs?
I'm sorry if this is a common question, I don't know how I'd search for it so I figured it best to just ask. I'm wanting to define an std::array of std::pairs in C++ to store SFML sf::IntRects in. I messed with it for like 10 minutes and finally realized that this compiles: std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{ { {sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2}} } }; Why do I need the extra set of curly braces around the pair itself? When I take them away: std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{ {sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2}} }; I get an error No suitable user-defined conversion from "sf::IntRect" to "std::pair<sf::IntRect,sf::IntRect>" exists What are these curly braces doing? I can't imagine what they'd be needed for.
std::array is a wrapper template around built-in C-style array. You may think of it as something like template <typename T, std::size_t N> class array { T arr[N]; ... }; Both std::array and built-in C-style array are aggregate types. You initialize it using aggregate initialization syntax. It would be something like std::array<T, N> array = {{ t0, t1, t2 }}; The outer {} is for std::array itself while the inner {} is for the wrapped built-in C-style array. Look at your example std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{ {sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2}} }; The error is more obvious when reformated as below. std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{{ sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2} }}; You are trying to initialize a pair with a single sf::IntRect object.
69,671,457
69,671,574
How does std::priority_queue accomplish O(log n) insertion?
The documentation for std::priority_queue states the complexity of the push operation as: Logarithmic number of comparisons plus the complexity of Container::push_back. And by default uses std::vector as the underlying container. However, push_back can only push elements to the end of the vector, while in a priority queue one might need to add elements somewhere in the middle of the vector, in which case all elements that follow have to be shifted to the right. In the worst case, when adding an element at the beginning, the push operation would incur the full O(n) cost. So how does the priority queue do it in logarithmic time? Why does it use a vector by default as opposed to some "easy insert and find" container such as a heap?
while in a priority queue one might need to add elements somewhere in the middle of the vector, in which case all elements that follow have to be shifted to the right No. The right shift does not occur. The new element is added to the end, at index i: O(1) Then its priority is compared to its parent at index i/2 and swapped if of higher priority. If a swap occurs, compare the next parent. Repeat above 2 steps until at at index 0. O(log(i))
69,671,465
69,672,202
Generating spheres with vertices and indices?
I'm currently working on an OpenGL project where I should currently generate spheres with vertices and indices. All vertices represent a point, and indices tells the graphic card to link 3 points as a triangle. Example : indices : {0,1,2} = it will make a triangle with the first, second and third point. I've managed to make a UV sphere with correct vertices, but I don't know how I can get indices. Here is my current result : And here is my code : Mesh ObjectFactory::createSphere() { // Texture loaded and binded to the shaderprogram Texture textures[]{ Texture("resources/pop_cat.png", "diffuse", 0, GL_RGBA, GL_UNSIGNED_BYTE), }; int numHorizontalSegments = 20; int numVerticalSegments = 20; Vertex vertices[numVerticalSegments * numVerticalSegments] = {}; GLuint indices[numVerticalSegments * numVerticalSegments] = {}; int i = 0; for (int h = 0; h < numHorizontalSegments; h++) { float angle1 = (h + 1) * M_PI / (numHorizontalSegments + 1); for (int v = 0; v < numVerticalSegments; v++) { i++; float angle2 = v * (2 * M_PI) / numVerticalSegments; float x = sinf(angle1) * cosf(angle2); float y = cosf(angle1); float z = sinf(angle1) * sinf(angle2); vertices[i] = Vertex{glm::vec3(x, y, z), glm::vec3(0.83f, 0.70f, 0.44f), glm::vec2(0.0f, 0.0f)}; indices[i] = i; } } // Store mesh data in vectors for the mesh std::vector<Vertex> verts(vertices, vertices + sizeof(vertices) / sizeof(Vertex)); std::vector<GLuint> ind(indices, indices + sizeof(indices) / sizeof(GLuint)); std::vector<Texture> tex(textures, textures + sizeof(textures) / sizeof(Texture)); // Create sphere mesh return {verts, ind, tex}; } Thank you a lot for your help !
You have created a sphere of vertices by calculating horizontal circles in multiple vertical layers, a UV sphere. Good. You are just adding indexes once for each vertex for a total of one index per vertex, that is not according to the concept. What you need to repeatedy do is finding the three indexes in your array of vertices, which make a usable triangle. Among other things it means that you will name the same vertex index multiple times. Mostly six times, because most of your vertices will be part of six triangles. At least one to the "upper left", one towards the "upper right", "lower left", "lower right"; while there are usually two double directions; e.g. two triangles to the upper right. "mostly six", because of edge cases like the "north pole" and "south pole"; which participate in many triangles and quads. Lets looks at a part of your UV sphere: V03----------V02----------V01---------V00 | | __/ | __/| | | __/ | c __/ | | | __/ | __/ | | | / f | / d | V13----------V12----------V11----------V10 | | __/ | e __/| | | a __/ | __/ | | | __/ | __/ | | | / b | / | V23----------V22----------V21----------V20 | | | | | | | | | | | | | | | | V33----------V32----------V31---------V30 You can see that for the quad in the middle (represented by two triangles "a" and "b"), you need six index entries, though it only has 4 of the vertices, and each of the vertices will be used even more often, from the other touching quads. For the triangle "a" you get indexes for the vertexes V11, V12, V22 (mind the orientation, depending on where you want the surface, thinking either always "counter clock" or always "clockwise" will get you where you only need a few tries to get the desired result). For the triangle "b" you get indexes for the vertexes V11, V22, V21. Also, the vertex V11 will have to be index again for the triangle "c" and "d", and "e", and "f"; for participating in six triangles or four quads. You managed to do your UV sphere fine, so I do not think that I need to provide the loop and selection code for getting that done. You managed to visualise the result of your UV sphere, just try and retry after checking the result.
69,671,475
69,672,838
Initialise unique_ptr inside class
I want to initialise the unique pointer inside class after declaration and I tried few ways but unable to resolve the errors.. template <typename T> struct Destroy { void operator()(T *t) const { t->destroy(); } }; class Test { std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime; public: Test() { /* the function createIRuntime() return type is *IRuntime. I tried using following but all the ways I got error: 1. runtime = std::make_unique<IRuntime, Destroy<IRuntime>> (createIRuntime()); 2. runtime = createIRuntime(); 3. runtime = std::unique_ptr<IRuntime, Destroy<IRuntime>> (createIRuntime()); Works fine if I do follow. std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime(createIRuntime()); */ /* how to initialize the unique pointer here*/ } };
runtime = std::make_unique<IRuntime, Destroy<IRuntime>> (createIRuntime()); Presumably IRuntime is an abstract class, which can't be constructed directly. But even if it could be constructed as-is, only the 1st template parameter specifies the type to create. The 2nd and subsequent template parameters specify the types of parameters for the constructor that is called. So, this statement is trying to call an IRuntime constructor that takes a Destroy<IRuntime> object as a parameter, passing a raw IRuntime* pointer to that parameter. No such constructor exists, so this fails to compile. runtime = createIRuntime(); std::unique_ptr does not have an operator= that takes a raw pointer, only a std::unique_ptr. std::unique_ptr has a constructor that takes a raw pointer, but that constructor is marked explicit. So this fails to compile, too. runtime = std::unique_ptr<IRuntime, Destroy<IRuntime>> (createIRuntime()); This is correct, and works just fine: Online Demo Another statement that works is: runtime.reset(createIRuntime()); Online Demo Also, since the code you showed is inside of another constructor, you can (and should) use that constructor's member initialization list: Test() : runtime(createIRuntime()) { } Online Demo
69,671,647
69,671,676
QObject Child Class Not Detecting QGuiApplication Event Loop
When I try to start a QTimer in a class derived from QObject, I get the warning QObject::startTimer: Timers can only be used with threads started with QThread and the timer doesn't run. Based on answer here, it appears that my custom class is not detecting QEventLoop created by QGuiApplication. My main.cpp ... classA objA; ... QGuiApplication app(argc, argv); ... My classA.h class classA : public QObject { Q_OBJECT private: QTimer m_oTimer; ... My classA.cpp classA::classA() { ... m_oTimer.start(100); ... } How can I fix that without creating a new QEventLoop?
I was able to fix the problem by changing the order of declaration of my classA and QGuiApplication. It appears that for any QObject child class to detect QGuiApplication Eventloop, it must be declared after QGuiApplication. My main.cpp: ... QGuiApplication app(argc, argv); ... classA objA; ...
69,671,944
69,674,237
How to stop variable symbols from being exported macOS
So I've got my main program that uses dlsym to find the symbols of 2 functions and a variable from a dylib and I have a variable that I don't want exported. My problem is that whether or not I use extern "C" for the variable dlsym will always find the variable Im not exporting, if I remove extern "C" from the functions they're not found by dlsym in the program but no matter what it'll always find the variables. Code for the dylib : export "C" char exported_var[2] = { 'a', '\0' }; extern "C" void dylib_quit() { ... } extern "C" void dylib_main() { ... } char hidden_var1[2] = { 'b', '\0' }; // dlsym will still find this char hidden_var2[2] = { 'b', '\0' }; // dlsym will still find this Code for the program : // I want to find all these and I can dylib_main_fn m_main_fn = (dylib_main_fn)dlsym(handle, "dylib_main"); dylib_quit_fn m_quit_fn = (dylib_quit_fn)dlsym(handle, "dylib_quit"); const char* exported_var = (const char*)dlsym(m_handle, "exported_var"); // And when I do this it will find the "hidden_var1" variable which I don't want happening // same with "hidden_var2" const char* hidden_var1 = (const char*)dlsym(m_handle, "hidden_var1"); So how am I able to hide the variable? Im using Xcode 11.3.1 on MacOS 10.14.6.
Hiding symbols using -fvisibility=hidden Exporting Code for the dylib : #define EXPORT extern "C" __attribute__((visibility("default"))) EXPORT char exported_var[2] = { 'a', '\0' }; EXPORT void dylib_quit() { ... } EXPORT void dylib_main() { ... } char hidden_var1[2] = { 'b', '\0' }; char hidden_var2[2] = { 'b', '\0' };
69,671,972
69,672,170
C++ How can I insert another loop or method to make 100 equivalent to 541?
My goal is to display the first list of prime numbers depending on user's input, when the user input 10, the program should display first 10 prime numbers which are 2 3 5 7 11 13 17 19 23 29. I'm thinking of having generated list from 2 which is the first prime number to 541 which is the 100th prime number then if the user input for example 100 then it will be equivalent to 2 upto 541. Will my algorithm works? currently I'm able to display prime numbers from 2 - 541 and stucked on implementing another loop for 1-100 input. #include <iostream> using namespace std; int main() { int N, counter, i, j, isPrime, n; cout << "List of prime numbers from 1-100: "; cin >> N; // if the user input 10 then the first 10 prime numbers are "2 3 5 7 11 13 17 19 23 29" // list of prime from 2-541 (or first list from 1-100 prime numbers) for (i = 2; i <= 541; i++) { isPrime = 0; for (j = 2; j <= i/2; j++) { if (i % j == 0) { isPrime = 1; break; } } if (isPrime == 0 && N != 101) cout << i << " "; } }
Your current algorithm doesn't work, because N is never modified. If the user inputs 101 then nothing will be printed, because if (isPrime == 0 && N != 101) will always be false. If the user inputs anything else then it will always print the first 100 primes. The key idea will be to count how many primes were found and break after the Nth prime. Or count down, how many primes we still need t ofind. The rough outline will be as follows: for (i = 2; N > 0; i++) { // Loop as long as we need to find more primes ... if(isPrime == 0) { std::cout << ... N--; // <- Found one prime, N-1 to go } }
69,672,020
69,673,451
cmake equivalent for MakeFile
I followed this answer to create a CMakeLists.txt for a simple Makefile Makefile CC = g++ INCFLAGS = -I/usr/local/include/embree3 LDFLAGS = -L"/usr/local/lib/" -lembree3 RM = /bin/rm -f all: $(CC) -o main main.cpp $(INCFLAGS) $(LDFLAGS) clean: $(RM) *.o main CMakeLists.txt cmake_minimum_required(VERSION 3.1.0) project(aaf_project_impl) include_directories(/usr/local/include/embree3) # -I flags for compiler link_directories(/usr/local/lib/) # -L flags for linker add_executable(main main.cpp) target_link_libraries(main embree) # -l flags for linking prog target The Makefile compiles properly and the executable runs without any issues. And to use the cmake file, I do the following (assuming I am in source directory) mkdir build cd build cmake .. make The make in step 4 throws the following error main.cpp:4:10: fatal error: 'embree3/rtcore.h' file not found #include <embree3/rtcore.h> ^~~~~~~~~~~~~~~~~~ 1 error generated. make[2]: *** [CMakeFiles/main.dir/main.cpp.o] Error 1 make[1]: *** [CMakeFiles/main.dir/all] Error 2 make: *** [all] Error 2 I installed embree from source by cloning the git repo. I am using Macbook M1 (MacOS Big Sur 11.5.1). I am very new to cmake (started using it a day ago) so I apologize if this is a rather silly question.
Ok, so following your answer to my comments, the problem is that since you starts your include instruction by embree3 (which make sense to avoid names conflict), cmake should have as include directory the directory containing the embree3 installation, not the embree3 folder itself. This is why include_directories(/usr/local/include) is working instead of include_directories(/usr/local/include/embree3).
69,672,051
69,672,211
wait() for thread made via clone?
I plan on rewriting this to assembly so I can't use c or c++ standard library. The code below runs perfectly. However I want a thread instead of a second process. If you uncomment /*CLONE_THREAD|*/ on line 25 waitpid will return -1. I would like to have a blocking function that will resume when my thread is complete. I couldn't figure out by looking at the man pages what it expects me to do #include <sys/wait.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> int globalValue=0; static int childFunc(void*arg) { printf("Global value is %d\n", globalValue); globalValue += *(int*)&arg; return 31; } int main(int argc, char *argv[]) { auto stack_size = 1024 * 1024; auto stack = (char*)mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); if (stack == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); } globalValue = 5; auto pid = clone(childFunc, stack + stack_size, /*CLONE_THREAD|*/CLONE_VM|CLONE_SIGHAND|SIGCHLD, (void*)7); sleep(1); //So main and child printf don't collide if (pid == -1) { perror("clone"); exit(EXIT_FAILURE); } printf("clone() returned %d\n", pid); int status; int waitVal = waitpid(-1, &status, __WALL); printf("Expecting 12 got %d. Expecting 31 got %d. ID=%d\n", globalValue, WEXITSTATUS(status), waitVal); return 0; }
If you want to call functions asynchronously with threads I recommend using std::async. Example here : #include <iostream> #include <future> #include <mutex> #include <condition_variable> int globalValue = 0; // could also have been std::atomic<int> but I choose a mutex (to also serialize output to std::cout) std::mutex mtx; // to protect access to data in multithreaded applications you can use mutexes int childFunc(const int value) { std::unique_lock<std::mutex> lock(mtx); globalValue = value; std::cout << "Global value set to " << globalValue << "\n"; return 31; } int getValue() { std::unique_lock<std::mutex> lock(mtx); return globalValue; } int main(int argc, char* argv[]) { // shared memory stuff is not needed for threads // launch childFunc asynchronously // using a lambda function : https://en.cppreference.com/w/cpp/language/lambda // to call a function asynchronously : https://en.cppreference.com/w/cpp/thread/async // note I didn't ues the C++ thread class, it can launch things asynchronously // however async is both a better abstraction and you can return values (and exceptions) // to the calling thread if you need to (which you do in this case) std::future<int> future = std::async(std::launch::async, [] { return childFunc(12); }); // wait until asynchronous function call is complete // and get its return value; int value_from_async = future.get(); std::cout << "Expected global value 12, value = " << getValue() << "\n"; std::cout << "Expected return value from asynchronous process is 31, value = " << value_from_async << "\n"; return 0; }
69,672,479
69,673,798
Generalizing binary left shift for octal representation without conversion
Currently I have a few lines of code for working with binary strings in their decimal representation, namely I have functions to rotate the binary string to the left, flip a specific bit, flip all bits and reverse order of the binary string all working on the decimal representation. They are defined as follows: inline u64 rotate_left(u64 n, u64 maxPower) { return (n >= maxPower) ? (((int64_t)n - (int64_t)maxPower) * 2 + 1) : n * 2; } inline bool checkBit(u64 n, int k) { return n & (1ULL << k); } inline u64 flip(u64 n, u64 maxBinaryNum) { return maxBinaryNum - n - 1; } inline u64 flip(u64 n, u64 kthPower, int k) { return checkBit(n, k) ? (int64_t(n) - (int64_t)kthPower) : (n + kthPower); } inline u64 reverseBits(u64 n, int L) { u64 rev = (lookup[n & 0xffULL] << 56) | // consider the first 8 bits (lookup[(n >> 8) & 0xffULL] << 48) | // consider the next 8 bits (lookup[(n >> 16) & 0xffULL] << 40) | // consider the next 8 bits (lookup[(n >> 24) & 0xffULL] << 32) | // consider the next 8 bits (lookup[(n >> 32) & 0xffULL] << 24) | // consider the next 8 bits (lookup[(n >> 40) & 0xffULL] << 16) | // consider the next 8 bits (lookup[(n >> 48) & 0xffULL] << 8) | // consider the next 8 bits (lookup[(n >> 54) & 0xffULL]); // consider last 8 bits return (rev >> (64 - L)); // get back to the original maximal number } WIth the lookup[] list defined as: #define R2(n) n, n + 2*64, n + 1*64, n + 3*64 #define R4(n) R2(n), R2(n + 2*16), R2(n + 1*16), R2(n + 3*16) #define R6(n) R4(n), R4(n + 2*4 ), R4(n + 1*4 ), R4(n + 3*4 ) #define REVERSE_BITS R6(0), R6(2), R6(1), R6(3) const u64 lookup[256] = { REVERSE_BITS }; All but the last one are easy to implement. My question is whether you know any generalization of the above functions for the octal string of a number, while working only on the decimal representation as above? Obviously without doing a conversion and storing the octal string itself (mainly due to performance boost) With flip() in octal code a would need to return the number with 8-x at the specified place in the string (for intstance: flip(2576, 2nd power, 2nd position) = 2376, i.e. 3 = 8-5). I do understand that in octal representation the any similar formulas as for rotate_left or flip are not possible (maybe?), that is why I look for alternative implementation. A possibility would be to represent each number in the octal string by their binary string, in other words to write: 29 --octal-> 35 --bin-> (011)(101) Thus working on sets of binary numbers. Would that be a good idea? If you have any suggestions for the code above for binary representation, I welcome any piece of advice. Thanks in advance and sorry for the long post!
my understand of rotate_left, do not know my understand of question is correct, hope this will help you. // maxPower: 8 // n < maxPower: // 0001 -> 0010 // // n >= maxPower // n: 1011 // n - maxPower: 0011 // (n - maxPower) * 2: 0110 // (n - maxPower) * 2 + 1: 0111 inline u64 rotate_left(u64 n, u64 maxPower) { return (n >= maxPower) ? (((int64_t)n - (int64_t)maxPower) * 2 + 1) : n * 2; } // so rotate_left for octadecimal, example: 3 digit octadecimal rotate left. // 0 1 1 -> 1 1 0 // 000 001 001 -> 001 001 000 // 4 4 0 -> 4 0 4 // 100 100 000 -> 100 000 100 // so, keep: // first digit of octadecimal number is: // fisrt_digit = n & (7 << ((digit-1) * 3)) // other digit of octadecimal number is: // other_digit = n - first_digit // example for 100 100 000: // first_digit is 100 000 000 // other_digit is 000 100 000 // so rotate left result is: // (other_digit << 3) | (first_digit >> ((digit-1) * 3)) // inline u64 rotate_left_oct(u64 n, u64 digit) { u64 rotate = 3 * (digit - 1); u64 first_digit = n & (7 << rotate); u64 other_digit = n - first_digit; return (other_digit << 3) | (first_digit >> rotate); } flip, for base 8, flip should be 7-x instead of 8-x: // oct flip same with binary flip: // (111)8 -> (001 001 001)2 // flip, // (666)8 -> (110 110 110)2 // this should be 7 - 1, not 8 - 1, indead. // inline u64 flip_oct(u64 n, u64 digit) { u64 maxNumber = (1 << (3 * digit)) - 1; assert(n <= maxNumber); return maxNumber - n; } // otc flip one digit // (111)8 -> (001 001 001)2 // flip 2nd number of it // (161)8 -> (001 110 001)2 // just need do xor of nth number of octadecimal number. // inline u64 flip_oct(u64 n, u64 nth, u64 digit) { return (7 << (3 * (nth - 1))) ^ n; } simple reverse. inline u64 reverse_oct(u64 n, u64 digit) { u64 m = 0; while (digit > 0) { m = (m << 3) | (n & 7); n = n >> 3; --digit; } return m; }
69,672,489
69,673,601
Sort an array by increasing frequency
Can anyone please explain how to deal with run time error? Line 1034: Char 34: runtime error: addition of unsigned offset to 0x607000000020 overflowed to 0x607000000018 (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34 Code fiddle class Solution { public: static bool cmp(pair<int,int> a, pair<int,int> b){ if(a.first<b.first) return true; if(a.first==b.first && a.second>b.second) return true; return false; } vector<int> frequencySort(vector<int>& nums) { int n = nums.size(); vector<int> res; vector<pair<int,int>> v(n); for(int i = 0;i<n;i++){ v[nums[i]].first++; v[nums[i]].second = nums[i]; } sort(v.begin(),v.end(),cmp); for(int i =0;i<n;i++){ for(int j =0;j<v[i].first;j++){ res.push_back(v[i].second); } } return res; } };
There're 2 problems: nums[i] is between -100 and 100. The vector v can't handle this case. This could be fixed easily with an offset of 100. vector<pair<int,int>> v(n);. Remember, this is a vector of frequency. It can't handle case like, for example, n = 5 but num[i] reach 50 or 100. This can also be fixed with a different const resize. New code: static bool cmp(pair<int,int> a, pair<int,int> b){ if(a.first<b.first) return true; if(a.first==b.first && a.second>b.second) return true; return false; } const int offset = 100; const int sz = 201; //because with an offset of 100, nums[i] could reach max 100+100=200 vector<int> frequencySort(vector<int>& nums) { int n = nums.size(); vector<int> res; vector<pair<int,int>> v(sz); for(int i = 0;i<n;i++){ v[nums[i]+offset].first++; v[nums[i]+offset].second = nums[i]+offset; } sort(v.begin(),v.end(),cmp); for(int i =0;i<sz;i++){ for(int j =0;j<v[i].first;j++){ res.push_back(v[i].second-offset); } } return res; } P.S: When doing programming problems, you should check the constraint: 1 <= nums.length <= 100 -100 <= nums[i] <= 100 and testcases. In this problem, the case: Input: nums = [-1,1,-6,4,5,-6,1,4,1] Output: [5,-1,4,4,-6,-6,1,1,1] that Leetcode provide could help you debug quicker.
69,673,623
69,677,131
malloc with C struct in C++
I am trying to write some tests in Catch2 (a C++ library) for a simple C library example and I am a little confused about how to initialize a C struct. My C header looks like this: struct node; And my C implementation cannot be simpler: struct node { int num; struct node* next; } Now, the problem is with the test (in C++): #include <catch2/catch.hpp> extern "C" { #include "node.h" } TEST_CASE("would it work?", "[foo]") { struct node* n = (struct node*) malloc(sizeof(struct node)); } The code will not compile because "struct node is an incomplete type". My question, in cases like this, how do you initialize C structs like that one in C++ code? what am I doing wrong?
Basically everything has already been said in the comments. You are just forward declaring the struct in the header. While it is best practice to use forward declarations to reduce include dependencies in headers that just need to know what something is (e.g. a struct) but not what it contains, it usually doesn't make much sense to forward declare the struct in the header that is actually supposed to define the struct itself. Using a struct (including malloc) beyond just needing to know that it is a pointer or a reference requires knowledge of the definition of that struct. Note that your C++ file only sees the contents of the included header; it doesn't see the contents of the C file. Therefore, the forward declaration in the header should replaced by the struct definition from the C file, making the C file obsolete in case it was really only intended to define the struct.
69,673,767
69,674,555
Template class with template method id
I am trying to create an identifier for my methods. This identifier is important for my work as it is in fact hardware synthesis. I have the following template class: template <int FF_COUNT, int FB_COUNT, int NEXT_COUNT> class Core{ public: ... template<int id> void consume_fb_events (hls::stream<event> feedback_stream [FB_COUNT] [FB_COUNT], weight w_mem [128*128]); } template <int FF_COUNT, int FB_COUNT, int NEXT_COUNT> template <int id> void Core<FF_COUNT, FB_COUNT, NEXT_COUNT>::consume_fb_events (hls::stream<event> feedback_stream [FB_COUNT] [FB_COUNT], weight w_mem [128*128]){ #pragma HLS INLINE off event e; for(int i = 0 ; i < FB_COUNT ; i++) { while (!feedback_stream[id][i].empty()) { feedback_stream[id][i].read(e); ap_uint<16> mem_offset = e << size_exp; consume_event (e, mem_offset, w_mem); } } } and this is my function call #define sth 8 for int i = 0 ; i < sth; i++ core[i].consume_fb_events<i>(....); I get the compilation error: ERROR: [HLS 200-70] Compilation errors found: In file included from c1/srnn.cpp:1: c1/srnn.cpp:197:14: error: no matching member function for call to 'consume_fb_events' core_1[i].consume_fb_events<i>(buffer_layer1_1, w1[i]); ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ c1/core.h:52:24: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'id' template<int id> void consume_fb_events (hls::stream<event> feedback_stream [FB_COUNT] [FB_COUNT], weight w_mem [128*128]); ^
What your looking for is a for loop at compile time. Because the template parameter must be a constexpr. I usually do it this way since you can't have for loops in constexpr functions: template<int i> struct MyFunc { MyFunc() { // do something with i core[i].consume_fb_events<i>(....); } }; template<int end, template <int I> class func, int i = 0> struct ForLoop { ForLoop() { func<i>{}; ForLoop<end, func, i+1>{}; } }; template<int end, template <int I> class func> struct ForLoop<end, func, end> { ForLoop() { } }; You can run any code in the constructor of MyFunc. You can then execute it like that: ForLoop<8, MyFunc>{}; where 8 is the number you would usually but at the i < ... part of the for loop You have to be careful with this, because this will only work for end up to about 900 (depending on the max template recursion depth). Or else you will get a compile time error. live example with std::cout EDIT: Since @SherifBadawy asked in a comment, you don't have to declare a struct/class MyFunc to do this, but I went with this approach because it makes the ForLoop more dynamic and you can reuse it multiple times. But if you'd like to this would also work: template<int i> void foo() { // code here } template<int end, int i = 0> struct ForLoop { ForLoop() { core[i].consume_fb_events<i>(....); // more code // or ... foo<i>(); ForLoop<end, func, i+1>{}; } }; template<int end> struct ForLoop<end, end> { ForLoop() { } }; To run ForLoop you would again do: ForLoop<8>{}; // without passing a class or function
69,674,058
69,674,233
"increment" `std::variant` alternative
I want to increment / decrement a std::variant's type alternative, essentially like so: using var_t = std::variant</*...*/>; var_t var; var.emplace< (var.index()+1) % std::variant_size<var_t> >(); // "increment" case, wrapping for good measure The problem here is that while emplace expects what clang's error message calls an "explicitly-specified argument", index does not appear to be constexpr. The obvious alternative would be something like this: switch(var.index()){ 0: var.emplace<1>(); break; 1: var.emplace<2>(); break; // ... variant_size<var_t>-1: var.emplace<0>(); } But that's what I personally would call "extremely ugly" and "a massive pain in the behind to maintain" (especially since I'd have to maintain two almost-copies of those blocks off-by-two for both incrementing and decrementing). Is there a better / "correct" way of doing this? In case that information is important in any way, I'm targeting C++20 on clang with libstdc++.
As usual, std::index_sequence might help: #include <variant> template <typename... Ts, std::size_t... Is> void next(std::variant<Ts...>& v, std::index_sequence<Is...>) { using Func = void (*)(std::variant<Ts...>&); Func funcs[] = { +[](std::variant<Ts...>& v){ v.template emplace<(Is + 1) % sizeof...(Is)>(); }... }; funcs[v.index()](v); } template <typename... Ts> void next(std::variant<Ts...>& v) { next(v, std::make_index_sequence<sizeof...(Ts)>()); } Demo Note: for prev, Is + 1 should be replaced by Is + sizeof...(Is) - 1.
69,674,448
69,675,522
Choose n distinct elements from a vector with probability inverse-proportional to their index
Given a vector and a certain number of elements n, I'm looking for a way to choose n distinct elements from a vector with probability inverse-proportional to their index. Example: std::vector v = {0, 1, 2, ... 998, 999}; n = 10; A potential set of chosen indices may be: {50, 200, 350, 500, 600, 700, 800, 850, 900, 950} Notes: The chosen indices need to be consistent between invocations. The same index cannot be chosen twice in the same invocation result. The density of indices from the beginning of the vector must be proportional to the density of indices from the end of the vector. I.e. the result {990 ... 999} is invalid for the given example. I'd prefer to use as much code as I can from the standard library rather than having to implement by myself. I may prefer a simple and working but less efficient solution over a complicated and efficient solution. Thanks
This paper describes a weighted random sampling method. Below is a C++ implementation. This is assigning a weight of 1 / index for a 1-based indexing of your data namespace views = std::ranges::views; std::random_device rd; std::mt19937 gen(rd()); // or whichever URBG you want std::uniform_real_distribution<double> dist(0, 1); std::vector<std::pair<double, std::size_t>> weighted_indexes; weighted_indexes.reserve(v.size()); for (auto i : views::iota(0u, v.size())) { auto k = std::pow(dist(gen), i + 1); weighted_indexes.emplace_back(k, i); } std::sort(weighted_indexes.begin(), weighted_indexes.end()); auto indexes = weighted_indexes | views::take(n) | views::values; auto selected_values = indexes | views::transform([&v](std::size_t i){ return v[i]; });
69,675,716
69,675,780
What is a legal definition of a pointer to a pointer to a const object?
I know from this answer that a pointer const int** z is supposed to be read as Variable z is [a pointer to [a pointer to a const int object]]. In my humble opinion, this would mean if z=&y then y should be a pointer to a const int object. However, the following code also compiles: int x=0; int const* y=&x; const int** z=&y; Why is an int const* object i.e. a const pointer to an int instead of a pointer to a const int acceptable to be the pointed object of z?
You are misunderstanding what the const refers to. A const always refers to the element to the left of it - unless it is the leftmost element itself, in which it refers to the element to the right. This means that int const * is a pointer to a const int, not a const pointer to int as you think. To get that, you would have to write int * const int const * and const int * are two ways of writing exactly the same: a pointer to a const int. You get it right if you read declarations from right to left. If const is the leftmost element, add a "that is" before it when reading. Ex: const int *: pointer to int that is const. int const *: pointer to const int. int * const: const pointer to int. const int * const: const pointer to int that is const. int const * const: const pointer to const int. Note that 1/2 are the same, and 4/5 are the same. 1 and 4 are called "west const" since const is on the west/left side, while 2 and 5 are called "east const".
69,675,810
69,675,945
Error when trying to access nativeLibraryDir
i'm trying to access getPackageManager.getApplicationInfo in jni. const char* getNativeLibPath(JNIEnv* env, jobject thiz, const char* libraryName, const char* packageName) { jclass contextClass = env->GetObjectClass(thiz); jmethodID getPackageManager = env->GetMethodID(contextClass, "getPackageManager", "()Landroid/content/pm/PackageManager;"); jobject instantiatePackageManager = env->CallObjectMethod(thiz, getPackageManager); jclass packageManagerClass = env->GetObjectClass(instantiatePackageManager); jmethodID getApplicationInfo = env->GetMethodID(packageManagerClass, "getApplicationInfo", "(Ljava/lang/String;I)Landroid/content/pm/ApplicationInfo;"); jobject instantiateApplicationInfo = env->CallObjectMethod(thiz, getApplicationInfo, packageName, 0); jclass applicationInfoClass = env->GetObjectClass(instantiateApplicationInfo); jfieldID nativeLibraryDir = env->GetFieldID(applicationInfoClass, "nativeLibraryDir", "Ljava/lang/String;"); auto string = (jstring) env->GetObjectField(instantiateApplicationInfo, nativeLibraryDir); const char* returnValue = env->GetStringUTFChars(string, nullptr); std::string appendedResult = std::string(returnValue) + std::string("/") + std::string(libraryName); return appendedResult.c_str(); } This is my code for it. However for some reason i'm getting this error: JNI ERROR (app bug): accessed stale WeakGlobal 0x74eecd21ff (index 1324143135 in a table of size 38) JNI DETECTED ERROR IN APPLICATION: use of deleted weak global reference 0x74eecd21ff Any help is appreciated!
Your code has at least three problems: You call getApplicationInfo with a const char * which expects a Java string: jobject instantiateApplicationInfo = env->CallObjectMethod(instantiatePackageManager, getApplicationInfo, env->NewStringUTF(packageName), 0); You need to call env->ReleaseStringUTF(returnValue) to release the string on the Java side You cannot return a const char * like that. Either return the std::string directly, or allocate memory with new char[] and let the caller free it.
69,676,420
69,676,660
Detect when 2 buttons are being pushed simultaneously without reacting to when the first button is pushed
I'm programming a robot's controller logic. On the controller there is 2 buttons. There is 3 different actions tied to 2 buttons, one occurs when only the first button is being pushed, the second when only the second is pushed, and the third when both are being pushed. Normally when the user means to hit both buttons they would hit one after another. This has the consequence of executing a incorrect action. Here is part of the code. while (true) { conveyor_mtr.setVelocity(22, pct); if (Controller1.ButtonL2.pressing() && Controller1.ButtonL1.pressing()) { conveyor_mtr.spin(fwd); // action 1 } else if (Controller1.ButtonL2.pressing()) { backGoalLift.setAngle(3); // action 2 } else if (Controller1.ButtonL1.pressing()) { backGoalLift.setAngle(55); // action 3 } else { conveyor_mtr.stop(hold); } task::sleep(20); //ms }
You could use a short timer, which is restarted every time a button press is triggered. Every time the timer expires, you check all currently pressed buttons. Of course, you will need to select a good timer duration to make it possible to press two buttons "simultaneously" while keeping your application feel responsive. You can implement a simple timer using a counter in your loop. However, at some point you will be happier with an event based architecture.
69,676,566
69,676,977
Passing object to << overload in alters data in object in C++
I'm trying to write a list class in C++, and I want to overload the << operator. However, when I pass the list object to the operator function, changes the values within the object. Other questions on StackOverflow have not helped resolve this. Superfluous code has been removed from the following: LinkedList.h: #include "Node.h" #include <iostream> class LinkedList { public: Node* head; Node* tail; int size; LinkedList(); void push(int data); friend std::ostream& operator<<(std::ostream& os, const LinkedList& list); }; This is LinkedList.cpp: #include "LinkedList.h" LinkedList::LinkedList() { head = nullptr; tail = nullptr; size = 0; } void LinkedList::push(int data) { Node newNode = Node(data); if (size == 0) { head = &newNode; tail = &newNode; } else { tail->next = &newNode; newNode.prev = tail; tail->next = &newNode; } size++; } std::ostream& operator<<(std::ostream& os, const LinkedList& list) { os << "["; os << list.head->data; os << "]"; return os; } (At the moment I just want it to output the data in the first element in the list) Here is the driver code: #include "LinkedList.h" int main() { LinkedList lis = LinkedList(); lis.push(5); std::cout << lis; } Please be gentle, I'm new to C++. Edits: Sorry, here is Node.h: #pragma once class Node { public: int data; Node* next; Node* prev; Node(int data); }; and Node.cpp #include "Node.h" Node::Node(int initdata) { data = initdata; next = nullptr; prev = nullptr; } I have also added the rest of LinkedList.cpp. The output I had expected from the above code is [5], since I am pushing 5 onto the list and then outputting it (or, at least, trying to).
You need to allocate new nodes with the new operator. This is your corrected code: #include <iostream> class Node { public: int data; Node *next; Node *prev; Node(int data); }; Node::Node(int initdata) { data = initdata; next = nullptr; prev = nullptr; } class LinkedList { public: Node *head; // <<<<<<<<<<< change here Node *tail; // <<<<<<<<<<< change here int size; LinkedList(); void push(int data); friend std::ostream& operator<<(std::ostream& os, const LinkedList& list); }; LinkedList::LinkedList() { head = nullptr; tail = nullptr; size = 0; } void LinkedList::push(int data) { Node *newNode = new Node(data); // <<<<<<<<<<< change here if (size == 0) { head = newNode; // <<<<<<<<<<< change here tail = newNode; // <<<<<<<<<<< change here } else { tail->next = newNode; newNode->prev = tail; tail->next = newNode; } size++; } std::ostream& operator<<(std::ostream& os, const LinkedList& list) { os << "["; os << list.head->data; os << "]"; return os; } int main() { LinkedList lis = LinkedList(); lis.push(5); std::cout << lis; }
69,676,937
69,677,135
I can't assign the value of a geometry point to a variable
I was trying to assign the value of a geometry point (it has x,y,z. All of them are float64. If you want to check it: http://docs.ros.org/en/noetic/api/geometry_msgs/html/msg/Point.html ) to a float64 variable. But when I compile the code the next error appears: error: request for member ‘data’ in ‘msg.nav_msgs::Odometry_std::allocator<void >::pose.geometry_msgs::PoseWithCovariance_std::allocator<void >::pose.geometry_msgs::Pose_std::allocator<void >::position.geometry_msgs::Point_std::allocator<void >::y’, which is of non-class type ‘const _y_type {aka const double}’ y = (msg.pose.pose.position.y).data; And the code is the following: #include <geometry_msgs/Point.h> #include <std_msgs/Float64.h> //Creo la variable con la informacion a publicar std_msgs::Float64 y; void controlMensajeRecibido(const geometry_msgs::Point& msg) { y = msg.y; } int main(int argc, char **argv) { //inicio comunicacion con sistema ROS ros::init(argc, argv, "coordenadas"); ros::NodeHandle nh; //Me suscribo al t ros::Subscriber sub = nh.subscribe("/ardrone/odometry/pose/pose/position", 1000, &controlMensajeRecibido); //creamos un objeto publicador ros::Publisher pub =nh.advertise<std_msgs::Float64>("/pid_y/state", 1000); pub.publish(y); //publico //cedemos control a ROS ros::spin(); } I don't know why it doesn't let me do it if the variable is the correct type. If anyone can help me it'll be amazing. Thank u
std_msgs::Float64 has a field "data" of type float64. Type of std_msgs::Float64 is not equal to field "y" of type float64 in geometry_msgs::Point. void controlMensajeRecibido(const geometry_msgs::Point& msg) { y.data = msg.y; }
69,677,048
69,677,231
Pointer to portions of array
I have an object of std::vector<std::array<double, 16>> vector entry Data [0] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [1] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [2] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [...] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 This is intended to represent a 4x4 matrix in ravel format. To not duplicate information I would like to create a pointer to extract a 3x3 from the above structure: I have mathematical operations for the 3x3 structure (std::array<double, 9>) someStructure: pointing to data elements [0, 1, 2, 4, 5, 6, 8, 9 10] The end goal is do: std::array<double, 9> tst = someStructure[0] + someStructure[1]; Is this doable? Best Regards
The 3x3 part is not contiguous, hence a pointer alone wont help here. You can write a view_as_3x3 that allows you to access elements of the submatrix of the 4x4 as if it was contiguous: struct view_as_3x3 { double& operator[](size_t index) { static const size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10}; return parent[mapping[index]]; } std::array<double, 16>& parent; }; Such that for example for (size_t = 0; i< 9; ++i) std::cout << " " << view_as_3x3{orignal_matrix}[i]; is printing the 9 elements of the 3x3 sub-matrix of the original 4x4 original_matrix. Then you could more easily apply your 3x3 algorithms to the 3x3 submatrix of a 4x4 matrix. You just need to replace the std::array<double, 9> with some generic T. For example change double sum_of_elements(const std::array<double, 9>& arr) { double res = 0; for (int i=0;i <9; ++i) res += arr[i]; return res; } To: template <typename T> double sum_of_elements(const T& arr) { double res = 0; for (int i=0;i <9; ++i) res += arr[i]; return res; } The calls are then std::array<double, 16> matrix4x4; sum_of_elements(view_as_3x3{matrix4x4}); // or std::array<double, 9> matrix3x3; sum_of_elements(matrix3x3); It would be nicer to use iterators instead of indices, however, writing the view with custom iterators requires considerable amount of boilerplate. On the other hand, I would not suggest to use naked std::arrays in the first place, but rather some my_4x4matrix that holds the array as member and provides iterators and more convenience methods.
69,678,651
69,678,940
free(): double free detected in tcache 2 on calling overloaded assignment operator
I'm working on a university project where we are to implement some of the c++ string class as Mystring. I'm working on the overloaded assignment operator and this is the current code for it: Mystring& Mystring::operator=(const Mystring& orig) { if(this != &orig) { delete ptr_buffer; len = orig.len; buf_size = orig.buf_size; ptr_buffer = orig.ptr_buffer; } return *this; } ptr_buffer, len. and buf_size are the three private variables for the Mystring class. This is my main program to test: void check (const Mystring s, const string name) { cout << "checking " << name << endl; cout << name << " contains " << s << endl; cout << name << " capacity() is " << s.capacity() << endl; cout << name << " length() is " << s.length() << endl; cout << name << " size() is " << s.size() << endl; cout << name << " max_size() is " << s.max_size() << endl << endl; } int main() { Mystring s1("Hi there!"); check(s1, "s1"); Mystring s2("Testing before assignment!"); check(s2, "s2"); s2 = s1; check(s2, "s2"); return 0; } This is what that outputs: checking s1 s1 contains Hi there! s1 capacity() is 10 s1 length() is 9 s1 size() is 9 s1 max_size() is 1073741820 checking s2 s2 contains Testing before assignment! s2 capacity() is 27 s2 length() is 26 s2 size() is 26 s2 max_size() is 1073741820 checking s2 s2 contains Hi there! s2 capacity() is 10 s2 length() is 9 s2 size() is 9 s2 max_size() is 1073741820 free(): double free detected in tcache 2 Process finished with exit code 134 (interrupted by signal 6: SIGABRT) As you can see, the assignment DOES work to set all the member variables, however I get a non-zero exit code and a free(): double free detected in tcache 2 error. What am I doing wrong and what does this error mean? I've confirmed that the exit code is coming from calling the assignment, because when I comment out s2 = s1;, it completes with exit code 0.
In this copy assignment operator Mystring& Mystring::operator=(const Mystring& orig) { if(this != &orig) { delete ptr_buffer; len = orig.len; buf_size = orig.buf_size; ptr_buffer = orig.ptr_buffer; } return *this; } there are at least two problems. If the array of characters pointed to by the pointer ptr_buffer was allocated dynamically then you have to use the operator delete [] instead of delete delete [] ptr_buffer; The second problem is that after this assignment ptr_buffer = orig.ptr_buffer; two pointers point to the same dynamically allocated memory. You need to allocate a new extent memory and copy there the string of the assigned object. The operator can be defined at least the following way Mystring & Mystring::operator =( const Mystring &orig ) { if(this != &orig) { if ( buf_size != orig.buf_size ) { delete [] ptr_buffer; ptr_buffer = new char[orig.buf_size]; buf_size = orig.buf_size; } len = orig.len; strcpy( ptr_buffer, orig.ptr_buffer ); // or if the class does not store strings then // memcpy( ptr_buffer, orig.ptr_buffer, len ); } return *this; }
69,678,689
69,698,394
Address Sanitizer in MSVC: why does it report an error on startup?
I'm trying a project that uses Qt with MSVC 2019 with Address Sanitizer. I built with Address Sanitizer the project, but didn't rebuild all libs, including Qt. it crashes inside Qt in resource initialization (with qRegisterResourceData in the call stack). Is this: Misuse of address sanitizer, like, I should rebuild Qt DLLs with it too? An issue in Qt I should investigate deeper? Known Qt issue? I've recreated the issue in Widget application created by Wizard by default. The call stack is as follows: > KernelBase.dll!RaiseException() Unknown QtWidgetsApplication1.exe!__vcasan::OnAsanReport(const char * description, const char * report, bool __throw) Line 602 C++ QtWidgetsApplication1.exe!__vcasan::ReportCallback(const char * szReport) Line 325 C++ clang_rt.asan_dbg_dynamic-x86_64.dll!__asan::ScopedInErrorReport::~ScopedInErrorReport(void) Unknown clang_rt.asan_dbg_dynamic-x86_64.dll!__asan::ReportMallocUsableSizeNotOwned(unsigned __int64,struct __sanitizer::BufferedStackTrace *) Unknown clang_rt.asan_dbg_dynamic-x86_64.dll!__asan::asan_malloc_usable_size(void const *,unsigned __int64,unsigned __int64) Unknown clang_rt.asan_dbg_dynamic-x86_64.dll!_recalloc() Unknown ucrtbased.dll!_register_onexit_function::__l2::<lambda>() Line 112 C++ ucrtbased.dll!__crt_seh_guarded_call<int>::operator()<void <lambda>(void),int <lambda>(void) &,void <lambda>(void)>(__acrt_lock_and_call::__l2::void <lambda>(void) && setup, _register_onexit_function::__l2::int <lambda>(void) & action, __acrt_lock_and_call::__l2::void <lambda>(void) && cleanup) Line 204 C++ ucrtbased.dll!__acrt_lock_and_call<int <lambda>(void)>(const __acrt_lock_id lock_id, _register_onexit_function::__l2::int <lambda>(void) && action) Line 980 C++ ucrtbased.dll!_register_onexit_function(_onexit_table_t * table, int(*)() function) Line 149 C++ Qt5Cored.dll!_onexit(int(*)() function) Line 267 C++ Qt5Cored.dll!atexit(void(*)() function) Line 275 C++ Qt5Cored.dll!QPropertyAnimation::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState) Line 268 C++ Qt5Cored.dll!QAbstractAnimationPrivate::setState(QAbstractAnimation::State newState) Line 991 C++ Qt5Cored.dll!QAbstractAnimation::start(QAbstractAnimation::DeletionPolicy policy) Line 1362 C++ Qt5Widgetsd.dll!QWidgetAnimator::animate(QWidget * widget, const QRect & _final_geometry, bool animate) Line 114 C++ Qt5Widgetsd.dll!QToolBarAreaLayout::apply(bool animate) Line 936 C++ Qt5Widgetsd.dll!QMainWindowLayoutState::apply(bool animated) Line 687 C++ Qt5Widgetsd.dll!QMainWindowLayout::applyState(QMainWindowLayoutState & newState, bool animate) Line 2759 C++ Qt5Widgetsd.dll!QMainWindowLayout::setGeometry(const QRect & _r) Line 1979 C++ Qt5Widgetsd.dll!QLayoutPrivate::doResize() Line 596 C++ Qt5Widgetsd.dll!QLayout::activate() Line 1119 C++ Qt5Widgetsd.dll!QWidgetPrivate::setVisible(bool visible) Line 8083 C++ Qt5Widgetsd.dll!QWidget::setVisible(bool visible) Line 8044 C++ Qt5Widgetsd.dll!QWidget::show() Line 7670 C++ QtWidgetsApplication1.exe!main(int argc, char * * argv) Line 9 C++ QtWidgetsApplication1.exe!WinMain(HINSTANCE__ * __formal, HINSTANCE__ * __formal, char * __formal, int __formal) Line 97 C++ QtWidgetsApplication1.exe!invoke_main() Line 107 C++ QtWidgetsApplication1.exe!__scrt_common_main_seh() Line 288 C++ QtWidgetsApplication1.exe!__scrt_common_main() Line 331 C++ QtWidgetsApplication1.exe!WinMainCRTStartup(void * __formal) Line 17 C++ kernel32.dll!BaseThreadInitThunk() Unknown ntdll.dll!RtlUserThreadStart() Unknown The output: Address 0x01c416f8eda0 is a wild pointer. SUMMARY: AddressSanitizer: bad-malloc_usable_size (C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\clang_rt.asan_dbg_dynamic-x86_64.dll+0x18004e63a) in _asan_wrap_GlobalSize+0x4b948 Address Sanitizer Error: bad-malloc_usable_size
The issue is load order. Qt happens to load before ASan and load C/C++ runtime before ASan DLLs loaded. Qt performs some initialization. So the memory is malloced without ASan knowledge, and later ASan sees realloc without prior malloc, which it reports. Building Qt with ASan should resolve the issue, I have not tried that, as I have found a workaround that does not involve Qt rebuild. The workaround: just make Qt DLLs import ASan DLLs. For me it is via the following commands: setdll /d:clang_rt.asan_dbg_dynamic-x86_64.dll <path_to_deployed_debug_app>\Qt5Cored.dll setdll /d:clang_rt.asan_dynamic-x86_64.dll <path_to_deployed_release_app>\Qt5Core.dll setdll is a tool from Detours library that may be obtained from https://github.com/microsoft/Detours and then built using nmake. clang_rt.asan_dynamic-x86_64.dll and clang_rt.asan_dbg_dynamic-x86_64.dll should be available directly or from %path% when executing this, the most convenient way is to execute the command from VS Tools command prompt.
69,678,864
69,679,086
Safe way to use string_view as key in unordered map
My type Val contains std::string thekey. struct Val { std::string thekey; float somedata; } I would like put my type in an unordered map, with thekey as key. For memory and conversion avoidance reasons I would like to have std::string_view as key type. Is it possible to have the key created to point to val.thekey, while using unique_ptr ? std::unique_ptr<Val> valptr = ...; std::unordered_map<std::string_view,std::unique_ptr<Val>> themap; themap[std::string_view(valptr->thekey)] = std::move(valptr); // is this ok and safe?
Safe way to use string_view as key in unordered map In general there isn't one, because the storage underlying the view might change at any time, invalidating your map invariants. Associative containers generally own a const key precisely to avoid this. In your specific case it makes much more sense to use std::unordered_set<Val, ValKeyHash, ValKeyEqual> with suitable hash and equality functors. Edit, these suitable functors are simply struct ValKeyHash { std::size_t operator() (Val const &v) { return std::hash<std::string>{}(v.thekey); } }; struct ValKeyEqual { bool operator() (Val const& a, Val const& b) { return a.thekey == b.thekey; } }; Obviously this leaves us with the slightly unhappy requirement of using a temporary Val{key, dummy_data} for lookups, at least until we can use the C++20 transparent/projected version in the other answer.
69,679,026
69,680,901
Inserting a node in LinkedList is giving segmentation error
struct Node { int data; Node * next; Node (int x) { data=x; next=NULL; } }; Node * insertInSorted(Node * head, int data) { Node* temp = new Node(data); if (head == NULL){ return temp; } if (data < head->data){ temp->next = head return temp; } Node* curr = head; while (curr->next->data < data && curr->next != NULL){ curr = curr->next; } temp->next = curr->next; curr->next = temp; return head; } Hi, I've recently learned C++ and have been practicing LinkedList, this question is simple all I've to do is insert an element at its correct position while maintaining the sorted order. My question is why am I getting segmentation fault. I noticed that in the while loop if I flip the order from while (curr->next->data < data && curr->next != NULL) to while (curr->next != NULL && curr->next->data < data) segmentation error does not occur. Can someone please help me understand this problem?
This while loop while (curr->next->data < data && curr->next != NULL){ curr = curr->next; } can invoke undefined behavior because there is no check whether curr->next is equal to nullptr before accessing the data member curr->next->data. You need to exchange the operands of the logical AND operator like while (curr->next != NULL && curr->next->data < data ){ curr = curr->next; } In any case the function can be written without checks of numerous conditions the following way if to use pointer to pointer. Node * insertInSorted( Node *head, int data ) { Node *temp = new Node( data ); Node **current = &head; while ( *current && !( data < ( *current )->data ) ) { current = &( *current )->next; } temp->next = *current; *current = temp; return head; } Pay attention to that you could pass the pointer to the head node to the function by reference. In this case there is no need to return the pointer to the head node from the function. The user of the original function can forget to assign the returned pointer from the function to the pointer within the caller of the function. So a more safer function definition can look the following way void insertInSorted( Node * &head, int data ) { Node *temp = new Node( data ); Node **current = &head; while ( *current && !( data < ( *current )->data ) ) { current = &( *current )->next; } temp->next = *current; *current = temp; }
69,679,356
69,683,917
How to read and write large std::vector<std::vector<float>> to file in C++
In the constructor of my program I am generating a very large lookup table of 2048 * 2048 floats using nested std::vector<std::vector<float>>. The lookup table is always the same each time, so I'd like to write this table to a file to save recalculating it. What is the best way to achieve this? Is it best to write the values to a big header, or is it wiser to save a binary copy of the object? Thanks in advance! Edit: If it is of any conceqence, perhaps it's related to the time take to allocate the memory which is being done with the following pattern: dataStructure.resize(numberOfRows); for (int i = 0; i < numberOfRows; i++) dataStructure[i].resize(numberOfColumns); Where datastructure is a std::vector<std::vector<float>>
The answer in this case has been to optimise the lookup table generation. I was doing much, much more work than was required, and now load times are practically instant. For those in the future looking at this thread with a similar problem, there is great general advice in the commments. Thanks to the attention of all who contributed!
69,679,649
69,679,884
c++ polymorphic method defined in derived class matches type that should match to the parent
I'm experimenting with this code class Base { public: virtual void foo(int) { // void foo(int) { cout << "int" << endl; } }; class Derived : public Base { public: void foo(double) { cout << "double" << endl; } }; int main() { Base* p = new Derived; p->foo(2.1); Derived d; d.foo(2); // why isn't this double? return 0; } It's also available in online editor here https://onlinegdb.com/s8NwhfG_Yy I'm getting int double I don't understand why d.foo(2) calls the double version. Since Derived inherits the int method and has its own double method, wouldn't polymorphism dictate that 2 be matched to the parent? Thanks.
Polymorphism as in calling virtual methods is orthogonal to symbol and overload resolution. The former happens run-time, the rest at compile-time. object->foo() always resolves the symbol at compile-time - member variable with overloaded operator() or a method. virtual only delays selecting "the body" of the method. The signature is always fixed, including the return value of course. Otherwise the type system would break. This is one of the reasons why there cannot be virtual function templates. What you are actually experiencing is name hiding and overload resolution. For Base* p; p->foo(2.1), the list of possible symbol candidates is only Base::foo(int). The compiler cannot know that p points to Derived (in general) because the choice must be done at compile time. Since int is implicitly convertible to double, foo(int) is chosen. Because the method is virtual, if Derived were to provide its own foo(int) override, it would have been called instead of Base::foo(int) at run-time. For Derived*d; d->foo(2), the compiler first looks for symbol foo in Derived. Since there is foo(double) which is valid as foo(2), it is chosen. If there was no valid candidate, only then the compiler would look into base classes. If there was Derived::foo(int), possibly virtual, the compiler would choose this instead because it is a better match. You can disable the name hiding by writing class Derived: public Base{ using Base::foo; }; It injects all Base::foo methods into Derived scope. After this, Base::foo(int) (now really Derived::foo(int)) is chosen as the better match.
69,680,005
69,680,017
Using two types with one template definition
Is it possible to use two different types, one is a subtype of the other, with one template definition? Something like: template<typename T> void foo(T a, T::bar b);
You would need one more usage of typename template <typename T> void foo(T a, typename T::bar b); because bar is a "dependent type" of T. See here for more details.
69,680,174
69,681,167
Shared pointer to array in pool-allocated memory
I am working on writing a fixed-capacity, copy-on-write "string" class which is capable of using Allocators for its memory allocations. Eventually, I want to be able to have these "strings" use a memory pool which returns fixed-sized chunks of memory. If the "capacity" of the string being created is less than the pool chunk size, the extra memory is "wasted." If the capacity is larger, this is an assert failure (i.e., you cannot create a string that is larger than the pool chunk size). To implement the copy-on-write behavior, I am trying to figure out how to use this pool to create shared pointers to arrays within this chunk of memory. I can't just use std::shared_ptr(pool.allocate(...)) because I need both the control block AND memory to be allocated in the SAME chunk of memory allocated by the pool. Visually, the memory should look like: ---------------------------------------------------- | Memory Pool Chunk | |--------------------------------------------------| | Control Block | Array of characters ... | UNUSED | ---------------------------------------------------- From my research, I can see that this is example what std::make_shared does; it allocates both the control block and object in a contiguous chunk of memory. However, it also looks like you can't allocate an arbitrarily-sized array using std::make_shared. You can use it to allocate std::array objects, but you of course need to know the size at compile time, whereas the size of the array I want to allocate is known at run-time. My next thought was to simply implement my own, stripped down shared pointer. Since I don't need weak pointers or custom deleters, this seems like I should just be able to store an allocator and reference count in some sort of "header" in the memory I get back from the pool. Then, the rest of the memory can be used for the array. However, I cannot figure out how you are supposed to store an allocate within a header and later use the allocator to, for example, make a deep copy of the data. Could someone help either: a) Direct me towards a way of doing this using the already build-in standard library constructs OR b) Help me figure out how to implement my own shared pointer that meets the requirements above
I would avoid trying to use shared_ptr for this. Not just because you need C++20 in order for allocate_shared to work on arrays, but also because it is inefficient for your embedded needs. The shared_ptr control block has two reference counts in order to allow for weak pointers. Your particular use case doesn't need weak pointers, so you only need one count. The control block has a pointer to the object it manages. In your use case, the array is always right after the control block. The control block has a copy of the allocator, but your string class already has that, so it doesn't need it in the control block. And so on. You should use a hand-rolled solution so that you can minimize the amount of book-keeping memory, thus maximizing the amount of actual string storage you get.
69,680,293
69,680,591
How to start a thread in another function but inside IF statement
I have a function that I want to run it inside another function, so the main function I have , have a while loop running and the other function outside also have a while loop, and I wanna run both together without any of each other interrupting each other, so the main function will keep its main while loop running normally and the other function. I want it to run as a thread in the background but only inside IF statement and its also a while loop and only if this IF statement was TRUE it will start the thread and will also run while the main loop function running I will show here the problem by example: void MatchChecker() { while (1) { if (g_pOBJ->checkInMatch() == 2) { std::cout << "In Match! " << std::endl; } } void mainFunc() { while (1) { if (checkIngame() == true) { std::thread checker(MatchChecker); checker.join(); break; } } while (1) { std::cout << "Im doing some stuff here in this main loop" << std::endl; someOtherThread.join(); } } so the main problem is with the checker.join(); when I add it inside that if , the second loop doesn't start and its stuck with the mainchecker loop, and I cant put the checker.join inside the other loop because its not defined, so what can I do to solve my problem? any suggestions?
ITNOA You can change your code like below void MatchChecker() { while (1) { if (g_pOBJ->checkInMatch() == 2) { std::cout << "In Match! " << std::endl; } } void mainFunc() { std::thread checker; while (1) { if (checkIngame() == true) { checker = std::thread(MatchChecker); break; } } while (1) { std::cout << "Im doing some stuff here in this main loop" << std::endl; someOtherThread.join(); } if (checker.joinable()) checker.join(); } In the above code, I separate thread definition and running by define empty thread, and start when I needed. For gracefully joining thread, in the end of function I check thread is joinable or not, if it is joinable, I try to join it.
69,680,725
69,680,928
C++ 2D algorithm code is reading the array wrong
Like the title said, my code is reading a 2D array entirely wrong. const int WINNING_ROWS[8][3] = { (0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6) }; Above is my 2D array of numbers. My program doesn't seem to be able to read it properly. For example, if I were to ask for row 2, item 1, I would expect 7, it, however, instead gives me 6. Here is a list of rows and item requests I have done to try and figure out what has gone wrong here. row 0, item 0, expected outcome 0, actual outcome 2 row 3, item 2, expected outcome 6, actual outcome 0 row 1, item 0, expected outcome 3, actual outcome 6 row 5, item 1, expected outcome 5, actual outcome 0 row 8, item 2, expected outcome 6, actual outcome 13629648 row 7, item 2, expected outcome 6, actual outcome 0 for reference, here is the code I have been using to call the items from the array cout << WINNING_ROWS[7][2] << endl; Edit 1: ignore the item in bold, that was a mistake on my part when testing my code. Edit 2: my question has been answered.
const int WINNING_ROWS[8][3] = { (0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6) }; That doesn't mean what you think it does. The (0,1,2) is not a row of three elements, but a single integer computed using the comma operator. 0,1,2 evaluates to 2. You need to use the proper {...} braces instead of parenthesis, or leave them out completely. Suggest also you change const to constexpr.
69,680,876
69,680,988
Construction of lambda object in case of specified captures in C++
Starting from C++20 closure types without captures have default constructor, see https://en.cppreference.com/w/cpp/language/lambda: If no captures are specified, the closure type has a defaulted default constructor. But what about closure types that capture, how can their objects be constructed? One way is by using std::bit_cast (provided that the closure type can be trivially copyable). And Visual Studio compiler provides a constructor for closure type as the example shows: #include <bit> int main() { int x = 0; using A = decltype([x](){ return x; }); // ok everywhere constexpr A a = std::bit_cast<A>(1); static_assert( a() == 1 ); // ok in MSVC constexpr A b(1); static_assert( b() == 1 ); } Demo: https://gcc.godbolt.org/z/dnPjWdYx1 Considering that both Clang and GCC reject A b(1), the standard does not require the presence of this constructor. But can a compiler provide such constructor as an extension?
Since this is tagged language-lawyer, here's what the C++ standard has to say about all this. But what about closure types that capture, how can their objects be constructed? The actual part of the standard that cppreference link is referencing is [expr.prim.lambda.general] - 7.5.5.1.14: The closure type associated with a lambda-expression has no default constructor if the lambda-expression has a lambda-capture and a defaulted default constructor otherwise. It has a defaulted copy constructor and a defaulted move constructor ([class.copy.ctor]). It has a deleted copy assignment operator if the lambda-expression has a lambda-capture and defaulted copy and move assignment operators otherwise ([class.copy.assign]). However, clauses 1 and 2 say: The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below. The closure type is not an aggregate type. An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing: [unrelated stuff] Which means that (apart from the unrelated exceptions), the described interface of the lambda as stated is exhaustive. Since no other constructors than the default one is listed, then that's the only one that is supposed to be there. N.B. : A lambda may be equivalent to a class-based functor, but it is not purely syntactical sugar. The compiler/implementation does not need a constructor in order to construct and parametrize the lambda's type. It's just programmers who are prevented from creating instances by the lack of constructors. As far as extensions go: But can a compiler provide such constructor as an extension? Yes. A compiler is allowed to provide this feature as an extension as long as all it does is make programs that would be ill-formed functional. From [intro.compliance.general] - 4.1.1.8: A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this document. Having done so, however, they can compile and execute such programs. However, for the feature at hand, MSVC would be having issues in its implementation as an extension: It should be emmiting a diagnostic. By its own documentation, it should refuse the code when using /permissive-. Yet it does not. So it looks like MSVC is, either intentionally or not, behaving as if this was part of the language, which is not the case as far as I can tell.
69,680,969
69,682,120
Finding a cycle and saving its vertices in an undirected, unweighted graph using BFS
I've been trying to make this program save the vertices that make the cycle in the graph. But I'm kind of a newbie in algorithms and achieving that functionality seems a bit complex when using BFS. The code below successfully finds cycles, but the question is how to modify this code so I can print all the vertices that make the cycle? #include <bits/stdc++.h> using namespace std; void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } bool isCyclicConntected(vector<int> adj[], int s, int V, vector<bool>& visited) { // Set parent vertex for every vertex as -1. vector<int> parent(V, -1); // Create a queue for BFS queue<int> q; // Mark the current node as // visited and enqueue it visited[s] = true; q.push(s); while (!q.empty()) { // Dequeue a vertex from queue and print it int u = q.front(); q.pop(); // Get all adjacent vertices of the dequeued // vertex u. If a adjacent has not been visited, // then mark it visited and enqueue it. We also // mark parent so that parent is not considered // for cycle. for (auto v : adj[u]) { if (!visited[v]) { visited[v] = true; q.push(v); parent[v] = u; } else if (parent[u] != v) return true; } } return false; } bool isCyclicDisconntected(vector<int> adj[], int V) { // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (!visited[i] && isCyclicConntected(adj, i, V, visited)) return true; return false; } // Driver program to test methods of graph class int main() { int V = 4; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) cout << "Yes"; else cout << "No"; return 0; }
You could use the parent links to reconstruct the cycle. When two BFS paths meet, then these two paths can each be reconstructed by following the parent link in tandem, until a common node is encountered. The lengths of these two paths can either be equal (the cycle is even), or differ by 1 (the cycle is odd). If you do the tandem walk via the mutual parent links in the right way, you will always encounter the "top" of the cycle. The nodes of the cycle will be listed in a natural order when you use a deque: the nodes coming from the first path can be pushed to the front, while the nodes of the other path to the back. You don't actually need a separate visited vector: you can also use parent for this purpose. True, the first node you start the BFS on, will then not be marked as visited, but there is no way to visit it as the end point of a cycle, as BFS will go through all edges from that source node, and does not allow to use any of those edges to visit the source node. So using parent for that purpose is enough. Here is your code adapted with those ideas: void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } bool isCyclicConnectedHelper(vector<int> adj[], int s, int V, vector<int>& parent, deque<int> &cycle) { queue<int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (auto v : adj[u]) { if (parent[v] == -1) { // Not yet visited parent[v] = u; q.push(v); } else if (parent[u] != v) { // Not the same edge // Two paths meet: unwind both of them at both sides of a deque: while (u != v) { cycle.push_front(v); v = parent[v]; if (u == v) break; cycle.push_back(u); u = parent[u]; } cycle.push_front(u); return true; } } } return false; } bool isCyclicConnected(vector<int> adj[], int V, deque<int> &cycle) { vector<int> parent(V, -1); for (int i = 0; i < V; i++) { if (parent[i] == -1) { if (isCyclicConnectedHelper(adj, i, V, parent, cycle)) { return true; } } } return false; } // Driver program to test methods of graph class int main() { int V = 5; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 4); addEdge(adj, 3, 4); addEdge(adj, 4, 1); deque<int> cycle; if (isCyclicConnected(adj, V, cycle)) { cout << "The graph has a cycle:"; for (auto v : cycle) { cout << " " << v; } } else { cout << "The graph has no cycle."; } cout << "\n"; return 0; } NB: I would suggest defining adj as vector<vector<int>> and adjust addEdge so it will extend that vector as needed. That way you also get rid of V.
69,681,271
69,681,417
Creating a Service in vs2019
I wanted to create a service in VS2019, but it hasn't a template for it. So I created an empty project and then I try to write a service from ground up. I written the following main function. #define SERVICE_NAME _T("My Sample Service") int _tmain(int argc, TCHAR* argv[]) { OutputDebugString(_T("My Sample Service: Main: Entry")); SERVICE_TABLE_ENTRY ServiceTable[] = { {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {NULL, NULL} }; if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) { OutputDebugString(_T("My Sample Service: Main: StartServiceCtrlDispatcher returned error")); return GetLastError(); } OutputDebugString(_T("My Sample Service: Main: Exit")); return 0; } But It says, you can't initialize a LPWSTR with a const wchar_t. This error is belong to the following line: SERVICE_TABLE_ENTRY ServiceTable[] = { {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {NULL, NULL} }; But when I was watching video tutorial, the authro exactly written the above code but in vs 2019 I can't write such things. What should I do now?
The issue is that the structure is defined as follows: typedef struct _SERVICE_TABLE_ENTRYW { LPWSTR lpServiceName; LPSERVICE_MAIN_FUNCTIONW lpServiceProc; } SERVICE_TABLE_ENTRYW, *LPSERVICE_TABLE_ENTRYW; LPWSTR is wchar_t*. String literal L"..." can be assigned to const wchar_t* pointer, but not wchar_t* pointer. Previously the Visual C++ compiler accepted such code. Now it will accept it with /permissive, but will reject with /permissive-. /permissive is the default option for the compiler, but /permissive- is set by default in Console Application project template. Generally, you shouldn't want to set /permissive for new code, it is more like an aid to port old code. So, to fix compilation, you can: use /permissive cast away constness by const_cast or C-style cast use non-constant string, like wchar_t ServiceName[] = L"My Sample Service"; The last option is generally safest, as it makes no assumptions not defined by type system. However, the others are likely to be good enough, since this appears to be a widespread code sample for a service, and it is unlikely that it ever stops working.
69,681,305
69,681,441
Segmentation fault in memory allocation when making a dynamically resized array C++
I get a segmentation fault when the append(int val) function is run, and called polymorphically, but I can't see where the memalloc error is coming from. I'm still new to C++, and run into this problem a lot, but when I do fix it on my own, it's always by happenchance. Any pointer? (No pun intended, or is it :)) IntegerCombination.h #ifndef INTEGERCOMBINATION_H #define INTEGERCOMBINATION_H using namespace std; class IntegerCombination { public: IntegerCombination(); void append(int Val); virtual int combine() = 0; protected: int* _collection; int _length; }; #endif IntegerCombination.cpp #include "IntegerCombination.h" IntegerCombination::IntegerCombination() { _length = 0; } void IntegerCombination::append(int val) { int newValPos = _length; // Stores current length as new position for new // value int* temp = _collection; //Stores current array delete _collection; // Deletes current array _length++; // Increases the length for the new array _collection = new int[_length]; // Creates a new array with the new length for(int i = 0; i < newValPos; i++) { _collection[i] = temp[i]; // Allocates values from old array into new array } _collection[newValPos] = val; // Appends new value onto the end of the new array } Main.cpp #include "IntegerCombination.h" #include "ProductCombination.h" using namespace std; int main() { ProductCombination objProd; for(int i = 1; i <= 10; i++) { objProd.append(i); } return 0; } Note: The code in ProductCombination.h and ProductCombination.cpp is not entirely relevant, as in the .cpp file, append(int val) is only delegating the append call to the base class in IntegerCombination.h
For starters the constructor does not initializes the data member _collection IntegerCombination::IntegerCombination() { _length = 0; } So this data member can have an indeterminate value and using the operator delete with such a pointer invokes undefined bejavior. Moreover as you are trying to allocate an array then you need to use the operator delete [] instead of delete. And the class has to define explicitly at least a virtual destructor. Also either declare the copy constructor and the copy assignment operator as deleted or also define them explicitly. The function append has several bugs. As it was mentioned you need to use the operator delete [] in this statement delete _collection; instead of the operator delete. But this operator must be called after the new array is allocated. Otherwise the pointer temp will have an invalid value int* temp = _collection; //Stores current array delete [] _collection; // Deletes current array That is you need to delete the previous array after you copied elements of it to the new allocated array.
69,681,755
69,688,653
C++ map custom iterator using the wrong type of begin() overload
For a school exercise I'm trying to recode the map STL container using Red-Black Tree method and I'm having an issue with the use of which begin() overload when I call them. For testing purpose I'm trying to show the content of my map with the following function: template <typename T> inline void printMapContainer(T& cont) { for (typename T::const_iterator it = cont.begin(); it != cont.end(); ++it) std::cout << "[" << it->first << "][" << it->second << "] | "; } But I get an error that tells me that there is no viable conversion from iterator type to const_iterator type. It means that when the loop calls begin(), it calls the non const begin() function that returns iterator instead of const_iterator.My implementation is the following: iterator begin() { return (iterator(this->_tree.begin())); }; const_iterator begin() const { return (const_iterator(this->_tree.begin())); }; The _tree.begin() function returns the node to the head element in the tree, and I define the iterator in my map class this way: typedef typename ft::rb_tree<value_type, Compare>::iterator iterator; typedef typename ft::rb_tree<value_type, Compare>::const_iterator const_iterator; What am I doing wrong?
As @n.1.8e9-where's-my-sharem said: Any iterator should be convertible to a corresponding const_iterator. You may add either a conversion operator to your iterator class, or a conversion constructor to your const_iterator class. what I was missing is a constructor in my const_iterator class that would be able to copy the content of an iterator!
69,681,934
69,682,255
Disable copy assigment in CRTP-template
I'm having a CRTP template in which I use an object pool. Object are allocated using the generate() static method. template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void> class SignalT : public SignalSignatureT<tBridgeType> { ... static tDerivedSignal &generate(tPayLoadType &fPayLoad) { tDerivedSignal &rtnVal = Pool::reserve(); // Copy pay load to signal instance rtnVal.mPayLoad = fPayLoad; // Return generated signal return(rtnVal); } ... } Now, the thing is that I wan't to prevent a copy assignment like DerivedSignal sig = DerivedSignal::generate() The reason is that the copy sig may be have a local scope and become invalid/destructed which will generate a seg fault later on when the user tries to use it. Also, the allocated pool object will be lost and leak memory. I would like the copy assignment above to generate compile time error but a reference assignment such as DerivedSignal &sig = DerivedSignal::generate() shall be OK. I've tried to delete the assignment operator in the CRTP template with no luck: template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void> class SignalT : public SignalSignatureT<tBridgeType> { ... // Disable copy assignment operator to prevent a generated signal from being copied into // a new instance that is not under pool management tDerivedSignal operator=(const tDerivedSignal &) = delete; tDerivedSignal operator=(const tDerivedSignal) = delete; ... } Anyone have any idea??
You want to delete the SignalT copy assignment (and most likely copy construction). By default, any class that inherits from this (as in your CRTP pattern) will have its default copy constructor/copy assignement operators also deleted, which will also inhibit the default move construct/move assignment operators. template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void> class SignalT : public SignalSignatureT<tBridgeType> { ... // Disable copy assignment operator to prevent a generated signal from being copied into // a new instance that is not under pool management void SignalT operator=(const SignalT&) = delete; // You probably also want to delete copy construction SignalT(SignalT const&) =delete; ... }
69,682,233
69,682,299
How to deduce template parameters based on return type?
I am attempting to create a simple input() function in C++ similarly to Python. I expected the code (below) to prompt the user for their age, then to print it into the console. #include <iostream> using namespace std; int main(void) { int age; age = input("How old are you? "); cout << "\nYou are " << age << endl; } I have written the following simple code to solve the problem template <typename T> T input(const string &prompt) { T _input; cout << prompt; cin >> _input; return _input; } Instead it gives me the following error message: In function 'int main()': 17:36: error: no matching function for call to 'input(const char [18])' 17:36: note: candidate is: 5:3: note: template<class T> T input(const string&) 5:3: note: template argument deduction/substitution failed: 17:36: note: couldn't deduce template parameter 'T' How do I make it so that input() automatically detects the fact that age is an int, and that I don't have to write input<int>()? I don't need a function template necessarily, any solution will do that lets the code in main work as written.
Conversion operators can mimic that. struct input { const string &prompt; input(const string &prompt) : prompt(prompt) {} template <typename T> operator T() const { T _input; cout << prompt; cin >> _input; return _input; } }; Mind however that this may not be applicable for every sort of operation. Plus, this is a fairly naive way of holding on the the prompt. You'd need to copy it proper if object lifetime issues become a concern.
69,682,235
69,683,143
How to store sent/received data with libcurl
Im trying to implement some curl and curlcpp functions for a small project. So far i have implemented a few functions but now i want to add functionality. The idea is to store in a buffer the sent and receive data so later i can access: Sent Data Sent Headers Received Data Received Headers I know there is CURLOPT_WRITEFUNCTION but this only works for response data and i need the output data/headers too. CURLOPT_DEBUGFUNCTION looks that works for me but i cant configure it on CPP. Here is an example code of my class: class CurlCPPClient { private: ... int trace_data(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr); curl::curl_easy curl_easy; std::string raw_data; public: ... } CurlCPPClient::CurlCPPClient() { curl_easy.add<CURLOPT_DEBUGFUNCTION>(this->trace_data); } int CurlCPPClient::trace_data(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { std::string frame_info(data); switch(type) { case CURLINFO_HEADER_OUT: case CURLINFO_DATA_OUT: raw_data += frame_info; break; case CURLINFO_HEADER_IN: case CURLINFO_DATA_IN: raw_data += frame_info; break; default: break; } return 0; } I have compiler issues when setting the function pointer to trace_data. I get "error C3867" and "error C2228" with: this->trace_data, this.trace_data, trace_data. If i dont use trace_data as a method of my class, i can call it but i cant save the info on a member to access it later in another part of the class.
libcurl expects standalone C-style functions for its callbacks. You can't use a non-static class method for a callback. Declare your trace_data() method as static. You can use CURLOPT_DEBUGDATA to pass the this pointer of the CurlCPPClient object to the method's userptr parameter. class CurlCPPClient { private: ... static int trace_data(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr); curl::curl_easy curl_easy; std::string raw_data; public: ... } CurlCPPClient::CurlCPPClient() { curl_easy.add<CURLOPT_DEBUGFUNCTION>(&CurlCPPClient::trace_data); curl_easy.add<CURLOPT_DEBUGDATA>(this); } int CurlCPPClient::trace_data(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { CurlCPPClient *pThis = static_cast<CurlCPPClient*>(userptr); std::string frame_info(data, size); switch(type) { case CURLINFO_HEADER_OUT: case CURLINFO_DATA_OUT: pThis->raw_data += frame_info; break; case CURLINFO_HEADER_IN: case CURLINFO_DATA_IN: pThis->raw_data += frame_info; break; default: break; } return 0; } Alternatively, use CURLOPT_DEBUGDATA to pass just the raw_data member to the callback: class CurlCPPClient { private: ... static int trace_data(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr); curl::curl_easy curl_easy; std::string raw_data; public: ... } CurlCPPClient::CurlCPPClient() { curl_easy.add<CURLOPT_DEBUGFUNCTION>(&CurlCPPClient::trace_data); curl_easy.add<CURLOPT_DEBUGDATA>(&raw_data); } int CurlCPPClient::trace_data(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { std::string *pRawData = static_cast<std::string*>(userptr); std::string frame_info(data, size); switch(type) { case CURLINFO_HEADER_OUT: case CURLINFO_DATA_OUT: *pRawData += frame_info; break; case CURLINFO_HEADER_IN: case CURLINFO_DATA_IN: *pRawData += frame_info; break; default: break; } return 0; }
69,682,251
69,822,888
Using Conan to build multiple libraries and packaging them to be used without Conan
I am very new to Conan and I am quite lost in the documentation at the moment and I cannot really find a way to do what I want. Maybe I am not using the right tool for this, I am very open to suggestions. Let's say my C++ project needs opencv and nlohmann_json to be built. I want to be able to create an archive of all my project's dependencies to be used as is, so it can be redistributed on our gitlab instance. I want to have a repository which roughly looks like this: ├── conanfile.py ├── json │   └── 3.10.4 │   └── conanfile.py └── opencv ├── 4.4.0 │   └── conanfile.py └── 5.1.0 └── conanfile.py Where invoking the root conanfile.py would automatically build the required libs and copy their files as to have something like this: ├── conanfile.py ├── json │   └── 3.10.4 │   └── conanfile.py ├── opencv │   ├── 4.4.0 │   │   └── conanfile.py │   └── 5.1.0 │   └── conanfile.py └── win64_x86 ├── include │   ├── nlohmann │   └── opencv2 └── lib └── <multiple files> and the CI/CD would archive the directory and make it available for download. I have managed to build and package a very simple repo (https://github.com/jameskbride/cmake-hello-world) independently using the git tools and doing something like this: def config_options(self): if self.settings.os == "Windows": del self.options.fPIC def source(self): git = tools.Git(folder="repo") git.clone("https://github.com/jameskbride/cmake-hello-world", "master") def build(self): cmake = CMake(self) cmake.configure(source_folder="repo") cmake.build() However, I cannot figure out how to get the files that I want to package from my main conanfile.py. All of the approaches I have tried so far needed the package to be built separately (ie, going to the folder, using conan source . conan build . and conan export-pkg .. I am, 100% sure I am not doing this properly but I can't really find a way to do this. I found something about deploy() in the docs but can't figure out how to use it... NB: I would really, really prefer not using a remote with prebuilt binaries for dependencies. I want to build everything from source with the CMake configurations I have defined. I also explicitely don't want a conan package in the end. I just want an aggregation of all the files needed to be shipped directly to the machines.
This question has been answered by Conan's co-founder james here: https://github.com/conan-io/conan/issues/9874 Basically: Use the CMakeDeps generator instead of cmake / cmake_find_package Patch the resulting cmake config files at install time inside the generate() method from the main conanfile.py Edit recipes accordingly (but should be fine most of the time)
69,682,392
69,697,727
C++ code duplication in functions with different number of arguments
I'm trying to remove some code duplication from my code. So there are 2 functions with almost the same code Post and Send but they have different number of parameters which puts me on thought that it should be or variadic template or std::function (correct me if I'm wrong). One function call is different though so I'm thinking it suppose to be pointer to member function, but I cannot make a pointer as send_report and publish_event functions also have different number of parameters. So here's pseudocode class MyClass { void Post( CStream& responseStream ); void Send(); void send_report( CStream& responseStream, std::string ); void publish_event( std::string string ); // callbacks void process( CStream& responseStream ); void update(); } void MyClass::Post( CStream& responseStream ) { // ... the same code ... send_report( responseStream, string ); // different function // ... the same code ... } void MyClass::Send() { // ... the same code ... publish_event( string ); // different function // ... the same code ... } void MyClass::process( CStream& responseStream ) { // some code Post( responseStream ); } void MyClass::update() { // some code Send(); } void MyClass::send_report( CStream& responseStream, std::string ) { // differ } void MyClass::publish_event( std::string string ) { // differ } As I see it Post and Send should be wrapped in variadic template and send_report and publish_event are wrapped into std::function. Could you provide me with some code example for my case? My compiler is C++11 though.
Solved it #include <iostream> #include <functional> using namespace std; class MyClass { public: void Post( int responseStream ); void Send(); void send_report( int responseStream, std::string str ); void publish_event( std::string str ); // callbacks void process( int ); void update(); template<typename F> void SuperSend( F send_func ); }; template<typename F> void MyClass::SuperSend( F send_func ) { std::string str = "Hello"; // lots of code send_func(str); // lots of code } void MyClass::process( int responseStream ) { std::function<void(std::string)> post = [&](std::string n) { send_report(responseStream, n); }; SuperSend( post ); } void MyClass::update() { std::function<void(std::string)> post = [&](std::string n){ publish_event(n); }; SuperSend( post ); } void MyClass::send_report( int responseStream, std::string str ) { cout << __FUNCTION__ << ": " << str << responseStream << endl; } void MyClass::publish_event( std::string str ) { cout << __FUNCTION__ << ": " << str << endl; } int main() { MyClass A; A.process(1); A.update(); return 0; }
69,682,496
69,705,612
GLSL: Fade 2D grid based on distance from camera
I am currently trying to draw a 2D grid on a single quad using only shaders. I am using SFML as the graphics library and sf::View to control the camera. So far I have been able to draw an anti-aliased multi level grid. The first level (blue) outlines a chunk and the second level (grey) outlines the tiles within a chunk. I would now like to fade grid levels based on the distance from the camera. For example, the chunk grid should fade in as the camera zooms in. The same should be done for the tile grid after the chunk grid has been completely faded in. I am not sure how this could be implemented as I am still new to OpenGL and GLSL. If anybody has any pointers on how this functionality can be implemented, please let me know. Vertex Shader #version 130 out vec2 texCoords; void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; texCoords = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy; } Fragment Shader #version 130 uniform vec2 chunkSize = vec2(64.0, 64.0); uniform vec2 tileSize = vec2(16.0, 16.0); uniform vec3 chunkBorderColor = vec3(0.0, 0.0, 1.0); uniform vec3 tileBorderColor = vec3(0.5, 0.5, 0.5); uniform bool drawGrid = true; in vec2 texCoords; void main() { vec2 uv = texCoords.xy * chunkSize; vec3 color = vec3(1.0, 1.0, 1.0); if(drawGrid) { float aa = length(fwidth(uv)); vec2 halfChunkSize = chunkSize / 2.0; vec2 halfTileSize = tileSize / 2.0; vec2 a = abs(mod(uv - halfChunkSize, chunkSize) - halfChunkSize); vec2 b = abs(mod(uv - halfTileSize, tileSize) - halfTileSize); color = mix( color, tileBorderColor, smoothstep(aa, .0, min(b.x, b.y)) ); color = mix( color, chunkBorderColor, smoothstep(aa, .0, min(a.x, a.y)) ); } gl_FragColor.rgb = color; gl_FragColor.a = 1.0; }
You need to split your multiplication in the vertex shader to two parts: // have a variable to be interpolated per fragment out vec2 vertex_coordinate; ... { // this will store the coordinates of the vertex // before its projected (i.e. its "world" coordinates) vertex_coordinate = gl_ModelViewMatrix * gl_Vertex; // get your projected vertex position as before gl_Position = gl_ProjectionMatrix * vertex_coordinate; ... } Then in the fragment shader you change the color based on the world vertex coordinate and the camera position: in vec2 vertex_coordinate; // have to update this value, every time your camera changes its position uniform vec2 camera_world_position = vec2(64.0, 64.0); ... { ... // calculate the distance from the fragment in world coordinates to the camera float fade_factor = length(camera_world_position - vertex_coordinate); // make it to be 1 near the camera and 0 if its more then 100 units. fade_factor = clamp(1.0 - fade_factor / 100.0, 0.0, 1.0); // update your final color with this factor gl_FragColor.rgb = color * fade_factor; ... } The second way to do it is to use the projected coordinate's w. I personally prefer to calculate the distance in units of space. I did not test this code, it might have some trivial syntax errors, but if you understand the idea, you can apply it in any other way.
69,682,609
69,683,402
Correctly catching the CDatabase::Close exception
I thought I would do a little digging about cataching exceptions. According to this question (C++ catching all exceptions) one of the answers states: [catch(...)] will catch all C++ exceptions, but it should be considered bad design. At the moment I have used this approach: CPTSDatabase::~CPTSDatabase() { try { CloseDatabase(); } catch(...) { } } void CPTSDatabase::CloseDatabase() { if (m_dbDatabase.IsOpen()) m_dbDatabase.Close(); } I thought that this was the correct way because when I trace into CDatabase::Close() it does something similar: // Disconnect connection void CDatabase::Close() { ASSERT_VALID(this); // Close any open recordsets AfxLockGlobals(CRIT_ODBC); TRY { while (!m_listRecordsets.IsEmpty()) { CRecordset* pSet = (CRecordset*)m_listRecordsets.GetHead(); pSet->Close(); // will implicitly remove from list pSet->m_pDatabase = NULL; } } CATCH_ALL(e) { AfxUnlockGlobals(CRIT_ODBC); THROW_LAST(); } END_CATCH_ALL AfxUnlockGlobals(CRIT_ODBC); if (m_hdbc != SQL_NULL_HDBC) { RETCODE nRetCode; AFX_SQL_SYNC(::SQLDisconnect(m_hdbc)); AFX_SQL_SYNC(::SQLFreeConnect(m_hdbc)); m_hdbc = SQL_NULL_HDBC; _AFX_DB_STATE* pDbState = _afxDbState; AfxLockGlobals(CRIT_ODBC); ASSERT(pDbState->m_nAllocatedConnections != 0); pDbState->m_nAllocatedConnections--; AfxUnlockGlobals(CRIT_ODBC); } } And the CDatabase::Close documentation does not even state anything about exceptions being thrown. The linked answer does state: You can use c++11's new current_exception mechanism. It is not clear if we can use this approach given the CDatabase class we are using.
Since CDatabase::Close() is using THROW_LAST to throw CDBException, you have to use catch (CDBException* e). Even if you are not handling it, you still have to Delete the error. You might as well do this when CDatabase methods are called directly: void CPTSDatabase::CloseDatabase() { try { if (m_dbDatabase.IsOpen()) m_dbDatabase.Close(); } catch (CDBException* e) { //TRACE(L"DB error: " + e->m_strError); e->Delete(); } } Or use CPTSDatabase::~CPTSDatabase() { try { CloseDatabase(); } catch (CDBException* e) { e->Delete(); } catch(...) {} } Because in this code it's not clear where the exceptions are coming from. catch(...) {} will deal with other exceptions. In general catch(...) {} is not recommended because it doesn't give useful information, it just says "something went wrong..." Use Standard Library exceptions only if you are adding throw in your own code, or when using std functions. Example: try { std::stoi("wrong argument"); } catch (const std::exception& e) { TRACE("%s\n", e.what()); } try { throw 123; } catch (int i) { TRACE("%d\n", i); }
69,682,659
69,682,711
c++: how to add an environmental variable only for the current process?
Basically the question is in the title. I'm using the setenv() fucntion to set the environmental variable in my cpp program, where I also use fork() exec() chain, which create a child process. The problem is that the created variable is also accessible from this child process. This makes setenv() equivalent to export ABC=EFG behavior in the shell. What I want is to separate this functionality. I want to separately set the variable ABC=EFG and make it available to the child process export ABC. How to do this? EDIT: I decided to add my comment to @SergeyA's answer here. How does bash handle env variables in a situation like this, for example? If I write ABC=EFG and call a script consisting from only one line echo $ABC it won't print anything unless I previously called export ABC. I'm just writing a shell and trying to mimic this behavior.
There is no direct way of doing this. Calling exec is always going to make child process inheriting environment variables of the parent process. You can use exceve to explicitly specify environment variables to be visible to child process.
69,682,947
69,683,002
Fill argv (and get argc) with a string to pass to other method
I receive from another method a string (I don’t know the size of this) and I want to fill my argv (and get argc) with this string to pass to other method and I don’t know how to do it. At the start of the string I set the name of my app so I have a final string like: "myapp arg1 arg2 arg3 arg4" The code I have is the following: int main (int argc, const char* argv[]) { while(true) { // send_string() give a string like: “the_name_of_my_app arg1 arg2 arg3 arg4” std::string data = send_string(); argv = data; argc = number_of_element_on_data; other_function(argc, argv); } return 0; }
Try something like this: #include <vector> #include <string> #include <sstream> int main (int argc, const char* argv[]) { while (true) { // send_string() give a string like: “the_name_of_my_app arg1 arg2 arg3 arg4” std::string data = send_string(); std::istringstream iss(data); std::string token; std::vector<std::string> args; while (iss >> token) args.push_back(token); std::vector<const char*> ptrs(args.size()+1); for(size_t i = 0; i < args.size(); ++i) ptrs[i] = args[i].c_str(); ptrs[args.size()] = NULL; other_function(args.size(), ptrs.data()); } return 0; }
69,683,005
69,683,482
Range-v3: Why is ranges::to_vector needed here?
I'm trying to compute a reversed views::partial_sum. The code below gives the expected result of a non-reversed partial_'min', but I need to use ranges::to_vector in order to un-views::reverse the final result (since you can't views::reverse a views::partial_sum). However, when the second to_vector is uncommented, the views::values of intermediate2 are all zeros (although the keys are computed correctly). Uncommenting the first to_vector will fix this, but I'd like to know why? And whether I it is possible to avoid the first to_vector? Or whether should I just not bother with understanding and just chuck in to_vectors until the code works. auto input = std::vector<float>{} | actions::push_back(views::iota(0u, COUNT)) | actions::shuffle(std::default_random_engine{});; auto intermediate1 = views::zip(views::iota(0u, COUNT), input) //| to_vector ; auto intermediate2 = intermediate1 | views::reverse | views::partial_sum( [](std::pair<unsigned, float> a, std::pair<unsigned, float> b) { if (a.second > b.second) return b; else return a; }) //| to_vector ; auto ans = intermediate2 //| views::reverse ; std::cout << "values = " << (ans | ranges::views::values | views::take(23)) << std::endl; std::cout << "indices = " << (ans | ranges::views::keys | views::take(23)) << std::endl; EDIT I overlooked that the uncommenting the final reverse breaks the code again, even with both to_vectors so it must a problem with reverse as per Barry's answer.
This is a range-v3 bug that is a result of views::reverse not properly propagating the value_type, and so you end up with a vector<common_pair<unsigned int, float&>> (note the reference) where you should really be ending up with a vector<pair<unsigned int, float>>. This will be fixed by this PR. In the meantime, you can fix this yourself by providing an explicit type for the vector that you're converting into, via ranges::to<std::vector<std::pair<unsigned int, float>>>().
69,683,071
69,683,523
How to pull text out of a .txt and store it into a dynamic 2d array?
I need to pull text line by line out of my .txt file and store it into a dynamic array that has new space allocated every time I pull a new line out of the .txt file. My code seems to pull out the first line just fine and store it into the first pointers array, but on the second loop, it seems to reset all the pointers arrays which gives me memory allocation errors when I later try to access it. Why does this happen especially when I don't touch the pointers and their arrays after I store stuff into them? char** temp = nullptr; char buffer[256]; int index = 0; // Open File fstream myFile; myFile.open("pantry.txt", ios::in); if (myFile.is_open()) { while (!myFile.eof()) { myFile >> buffer; // Pull line out of txt.file temp = new char* [index + 1]; // Create new pointer temp[index] = new char[strlen(buffer)+1]; // Create char array pointed at by new pointer #pragma warning(suppress : 4996) // Turns off complier warning strcpy(temp[index], buffer); //Copy buffer into new char array index++; // Increment our index counter int } for (int i = 0; i < index; i++) { cout << temp[i] << endl; } If allocated and stored correctly I want it to just print out the txt file exactly. Instead, I get Exception thrown at 0x7B9A08CC (ucrtbased.dll) in PE 12.4.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD. pantry.txt Basil Flat Leaf Parsely Thyme Sage Cumin Steak Seasoning Mace Garlic Powder
There are multiple bugs in the shown code. while (!myFile.eof()) This is always a bug that also must be fixed, in addition to the main problem with the shown code: temp = new char* [index + 1]; To help you understand the problem with this line, it's helpful to remember The Golden Rule Of Computer Programming: Your computer always does exactly what you tell it to do instead of what you want it to do. According to the Golden Rule, the above line tells your computer, exactly: "new something, and assign it to temp". And this is what your computer will do every time it executes this line. This line is executed once, on each iteration of this loop. The next time this loop runs, the previously newed temp will be replaced by another one, leaking everything that it pointed to before. Why should your computer do anything else, on this line? After all, this is exactly what you told your computer to do. And this is why you observed that this will "reset all the pointers arrays" on every iteration of the loop, resulting in "memory allocation errors". In any case, this entire chunk of logic needs to be scrapped and rewritten from scratch, this time using the right logic. The simplest thing to do is to actually use the C++ library's std::vector and std::string objects, which will do all the memory allocation for you, correctly. Modern C++ code rarely needs to new anything, and will use C++ library's containers, instead. It is possible that the goal of your assignment is to demonstrate proper use of low-level memory allocation and deallocation logic. In this case you will need to find some other way of doing this. Since you don't know the number of lines in advance, one approach will be to build a linked list, one line at a time, as each line gets read from the file. The final array, with all the character pointers gets allocated only after the entire file is read (and the number of lines is known), the pointers moved to the array, and the temporary linked list deleted. Or, perhaps implement a std::vector-like algorithm that progressively allocates a new pointer array, when it is full, copies over all the character pointers to a bigger array and then deletes the original one. Of course, that's a lot of work. But unless the purpose of your assignment or task is to correctly implement low-level memory allocations and deallocation, why go through all the work and pain to do what std::vector and std::string already do, when you can simply use them, in just five or six lines of code, that will replace all of the above?
69,683,155
69,683,752
Program seems to be skipping second set of inputs and going directly to the end calculations
after the second output statement, the program doesn't take the second set of inputs. Any idea what I could even do to fix this? Is this just a quirk of C++? Any help at all is much appreciated. :) #include <iostream> using namespace std; int main() { int startHours, startMinutes; int endHours, endMinutes; bool startIsAM, endIsAM; char amPmChar, extra; int computeDifference(int startH, int startM, bool startTime, int endH, int endM, bool endTime); int diff, hours, minutes; //----------------------------------------------------------------------// cout << "Enter start time, in the format 'HH:MM xm', where 'xm' is\n either 'am' or 'pm' for AM or PM: "; cin >> startHours; cin >> extra; cin >> startMinutes; cin >> amPmChar; startIsAM = (amPmChar == 'A') || (amPmChar == 'a'); cout << "Enter future time in the format 'HH:MM xm' where 'xm' is\n either 'am' or 'pm': "; cin >> endHours; cin >> extra; cin >> endMinutes; cin >> amPmChar; }
You have to read one more char, because when you read amPmChar from the input - m is still in your stream. And after that - there is an endline, so your endHours tries to initialize with that value. That's your problem. You may read more about it in this answer, it's about cin validation.
69,683,374
69,683,401
How to pass non-static member function pointer to a template function in C++?
I'm trying to make a function template in a header file that accepts a generic function pointer and packed arguments. The function template would invoke the received function pointer using the packed arguments. My goal is to calculate and return the execution time of the function pointer. #ifndef LOGTIME_HPP #define LOGTIME_HPP #include <chrono> #include <ratio> template<typename Function, typename... Args> double getExecutionTime(Function&& function, Args&&... args) { auto t1 = std::chrono::high_resolution_clock::now(); std::invoke(std::forward<Function>(function), std::forward<Args>(args)...); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> ms = t2 - t1; return ms.count(); } #endif This seems to only work for function pointers that aren't member functions of a class or struct. This is some example code using the function template: #include <iostream> #include <thread> #include <random> #include "LogTime.hpp" // header including getExecutionTime() class Obj { public: int testFunc(int dur, int num) { std::cout << "test" << num; for (int i = 0; i < dur; i++) { std::cout << "."; std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return 2; } }; int testFunc(int dur, int num) { std::cout << "test" << num; for (int i = 0; i < dur; i++) { std::cout << "."; std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return 1; } int main() { std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<> uniform_dist(1, 100); Obj obj = Obj(); for (int i = 0; i < 10; i++) { int rand = uniform_dist(rng); std::cout << "elapsed: " // this works << getExecutionTime(testFunc, uniform_dist(rng), i) << std::endl; // this doesn't work << getExecutionTime(Obj::testFunc, uniform_dist(rng), i) << std::endl; } } My issue is that Obj::testFunc is failing. I know that if Obj::testFunc was static, then the function would execute fine. I've read that std::invoke can invoke a member function by passing an instance of the class type. However, I don't know how to incorporate this into the function template (I've never used templates before now). I would appreciate any help or insight.
Non-static member functions have an implicit parameter of the class type as the first parameter of the function, and it is that object which is mapped to the this pointer. That means that you need to pass an object of the class type as the first argument after the member function pointer like << getExecutionTime(&Obj::testFunc, obj, uniform_dist(rng), i) << std::endl; or you can use a lambda instead like << getExecutionTime([&](){ obj.testFunc(uniform_dist(rng), i); }) << std::endl;
69,683,517
69,683,871
Fast and precise implementation of pow(complex<double>, 2)
I have a code in which I perform many operations of the form double z_sq = pow(abs(std::complex<double> z), 2); to calculate |z|² of a complex number z, where performance and precision are my major concerns. I read that the pow() function of C++ converts int exponents to double and thus introduces numerical errors apart from also having worse performance than x*x in general (discussed here for real numbers). Similarly, the std::pow() method of <complex> converts the exponent to std::complex<double> unnecessarily. My first question is how to implement the complex square Re²+Im² or zz* with best-possible performance and precision. I thought about doing something like double complex_square1(std::complex<double> z) { double abs_z = abs(z); return abs_z * abs_z; } or (which gives a type error, but would be the most straight-forward way, I can think of) double complex_square2(std::complex<double> z) { return z * conj(z); } My second question is, whether for many (10^14) such operations, the function calls can decrease performance noticably. So would it be better in the case of complex_square1 to write abs(z) * abs(z) into the .cpp file instead of defining a function for it? Are there any other better ways to do it?
I think it would be hard to beat just taking the sum of the squares of the imaginary and real parts. Below I measure it being about 5x faster than actually calculating the magnitude and squaring it: #include <complex> #include <chrono> #include <random> #include <vector> #include <iostream> double square_of_magnitude_1( std::complex<double> z) { auto magnitude = std::abs(z); return magnitude * magnitude; } double square_of_magnitude_2( std::complex<double> z) { return z.imag() * z.imag() + z.real() * z.real(); } volatile double v; // assign to volatile so calls do not get optimized away. std::random_device rd; std::mt19937 e2(rd()); std::uniform_real_distribution<double> dist(0, 10); int main() { using std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::duration; using std::chrono::microseconds; std::vector<std::complex<double>> numbers(10000000); std::generate(numbers.begin(), numbers.end(), []() {return std::complex<double>(dist(e2), dist(e2)); }); auto t1 = high_resolution_clock::now(); for (const auto& z : numbers) { v = square_of_magnitude_1(z); } auto t2 = high_resolution_clock::now(); std::cout << "square_of_magnitude_1 => " << duration_cast<microseconds>(t2 - t1).count() << "\n"; t1 = high_resolution_clock::now(); for (const auto& z : numbers) { v = square_of_magnitude_2(z); } t2 = high_resolution_clock::now(); std::cout << "square_of_magnitude_2 => " << duration_cast<microseconds>(t2 - t1).count() << "\n"; } A typical run of the above yields square_of_magnitude_1 => 54948 square_of_magnitude_2 => 9730
69,683,569
69,683,581
Writing a program in c++ to output string in reverse, getting no output as a result
#include <iostream> using namespace std; int main() { int i; string userInput; int index; getline(cin, userInput); index = userInput.length(); for(i = index; i <= 0; i--) { cout << userInput.at(i); } return 0; } Program is generating absolutely 0 output. No errors or bugs, I just can't generate any output... Any ideas to why?
You got the loop condition wrong Try i >= 0 (instead of <= ) In addition, you'll want to start the index at index-1 Working example: #include <iostream> using namespace std; int main() { int i; string userInput; int index; getline(cin, userInput); index = userInput.length(); for(i = index-1; i >= 0; i--) { cout << userInput.at(i); } return 0; }
69,683,597
69,683,891
Why isn't there an implicit defaulted definition for pure virtual destructor?
I know that if the class is supposed to be abstract, but does not contain any used-defined method, there is technique to achieve this by making the destructor pure virtual. class B{ public: virtual ~B() = 0; } As far as I understand the object in example below should not be able to be instantiated. #include <iostream> class A{ public: A(){std::cout<<"A::A()"<<std::endl;} virtual ~A() = 0; }; class B : public A{ public: B(){std::cout<<"B::B()"<<std::endl;} }; int main(){ B b; } I know that pure virtual functions also can have definitions, and that in the case above it should be defined for destructor of B, but something is obscure to me. Is there any particular reason not to make the definition of pure virtual destructor to be implicitly defaulted in C++ standard, because to me it would make a lot of sense.
If a function is declared pure virtual, then this means two things: The class with such a declaration cannot be instantiated. Any derived classes must provide a definition for the method, or they also cannot be instantiated. However, #2 only happens if you don't provide a definition for that pure virtual function declaration. If you do define the pure virtual function, then derived classes do not specifically need to override those methods. Therefore, if there was always a defaulted definition of a pure virtual destructor, it would be impossible to force a user to declare a destructor for derived classes. In the vanishingly rare circumstance where you have a class you intend to use as a virtual type, but has no actual interface (I fail to see how you could uphold the Liskov substitution principle when you have no interface) and therefore should not be instantiated, and but you also want a user to not have to define a destructor explicitly, you can do this: #include <iostream> class A{ public: A(){std::cout<<"A::A()"<<std::endl;} virtual ~A() = 0; }; A::~A() = default; //Yes, this is legal. class B : public A{ public: B(){std::cout<<"B::B()"<<std::endl;} }; int main(){ B b; } However, I highly doubt this circumstance comes up in reality often enough to actually matter. In most real types intended for use in virtual interfaces, they have actual virtual interfaces beyond "can be destroyed". They need virtual destructors, but they also have other virtual functions which can be pure. As such, their destructors don't need to be pure.
69,683,869
69,694,512
How to implement the Fortran spacing() function in C++?
The code I'm converting from Fortran to C++ contains the spacing(x) function. From the description, spacing(x) returns the Smallest distance between two numbers of a given type and Determines the distance between the argument X and the nearest adjacent number of the same type. Is there a C++ equivalent function or, if not, how do I implement that function in C++?
Using SPACING as Determines the distance between the argument X and the nearest adjacent number of the same type, use nexttoward(). upper = nexttoward(x, INFINITY) - x; lower = x - nexttoward(x, -INFINITY); spacing = fmin(upper, lower); upper != lower in select cases: e.g. x is a power-of-2. May need some work to handle implementations that lack a true INFINITY. or if (x > 0) { spacing = x - nexttoward(x, 0); } else { // 1.0 used here instead of 0 to handle x==0 spacing = nexttoward(x, 1.0) - x; } or // Subtract next smaller-in-magnitude value. With 0, use next toward 1. spacing = fabs(x - nexttoward(x, !x)); I suspect nextafter() will work as well, or better than, nexttoward().
69,684,527
69,698,617
how to automatically generate a unique c++ class based on a file
let me preface this question by saying I have no idea if I'm asking the right question. I'm pretty new to c++ and I haven't gotten all of its nuances down yet, but I have coded in other OOP languages for nearly 7 years. I originally asked: Is there a way to take a text file and automatically generate c++ code? If yes, how do I do that? What are some resources that explain the process? but to clarify, what I really want is: Is there some way to take a text file, or other file type (like json) and use it to generate a compiled c++ class, or other compiled object, that can be interfaced with c++? The final result doesn't need to be human readable, and it can be system specific. I want to be able to do this at compile time. It does not have to happen at run time. I will know at run time what classes I need. It's just that the classes I will be making (and there will be a lot of them) are all very similar, and just deviate in a few key places. So I want a way to tell the computer the important stuff (which may only take 5 or 6 lines of code), and have it generate the other 30 lines of boiler plate code. I'm making a game engine, and I am trying to design a system that allows me to plug and play with systems, without having to write a lot of boiler plate code. Someone commented that I should make the example simpler. So here goes. I'm trying to build a system that takes a text file input and builds me a compiled c++ binary. It doesn't have to be a text file, and it doesn't have to be specifically c++, as long as it can interface with c++ (relatively easily). This is to decrease the amount of boiler plate code, and number of short kinda useless c++ files that are all almost identical. For example having a file called example.txt which looks like this. objectGenerator ExampleClass { autofunction[hello world] } I would then hope to generate something that functions similarly to a c++ class like class ExampleClass { public: void callAutoFunctions() { helloWorld(); } private: AutoFunction helloWorld; }; then in my main.cpp for example I could call void main() { GeneratedClasses::ExampleClass exampleClass; exampleClass.callAutoFunctions(); } to print "hello world". I want to be able to do this so I can make lots of different game objects that I can pull parts out of easily (by just changing one or two lines of text). It would make iterating over game ideas much easier, and in the long run would mean my games aren't the tangled mess of references and convoluted solutions to easy problems that they normally are. I don't mind If I have to write a script in a different language than c++. It will make my indie game design career a lot easier if I could set this up now, and just use it for all my games in the future. p.s. I'm trying to remake a game I created in python arcade over a year ago, but in c++ so it runs better, and I can actually create an exe file for the game that I can give to friends, or add to itch.io. I know that it is very bold of me to assume I will be able to make a viable, sellable game when I've coded in c++ for less than a year, but I am a task driven person and I wouldn't have the motivation to learn the c++ I need without doing something over the top like this.
It seems like all you want is separate compilation. Firstly, you make an interface for the part of your game you wish to make more decoupled: // Player.hpp #include <memory> struct IPlayer { virtual void run() = 0; virtual ~IPlayer() = default; }; std::unique_ptr<IPlayer> getPlayer(); Then use it in your program without supplying the implementation: // main.cpp #include "Player.hpp" int main() { auto player = getPlayer(); player->run(); } Then you compile it without linking: $ clang++ -c main.cpp -O3 -Wall -Wextra Now you work on your actual implementations: // FastPlayer.cpp #include "Player.hpp" struct FastPlayer : IPlayer { void run() override { /* ... */ } } std::unique_ptr<IPlayer> getPlayer() { return std::unique_ptr<IPlayer>{ new FastPlayer }; } Then compile whichever implementation you wish to test now and link it with the binary you compiled previously: $ clang++ FastPlayer.cpp main.o -O3 -Wall -Wextra This way you can swap out the implementations easily to test a lot of functionality. It is safer than loading arbitrary code at run time. Ideally, you wouldn't do this manually and would have a build system like CMake handle it for you.
69,684,742
69,684,800
If I am learning C++, is it a problem to learn C++11/14 when C++20 is the most modern version?
I am a fairly new programmer, with only a little bit of python experience. I learned python because I wanted to see if I would enjoy programming, and now I love it. I want to learn C++, and according to The Definitive C++ Book Guide and List a really great book is Programming: Principles and Practice Using C++, a book by the creator of C++. My only concern is that the book is only updated for C++11 and 14, while I read C++20 is a major change("C++20 will be the next big C++ standard after C++11. As C++11 did it, C++20 will change the way we program modern C++" is what I read. I was looking at the changes, but honestly I don't understand a single one). Will learning through this book be a problem for me in the future, or will learning with C++11/14 not really impact me concerning C++20?
I don't think learning C++14 will hurt you at all. It's still very "modern" in the grand scheme of C++ history. The newer C++ versions tend to build on previous versions with more advanced features, but if you're just getting started with C++, the basics will be the same going back to at least the 90's. If anything, you'll have a much better appreciation for why the improvements in the newer versions are actually considered improvements.
69,684,808
69,685,023
Cannot terminate cstring properly
I'm making a program that finds the most frequently inputted character and outputs it but a junk character takes over the output if it's less than the array value. I've tried putting null in multiple places. Putting it at the end, putting it at the beginning. It keeps giving me the junk character ╠ for some reason. #include <iostream> using namespace std; void getMaxCharfrequ(char arr[], int size) { arr[0] = '\0'; char maxChar = ' '; int maxfreq = 0; for (int i = 0; i < size; i++) { int count = 1; for (int j = i + 1; j < size; j++) if (arr[i] == arr[j]) count++; if (count > maxfreq) maxfreq = count; } for (int i = 0; i < size; i++) { int count = 1; for (int j = i + 1; j < size; j++) if (arr[i] == arr[j]) count++; if (count == maxfreq) maxChar = arr[i]; } cout << "The max character frequency is " << maxChar << " with frequency " << maxfreq; } #define size 15 void main() { char arr[size]; arr[0] = '\0'; cout << "Please enter your string: "; cin >> arr; getMaxCharfrequ(arr, size); }
Multiple problems with your code. Before discussing the problems, a suggestion - Read about std::string in C++ and going forward start using it instead of plain C style character array. I am leaving it up to you to use std::string in your program. Below answer is pointing out the problem in your existing code. Lets discuss them one by one: First: In main() function, you are doing arr[0] = '\0'; before taking input from user. Its not required because cin adds a null terminator at the end when reading char *. Second: You are reading user input like this - cin >> arr; What happen when user input more than 15 characters? At least use cin.get (arr, size). Best would be to use std::string, instead of plain char array. Third: You are passing size to getMaxCharfrequ() function. size is macro which will expand to value 15. In the getMaxCharfrequ() function, you are iterating loop till size, so whatever the input user will give, the loop will iterate 15 times which is not correct. This is also the root cause of the problem that you are facing. Instead, the loop should iterate for the number of characters in input string, e.g., if user give input string hello, the loop should iterate for 5 characters only. You should pass the length of input string, instead of size, to getMaxCharfrequ() function or you can also iterate till \0 character of string and, in this case, you don't need to pass the length of string. Fourth: In the getMaxCharfrequ() function, the first statement is arr[0] = '\0'; That means, you are overwriting the first character of user input with null terminating character. You don't need to do this. Fifth: You don't need to reiterate the string again to identify the maximum frequency character. Rather, you can do it while calculating the frequency of characters in the string. Just record the character when count > maxfreq. Sixth: The return type of main() should be int. Seventh: This using namespace std; is bad practice, avoid it. Putting these altogether, you can do: #include <iostream> #include <cstring> void getMaxCharfrequ(char arr[], size_t size) { char maxChar = ' '; int maxfreq = 0; for (size_t i = 0; i < size; i++) { int count = 1; for (size_t j = i + 1; j < size; j++) { if (arr[i] == arr[j]) { count++; } } if (count > maxfreq) { maxfreq = count; maxChar = arr[i]; } } if (arr[0] == '\0') { std::cout << "Input string is empty" << std::endl; } else { std::cout << "The max character frequency is " << maxChar << " with frequency " << maxfreq << std::endl; } } #define size 15 int main() { char arr[size]; std::cout << "Please enter your string: "; std::cin.get(arr, size); getMaxCharfrequ(arr, strlen(arr)); return 0; } Output: # ./a.out Please enter your string: helloworld The max character frequency is l with frequency 3 # ./a.out Please enter your string: Input string is empty # ./a.out Please enter your string: aaabbbbcc The max character frequency is b with frequency 4 # ./a.out Please enter your string: aaabbggggg The max character frequency is g with frequency 5
69,684,923
69,684,932
If I have heap allocated member in my struct, do I have to allocate the struct itself in the heap?
struct Vector { size_t size; char ** data; } Vector; I have a vector struct. Do I have to allocate the Vector on heap if the struct has dynamically allocated data? Update: Does that applies the same in c++ class?
No, there is no such rule. A pointer residing in any part of memory may point to any other part of memory. That said, if your struct Vector is allocated in a different way than its data, then the two might end up with different lifetimes, and it might be harder to avoid use-after-free bugs or memory leaks. So if data is dynamically allocated, most of the time you will want struct Vector to be dynamically allocated too. But it's not a requirement.
69,685,415
69,685,439
Error passing a function in as a parameter C++
I have a working implementation of testing the time of a function for search methods, which take: checkSearchTime(T(*funcPointer) (T myArray[], int size, T wanted) as parameters, I try to do the same thing with sort methods: checkSortTime(T(*funcPointer) (T myArray[],int size) and I get an error. This is the error: Error C2664 'void checkSortTime<int>(T (__cdecl *)(T [],int),T [],int)': cannot convert argument 1 from 'void (__cdecl *)(T [],int)' to 'T (__cdecl *)(T [],int)' Here is the code for both files: int main() { memLeaks(); constexpr auto SIZE = 5; int myArray[SIZE]; populateArrayRandom(myArray, SIZE); PrintArray(myArray, SIZE); //insertionSort(myArray, SIZE); PrintArray(myArray, SIZE); checkSearchTime(binary_search, myArray, SIZE, 12); checkSortTime(selectionSort, myArray, SIZE); // THIS IS WHERE THE ERROR IS //checkAllSorts(myArray, SIZE); // WOULD LIKE TO CALL THIS AFTER } template<typename T> void checkSearchTime(T(*funcPointer) (T myArray[], int size, T wanted), T arrayArgument[], int sizeArgument, T wantedArgument) { // Use auto keyword to avoid typing long auto start = std::chrono::high_resolution_clock::now(); funcPointer(arrayArgument, sizeArgument, wantedArgument); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start); //std::cout << "Microseconds: " << duration.count() << std::endl; std::cout << "[" << duration.count() << "] Nanoseconds" << std::endl; } template<typename T> void checkAllSearches(T myArray[], int size, T value) { std::cout << "Search Implementations and Timing\n"; std::cout << "Binary="; checkSearchTime(binary_search, myArray, size, value); std::cout << "Linear="; checkSearchTime(linear_search, myArray, size, value); std::cout << "JumpSearch="; checkSearchTime(jump_search, myArray, size, value); std::cout << "Exponential="; checkSearchTime(exponential_search, myArray, size, value); std::cout << "FibMonaccian="; checkSearchTime(fibMonaccian_search, myArray, size, value); } template<typename T> void checkSortTime(T(*funcPointer) (T myArray[],int size), //tried const here, doesn't work either T arrayArgument[], int sizeArgument) { // Use auto keyword to avoid typing long auto start = std::chrono::high_resolution_clock::now(); funcPointer(arrayArgument, sizeArgument); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start); //std::cout << "Microseconds: " << duration.count() << std::endl; std::cout << "[" << duration.count() << "] Nanoseconds" << std::endl; }
It was because sort methods don't return anything.
69,685,438
69,697,561
Qml c++ diffrent delegates qt mvc
How I can use different delegates in qml for the ListView. For example I have QList<SomeObject*> list, SomeObject has two fields: type (circle, rectangle, etc), and someValue. I created QListModel for this list. I have different qml elements (circle.qml, rectangle.qml, etc). How can I view delegate for an item by type, and view field someValue in this delegate. And can I position these delegates without a table/list, I wanted to position them by coordinates(x, y).
You can try a concept of qml Loader that may match your requirements. Basically, you cannot define multiple delegates for a single view. So setting your Top Delegate as the loader and loading the items based on the type will help you with this case. Positioning is also possible you can have x & y pos defined with your model data. So that you can align your view items accordingly. I have used Scrollview + Repeater in this case Shared a minimal sample here. For sake of simplicity, I have kept my data with Qml ListModel. The same can be done with objects from the c++ model as well. Here provided the source as a Qt solution project too. // ShapeModel.qml // import QtQuick 2.15 import QtQml.Models 2.15 ListModel { ListElement { type: "circle" val: "100" xpos: 10 ypos: 10 } ListElement { type: "rectangle" val: "30" xpos: 100 ypos: 100 } ListElement { type: "circle" val: "150" xpos: 300 ypos: 450 } ListElement { type: "rectangle" val: "20" xpos: 500 ypos: 200 } ListElement { type: "circle" val: "25" xpos: 650 ypos: 100 } ListElement { type: "rectangle" val: "60" xpos: 600 ypos: 200 } } // main.qml // import QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.15 Window { width: 640 height: 480 visible: true title: qsTr("Qt MVC") Component { id: componentCircleId Rectangle { border.color: "blue" border.width: 1 height: value width: value radius: value/2 } } Component { id: componentRectangleId Rectangle { border.color: "orange" border.width: 1 height: value width: value } } Component { id: componentLoaderId Loader { property real value: val x: xpos y: ypos sourceComponent: type === "circle" ? componentCircleId : componentRectangleId } } ScrollView { id: scrollviewId anchors.fill: parent Repeater { anchors.fill: parent model: ShapeModel{} delegate: componentLoaderId onItemAdded: { // scroll area computation // Better solutions may be available if(item.x+item.width > scrollviewId.contentWidth) scrollviewId.contentWidth = item.x+item.width if(item.y+item.height > scrollviewId.contentHeight) scrollviewId.contentHeight = item.y+item.height } } } }
69,685,745
69,685,765
std::array guarantee zero-initialization?
I'm wondering that std::array initialize all fields to zero struct Foo { int a; int b; std::uint32_t c : 16; std::uint32_t d : 16; }; class Bar { public: std::array<Foo, 2> foo; } foo's all fields are initialized with zero?
std::array is an aggregate class. When you default initialise an aggregate, the members of the aggregate are also default initialised. Default initialising an integer does not zero initialise it. If you value initialise the aggregate, then the members of the aggregate are also value initialised. Value initialisation of an integer is zero initialisation. In short: No.
69,685,842
69,685,909
Why is my merge sort slower than this merge sort?
I've implemented merge sort in C/C++. But my code takes longer time than the code I pulled from a website. The recursive code seems to be exactly same for both cases: void mergeSort(int* arr, int l, int h) { if (l < h) { int mid = (l + h) / 2; mergeSort(arr,l,mid); mergeSort(arr, mid + 1, h); merge(arr, l, mid, h); } } However the merge algorithm is a bit different, but I don't see any significant difference here. My merge algorithm : void merge(int *arr, int l, int mid, int h) { int i = l, j = mid+1, k = l; int* newSorted = new int[h+1](); while (i <= mid && j <= h) { if (arr[i] < arr[j]) newSorted[k++] = arr[i++]; else newSorted[k++] = arr[j++]; } for (; i <= mid; i++) newSorted[k++] = arr[i]; for (; j <= h; j++) newSorted[k++] = arr[j]; k = 0; for (int x = l; x <= h; x++) arr[x] = newSorted[x]; delete[] newSorted; } Time taken for 200000 (two hundred thousand inputs) : 17 Seconds Merge Algorithm from a website : void merge(int arr[], int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; int* L = new int[n1]; int *M = new int[n2]; for (int i = 0; i < n1; i++) L[i] = arr[p + i]; for (int j = 0; j < n2; j++) M[j] = arr[q + 1 + j]; int i, j, k; i = 0; j = 0; k = p; while (i < n1 && j < n2) { if (L[i] <= M[j]) { arr[k] = L[i]; i++; } else { arr[k] = M[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = M[j]; j++; k++; } delete[] L; delete[] M; } Time taken for 200000 (two hundred thousand inputs) : 0 Seconds There is a massive difference in time. I don't understand the problem in my code. I would really appreciate if someone can help me figure this out. Thank you.
Your algorithm need to allocate [h+1] for each step. The algorithm from a website only need to allocate [r-p+1] (your h = its r, your l = its p)
69,685,871
70,798,672
How to do serialization in Miracl library?
Is there a way to do serialization in C++ Miracl library ? Typically, in Crypto world we would do encryption routine and decryption(like AES,RSA) routine in two differenti program, I want the same structure in these pairing based Encryption like the Attributed-based Encryption and Broadcast Encryption , i.e implement Encryption function in one program and Decryption in another program. There are some example programs in Miracl repo this and this. But they do encryption , keygen and decryption in one program. So I need dump the ciphers produced in Encryption (Mostly ,they are elements in G1 and GT , sometime Big objects) into files, and reload it in Decryption program , is there a way to do this kind of work? Functions in Miracl or from other libs? More specifically, Can I just save the element in G1 to bytes . By call G1 a; std::cout << sizeof(a) << std::endl; It outpus 40. Can I just save the 40 bytes and reload it again? Is it possible?
There is a build functions spill and restore inside G1, G2 and GT classes. you can use them to spill G1 into a char* and restore G1 back using char*. For example:- pfc.precomp_for_mult(Q); // precomputation based on fixed point Q char *bytes; int len=Q.spill(bytes); // allocates byte array of length len .. // ..and spills precomputation into it Q.restore(bytes); // restores Q from byte array (and deletes array)