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
72,991,514
72,991,712
runtime error: addition of unsigned offset/UndefinedBehaviorSanitizer: undefined-behavior
I am not able to find where is my vector going out of bound. This is solution of leetcode question 695. Error: Line 1034: Char 34: runtime error: addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028 (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: int maxAreaOfIsland(vector<vector<int>>& grid) { int n = grid.size(); int m = grid[0].size(); vector<vector<int>> vis(n,vector<int>(m,0)); int ans =0 ; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int count = 0; if(grid[i][j]==1 && !vis[i][j]) { vis[i][j]=1; queue<pair<int,int>> q; q.push({i,j}); count++; while(!q.empty()) { int a = q.front().first; int b = q.front().second; q.pop(); int r[] = {-1, 1, 0, 0}; int c[] = {0, 0, 1, -1}; for(int z=0; z<4; z++) { int x = a + r[z]; int y = b + c[z]; if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) { vis[x][y]=1; q.push({x,y}); count++; } } } ans = max(ans,count); } } } return ans; }
I expect if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) { should be if (x>=0 && y>=0 && x<n && y<m && grid[x][y]==1 && !vis[x][y]) { Notice in the error addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028. In other words the unsigned offset is negative (when regarded as a signed quantity). Always be careful mixing signed and unsigned arithmetic.
72,991,965
72,993,204
C++20 concept fails to compile when template class object instantiated with value
Please refer to the following C++20 code: template<bool op> class Person { const bool own_pet; public: Person() : own_pet(op) {} consteval bool OwnPet() const { return own_pet; } consteval bool OwnPetC() const { return true; } void PatPet() const {} }; template<typename T> concept MustOwnPet = requires(T obj) { requires obj.OwnPet(); }; void pat(const MustOwnPet auto& p) { p.PatPet(); } template<typename T> concept MustOwnPetC = requires(T obj) { requires obj.OwnPetC(); }; void pat_c(const MustOwnPetC auto& p) { p.PatPet(); } int main() { // Error in gc 12.1 with -std=c++20: // in 'constexpr' expansion of 'obj.Person<true>::OwnPet()' // <source>:16:24: error: 'obj' is not a constant expression // Also doesn't compile in clang 14.0.0 with -std=c++20 // pat(Person<true>()); // Error in clang 14.0.0 with -std=c++20 // Compiles fine in gcc 12.1 with -std=c++20 pat_c(Person<true>()); return 0; } My understanding is that both Person::OwnPet() and Person::OwnPetC() are compile time functions as op is known as compile time as instantiated in main(). Then why the pat() fails to compile? Please see error in the code comment. And pat_c() fails to compile only in clang but compiles fine in gcc. Which compiler is correct?
The problem is that the parameter named obj is not a constant expression. Thus it cannot be used in an evaluated context where a constant expression is required. For example, we cannot use obj as a template nontype parameter(TNP) as TNP must be compile time constant which obj is not. Which compiler is correct? This seems to be a bug in gcc submitted here
72,992,551
72,992,714
Inaccuracy in code which returns the next permutation of an array
I was solving a question on leetcode with the description: The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). This is what I came up with in C++: void nextPermutation(vector<int>& nums) { int index = -1, j = nums.size() - 1; for (int i = nums.size() - 1; i > 0; i--) { if(nums[i - 1] < nums[i]) { index = i - 1; break; } } if(index == -1) { reverse(nums.begin(), nums.end()); return; } for (int i = nums.size() - 1; i >= index + 1; i--) { if(nums[i] > nums[index]) { j = i; } break; } swap(nums[index], nums[j]); reverse(nums.begin() + index + 1, nums.end()); } Here I traversed the array from left to right and look for an element which is smaller than the element on its right(named it index), and then traversed it again looking for a number just bigger than the number before and swapped them and then reversed the array after index This code works for the example cases but fails in a case where: Input: [2,3,1] MyOutput: [1,2,3] Expected Output: [3,1,2] I do not understand what I did wrong and everything should be working but its not.
Your issue is that the break statement in second loop is outside the if block. if (nums[i] > nums[index]) { j = i; } break; // <--------- this should be inside if Putting it inside, gives the correct result. if (nums[i] > nums[index]) { j = i; break; } Demo: https://godbolt.org/z/147We9c4q
72,992,713
72,996,020
Adding searcher in package.searchers with lua c api?
Issue I want require in lua to be able to find module in a game assets archive using Physfs. After some searche, i must add a c function to the package.searchers table ? I tried to do so, but sadly i can't manage to. I'm new to lua and embeding lua, so it is definitly not helping. One thing i don't get is, the package table and all the nested table in there are not global? I tried to add a lua function to the table (so lua side of things) and i get nothing because package is nil. With something like this: package.searchers[#package.searchers + 1] = function(name) print("searchers as been called.") end Edit For the package library (and the other one), here is how i basically load it : const luaL_Reg lualibs[] = { { LUA_COLIBNAME, luaopen_base }, { LUA_LOADLIBNAME, luaopen_package }, { LUA_TABLIBNAME, luaopen_table }, { LUA_IOLIBNAME, luaopen_io }, { LUA_OSLIBNAME, luaopen_os }, { LUA_STRLIBNAME, luaopen_string }, { LUA_MATHLIBNAME, luaopen_math }, { LUA_DBLIBNAME, luaopen_debug }, { NULL, NULL } }; lua_State* ls = luaL_newstate(); const luaL_Reg* lib = lualibs; for (; lib->func; lib++) { lua_pushcfunction(ls, lib->func); lua_pushstring(ls, lib->name); lua_call(ls, 1, 0); } Edit 2 Problem solved, thanks to Egor Skriptunoff's answere. All i have to do was loading the libraries with luaL_openlibs directly. then i can do something like that : lua_getglobal(_ls, LUA_LOADLIBNAME); if (!lua_istable(_ls, -1)) return; lua_getfield(_ls, -1, "searchers"); if (!lua_istable(_ls, -1)) return; lua_pushvalue(_ls, -2); lua_pushcclosure(_ls, mysearcher, 1); lua_rawseti(_ls, -2, 5); lua_setfield(_ls, -2, "searchers"); Some info I use LUA 5.4 It's a c++ project.
I guess i have to post and answere to mark this post as solved. First things, package table was not global because i was loading libraries wrong. i need to use luaL_requiref as mentioned by Egor Skriptunoff or directly luaL_openlibs. Then after that, because it is now global, i can just do something like that for exemple : lua_getglobal(_ls, LUA_LOADLIBNAME); if (!lua_istable(_ls, -1)) return; lua_getfield(_ls, -1, "searchers"); if (!lua_istable(_ls, -1)) return; lua_pushvalue(_ls, -2); lua_pushcclosure(_ls, mysearcher, 1); lua_rawseti(_ls, -2, 5); lua_setfield(_ls, -2, "searchers");
72,992,732
73,139,976
Pass pointer of a non static member function to another non static member object
NOTE: In this context, the term "ISR" is not really addressing ISR vectors. There are a lot of tricks in the drivers. One of them is handling with the interrupts generated by the radio tranceiver chip. SX1276_LoRaRadio driver has a thread that checks the actual interrupt source. This is because all these things are working on an rtos (mbed, based on RTX5) and the rtos does not allow direct access to the MCU interrupt vectors. So once PIN_X of the mcu is triggered, the thread reads the radio chip registers for the actual interrupt source. I am developing for an ARM MCU. There is a radio tranceiver chip (sx1276) on my board. The radio chip driver requires pointers to my own ISR member functions. Thus, I have to pass the pointers of the ISR member functions to another member object (a struct that keeps the pointers) of the same class. The detailed explanation is below. A low level radio driver handles with the device registers (SX1276_LoRaRadio.cpp). This is provided by the manufacturer and developed exactly for the framework I am using (mbed os). This inherits from LoRaRadio An API developed by the framwork developer (arm) provides a higher level pure virtual class for abstraction (LoRaRadio.h). My own radio comm stack exploits the other two in the application layer (ProtoTelecom.hpp and ProtoTelecom.cpp). The radio has some interrupt pins which are triggered in the occurance of some events. But i can use only one of them due to how the manufacturer designed the driver. This is explained at the very beginning. The events are members of a struct: // This is in LoRaRadio.h typedef struct radio_events { /** * Callback when Transmission is done. */ mbed::Callback<void()> tx_done; <other mbed::Callback type members> } radio_events_t; My ProtoTelecom.hpp looks like this: class ProtoTelecom: public manageCommands { public: explicit ProtoTelecom(LoRaRadio *Radio, tcm_Manager *tcm); static void OnTxDone(void); void nonstaticTxDone(void); <other corresponding ISR member functions> private: static radio_events_t RadioEvents; <other private stuff here> }; Then in ProtoTelecom.cpp I assign the pointers of the corresponding static member functions to the RadioEvents members: radio_events_t ProtoTelecom::RadioEvents = { .tx_done = ProtoTelecom::OnTxDone, <other pointer assignments> }; ProtoTelecom::ProtoTelecom(LoRaRadio *Radio, c_TC_Manager *tcm) : manageCommands() { <other stuff goes here> Radio->init_radio(&RadioEvents); } My problem is I have to have multiple instances of ProtoRadio. However, the radio isr functions must be static because passing member function pointers inside the class itself is not allowed in c++. This simply prevents me to initialize another hw because both execute the same isr functions. So how can I pass the pointer of a non static member function to another non static member object inside the class itself? Something like this: ProtoTelecom::ProtoTelecom(LoRaRadio *Radio, c_TC_Manager *tcm) : manageCommands() { <other stuff goes here> RadioEvents.tx_done = nonstaticTxDone; Radio->init_radio(&RadioEvents); } I found this thread but the case is slightly different than mine and I could not manage to adapt it to my situation. The main theme of my question is the title but I know that what I am trying to achive is a bit strange and requires some tricks. So if there are other ways to achive my final goal that is also okay for me. Thanks.
As @Wutz stated in his third comment, the correct way is using mbed::Callback. Here is my new constructor: ProtoTelecom::ProtoTelecom(LoRaRadio *Radio, c_TC_Manager *tcm) : manageCommands() { this->Radio = Radio; this->tcm = tcm; //Inizialize the radio newRadioEvents.tx_done = mbed::Callback<void()>(this, &ProtoTelecom::nonstaticOnTxDone); newRadioEvents.tx_timeout = mbed::Callback<void()>(this, &ProtoTelecom::nonstaticOnTxTimeout); newRadioEvents.rx_done = mbed::Callback<void(const uint8_t *, uint16_t , int16_t , int8_t)>(this, &ProtoTelecom::nonstaticOnRxDone); newRadioEvents.rx_timeout = mbed::Callback<void()>(this, &ProtoTelecom::nonstaticOnRxTimeout); newRadioEvents.rx_error = mbed::Callback<void()>(this, &ProtoTelecom::nonstaticOnRxError); Radio->init_radio( &newRadioEvents ); switchModem(radio_mode); setState(RADIO_RECEIVE); } The newRadioEvents is a non static instance of radio_events_t.
72,992,809
72,997,115
CEF - how to get a variable from JS to С++
Please help me, I've been suffering for two weeks, I can't understand if it's possible in CEF to get the value of a variable from the JS code to a C++ variable? For example: I am executing js code in a browser window using the method CefFrame::ExecuteJavaScript: (*frame).GetMainFrame()).ExecuteJavaScript("const elem = document.getElementsByClassName("my_class")[0];const rect = elem.getBoundingClientRect(); alert(rect.x + \":\" + rect.y)", "", 1); And everything works great, but only "inside" javascript. Here's the question: is it possible to somehow get the value of a variable to a rect.x to pull out and put in a C++ variable int rect_x ?
You might have noticed, if you type rect.x in the console in the developer tools, it echoes the variable value. It should have hinted you, how to retrieve variable values. CefRefPtr<CefV8Context> v8_context = frame->GetMainFrame()->GetV8Context(); if (v8_context.get() && v8_context->Enter()) { CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; if (v8_context->Eval("rect.x", "", 0, retval, exception)) { int rect_x = retval->GetIntValue() } v8_context->Exit(); }
72,992,990
72,996,355
Possible causes for icc (2019) with -O3 -march=native on Xeon Gold 6126 producing slower exe than -O3 -xCORE-AVX512?
The purpose of the question is to ask about possible causes regarding the program's behaviour as a function of icc 2019's compilation flags, considering two phenomena and the information provided in the notes below. A program can run three types of simulations, let's name them S1, S2 and S3. Compiled (and ran) on Intel Xeon Gold 6126 nodes the program has the following behaviour, expressed as A ± B where A is the mean time, B is the standard deviation, and the units are microseconds. When compiled with -O3: S1: 104.7612 ± 108.7875 EDIT: it's 198.4268 ± 3.5362 S2: 3.8355 ± 1.3025 EDIT: it's 3.7734 ± 0.1851 S3: 11.8315 ± 3.5765 EDIT: it's 11.4969 ± 1.313 When compiled with -O3 -march=native: S1: 102.0844 ± 105.1637 EDIT: it's 193.8428 ± 3.0464 S2: 3.7368±1.1518 EDIT: it's 3.6966 ± 0.1821 S3: 12.6182 ± 3.2796 EDIT: it's 12.2893 ± 0.2156 When compiled with -O3 -xCORE-AVX512: S1: 101.4781 ± 104.0695 EDIT: it's 192.977±3.0254 S2: 3.722 ± 1.1538 EDIT: it's 3.6816 ± 0.162 S3: 12.3629 ± 3.3131 EDIT: it's 12.0307 ± 0.2232 Two conclusions: -xCORE-AVX512 produces code that is more performant than -march=native the program's simulation called S3 DECREASES its performance when compiled considering the architecture. Note1: the standard deviation is huge, but repeated tests yield always similar values for the mean that leave the overall ranking unchanged. Note2: the code runs on 24 processors and Xeon Gold 6126 has 12 physical cores. It's hyper-threading but each two threads per core DO NOT share memory. Note3: the functions of S3 are "very sequential", i.e. cannot be vectorized. There is no MWE. Sorry, the code is huge and cannot be posted here. EDIT: print-related outliers were to blame for the large deviation. The means were slightly changed but the trend and hierarchies remains.
An acceptable possible explanation was outlined in the comments, it read: Tiny differences in tuning choices for code-gen might result in alignment differences that end up mattering more. Especially How can I mitigate the impact of the Intel jcc erratum on gcc? on Skylake-family CPUs if -march=native or -xCORE-AVX512 didn't enable a workaround option. Further readings: 32-byte aligned routine does not fit the uops cache Intel JCC Erratum - should JCC really be treated separately?
72,993,218
72,993,401
C++ iterator for map derived class
I have a class that internally has an instance of map: template<typename K, typename V> class my_map { private: std::map<K, V> mmap; Internally to the class I need to create an iterator for templated types, how can I do this?
To avoid confusion with typename keyword. I suggest to do the following template<typename K, typename V> class my_map { private: std::map<K, V> mmap; public: typedef typename std::map<K, V>::iterator iterator; typedef typename std::map<K, V>::const_iterator const_iterator; iterator begin() {return mmap.begin();} const_iterator begin() const {return mmap.begin();} . . . }; You can now use it as my_map<K, V>::iterator or my_map<K, V>::const_iterator.
72,993,691
73,177,082
Disagreement between GCC and clang about "typename" keyword
I was compiling the following code and GCC seems to accept the following code. #include <map> template<typename K, typename V> class my_map { private: std::map<K, V> mmap; public: typedef std::map<K, V>::iterator iterator; typedef std::map<K, V>::const_iterator const_iterator; iterator begin() {return mmap.begin();} const_iterator begin() const {return mmap.begin();} }; int main() { my_map<int, int>::iterator whatever; return 0; } But clang complains about the missing typename keyword. The complaint of clang makes more sense to me. Is this a GCC bug? Edit: Obviously, Where and why do I have to put the "template" and "typename" keywords? does not answer my question, as I am not asking what typename keyword is, but asking about different behaviors of compilers. Edit: Now the program is accepted by both clang(from version 16) and gcc.
asking about different behaviors of compilers. It seems that Clang has not implemented this C++20 feature yet. This can be seen from compiler support documentation. This means clang is not standard compliant. C++20 feature Paper(s) GCC Clang MSVC Apple Clang Allow lambda-capture [=, this] P0409R2 8 6 19.22* 10.0.0* Make typename more optional P0634R3 9 19.29 (16.10)* Pack expansion in lambda init-capture P0780R2 9 9 19.22* 11.0.3* As we can see in the above above table, the entry for clang corresponding to "Make typename more optional" is blank. On the other hand GCC and MSVC have implemented this C++20 feature and so are standard compliant. GCC and MSVC Demo Update As of 03/11/2022, clang supports this with version 16 as shown in the updated table below: C++20 feature Paper(s) GCC Clang MSVC Apple Clang Allow lambda-capture [=, this] P0409R2 8 6 19.22* 10.0.0* Make typename more optional P0634R3 9 16 19.29 (16.10)* Pack expansion in lambda init-capture P0780R2 9 9 19.22* 11.0.3* The program compiles with clang trunk.
72,993,739
72,994,105
How to pass reference value to a std::function from one class to another class
I have the following scenario. File Box.h #pragma once #include <functional> class Box { public: Box() :m_data(45) {} void set_callback(std::function<int(int, int& c)> cb) { f = cb; } auto get_box_dimension(void) { return f(4,m_data); } private: std::function<int(int, int&)> f; int m_data; }; File SquareBox.h #pragma once #include <functional> class SquareBox { public: int sq_func(int a, int& b) { return a * b; } private: }; File main.cpp #include<iostream> #include<functional> #include"Box.h" #include"SquareBox.h" int main() { int x = 1; int a = 5; Box b; SquareBox sq_box; b.set_callback(std::bind(&SquareBox::sq_func,&sq_box,a,x)); int ret_val = b.get_box_dimension(); std::cout << "Return Value == " << ret_val << std::endl; return 0; } I was expecting the answer to be 5 times 45 . 45 being passed from the class Box. But the answer is 5. How can I make sure that the sq_func receives the value of second argument from class Box m_data ?
std::bind is rather old-fashioned and quirky. Most uses are simpler with a lambda expression. Specifically you tripped over this detail (see cppreference): If some of the arguments that are supplied in the call to g() are not matched by any placeholders stored in g, the unused arguments are evaluated and discarded. In other words: Apart from the implicit this, sq_func takes 2 parameters, you already bound 2 hence the two parameters passed when you call f(4,m_data) are discarded. You should only bind the parameters that you will not pass later and use placeholders for the ones you do not want to bind (_1,_2,etc). If you want to capture sq_box and a then the resulting callable has only a single argument not two. I don't understand why you bind x nor why you pass 4 when calling it. Anyhow, you get expected output when you change the function type to std::function<int(int&)> and use a lambda expression to bind the parameters: #include <functional> #include <iostream> struct Box { Box() :m_data(45) {} void set_callback(std::function<int(int& c)> cb) { f = cb; } auto get_box_dimension() { return f(m_data); } private: std::function<int(int&)> f; int m_data; }; struct SquareBox { int sq_func(int a, int& b) { return a * b; } }; int main() { int a = 5; Box b; SquareBox sq_box; b.set_callback([&sq_box,a](int& v){ return sq_box.sq_func(a,v);}); int ret_val = b.get_box_dimension(); std::cout << "Return Value == " << ret_val << std::endl; } Note that I captured a by value. If you want to set eg a = 42 and then calling b.get_box_dimension() should reflect that you can capture it by reference as well.
72,993,742
72,993,840
Don't print space after last value with iterator
I'm having a problem with a beginner concept in competitive programming extra space in print may cause wrong answer judgment I want to iterate through a container like map or set but last value should not have a space #include <iostream> #include <set> using namespace std; int main() { set<int> st = {1,2,3}; for(auto x : st){ cout<<x<<" "; } return 0; } why can't I do this set<int> st = {1,2,3}; for(auto x = st.begin(); st!=end();x++){ if(x!=st.end()-2) cout<<x<<" "; else cout<<x; }
The standard class templates std::set and std::map do not have random access iterators. So this expression x!=st.end()-2 is invalid. If you compiler supports C++ 20 then you may write for example set<int> st = {1,2,3}; for( size_t i = 0; auto x : st){ if ( i++ != 0 ) std::cout << ' '; cout << x ; } Or you could use a boolean variable instead of the variable i with the type size_t. In any case you can declare the variable before the range-based for loop as for example set<int> st = {1,2,3}; bool first = true; for( auto x : st){ if ( !first ) { std::cout << ' '; } else { first = false; } cout << x ; } If to use an ordinary for loop with iterators then you can write for ( auto it = st.begin(); it != st.end(); it++) { if ( it != st.begin() ) std::cout << ' '; std::cout << *it; }
72,993,789
72,993,850
What memory adress are we referencing to when we use a const reference to an rvalue
Consider the follwoing code: int main() { const int& number=10; cout << number << endl << &number << endl; return 0; } As output I get: 10 0x62ff08 As far as I know "10" is an rvalue without memory adress, so where does the memory adress come from?
When you wrote: //------------------vv---->10 is a prvalue and temporary materialization will result in an xvalue const int& number = 10; temporary materialization happens as can be seen from temporary materilization: Temporary materialization occurs in the following situations: when binding a reference to a prvalue; Now number refers to the materialized temporary(xvalue). Moreover the lifetime of the temporary is extended as can be seen from lifetime The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
72,994,189
72,994,414
Strange C++ delete[] statement in MS C++
On some very old code base, we have this kind of statement: delete [i+4] v; Where v is indeed an array and i is an integer. This code is in VS2010 but still compiles in VS2019. Working demo What's the meaning of this? Is it, or was it something specific to Microsoft C++?
delete [i+4] v; where v is pointing to a dynamic array that was created using new is not valid in C++. This seems to be a msvc bug which has been submitted here.
72,994,320
72,994,790
Building CMake project with Boost libraries on GitHub Actions gives error "Could NOT find Boost"
I'm trying to build my CMake project on GitHub Actions workflow. Everything is working locally on Ubuntu 22.04 LTS and building a Docker image, but not when using the same OS on GitHub Actions. The error is the following: CMake Error at /usr/local/share/cmake-3.23/Modules/FindPackageHandleStandardArgs.cmake:230 (message): Could NOT find Boost (missing: Boost_INCLUDE_DIR system filesystem thread date_time chrono regex serialization program_options) Call Stack (most recent call first): /usr/local/share/cmake-3.23/Modules/FindPackageHandleStandardArgs.cmake:594 (_FPHSA_FAILURE_MESSAGE) /usr/local/share/cmake-3.23/Modules/FindBoost.cmake:2376 (find_package_handle_standard_args) CMakeLists.txt:261 (find_package) My GitHub Actions workflow job: install: name: Install Dependencies runs-on: ubuntu-22.04 needs: [ clean ] steps: - uses: actions/checkout@v2 - name: Install General run: | sudo apt-get update sudo apt-get install -y build-essential libboost-all-dev libssl-dev libffi-dev python3-dev gcc-11 g++-11 git cmake librocksdb-dev cron rpcbind libboost-system1.74.0 libboost-filesystem1.74.0 libboost-thread1.74.0 libboost-date-time1.74.0 libboost-chrono1.74.0 libboost-regex1.74.0 libboost-serialization1.74.0 libboost-program-options1.74.0 libicu70 build: name: Build Target runs-on: ubuntu-22.04 needs: [ install ] steps: - uses: actions/checkout@v2 - name: Create Build Dir run: mkdir build - name: CMake run: cmake -DCMAKE_CXX_FLAGS="-g0 -Os -fPIC -std=gnu++17" -DBoost_DEBUG=ON -DBoost_ARCHITECTURE=-x64 .. working-directory: build - name: Make run: make -j$(nproc) --ignore-errors working-directory: build My CMake configuration of Boost: set(Boost_NO_BOOST_CMAKE ON) set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_STATIC_RUNTIME ON) find_package(Boost REQUIRED COMPONENTS system filesystem thread date_time chrono regex serialization program_options) message(STATUS "Boost Found: ${Boost_INCLUDE_DIRS}") include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) When building it in a Docker container with Ubuntu 22.04 LTS it works without any problems. My Dockerfile: FROM ubuntu:22.04 COPY . /usr/src/project_name WORKDIR /usr/src/project_name # install build dependencies RUN apt-get update && \ apt-get install -y \ build-essential \ libssl-dev \ libffi-dev \ python3-dev \ gcc-11 \ g++-11 \ git \ cmake \ librocksdb-dev \ libboost-all-dev \ libboost-system1.74.0 \ libboost-filesystem1.74.0 \ libboost-thread1.74.0 \ libboost-date-time1.74.0 \ libboost-chrono1.74.0 \ libboost-regex1.74.0 \ libboost-serialization1.74.0 \ libboost-program-options1.74.0 \ libicu70 # create the build directory RUN mkdir build WORKDIR /usr/src/project_name/build # build and install RUN cmake -DCMAKE_CXX_FLAGS="-g0 -Os -fPIC -std=gnu++17" .. && make -j$(nproc) --ignore-errors WORKDIR /usr/src/project_name/build/src All of the dependencies are installed on the GitHub runner with a job before. Any ideas why this might occur? Anyone else had this issue? I can post the CMake debug info if requested.
github.com will give you a fresh runner for every job. See here https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#using-a-github-hosted-runner for details. Thus it is not possible to prepare the machine in one job and use it in a later job. You should move the installation of the needed packages inside your build job. In case you need to exchange artifacts, like binaries from one job to a later job, you should take a look at the github actions upload-artifact and download-artifact.
72,994,701
72,995,350
How to convert a vector of parent pointers to another in c++?
How to convert two parent pointers in c++? This is the code. // base class class B { public: virtual ~B() {}; // other code }; class A { public: virtual ~A() {}; // other code }; // child class class C1 : public A, B { public: virtual ~C1() {}; // other code }; class C2 : public A, B { public: virtual ~C2() {}; // other code }; // ...other C class There is a std::vector<std::shared_ptr<A>> which items point to instance C1 or C2 ...Cn. Does anyone know how to convert the vector to a std::vector<std::shared_ptr<B>>?
Your code has typos. Missing public in inheritance of B when defining C<x> breaks stuff. After this is fixed sidecast does the job as it should: dynamic_cast conversion - cppreference.com b) Otherwise, if expression points/refers to a public base of the most derived object, and, simultaneously, the most derived object has an unambiguous public base class of type Derived, the result of the cast points/refers to that Derived (This is known as a "sidecast".) // base class class B { public: virtual ~B() { } }; class A { public: virtual ~A() { } }; class C1 : public A, public B { public: virtual ~C1() { } }; class C2 : public A, public B { public: virtual ~C2() { } }; TEST(SideCast, sigleItemCast) { C2 x; A* a = &x; auto b = dynamic_cast<B*>(a); ASSERT_THAT(b, testing::NotNull()); } TEST(SideCast, sideCastOfVectorContent) { std::vector<std::shared_ptr<A>> v { std::make_shared<C1>(), std::make_shared<C2>() }; std::vector<std::shared_ptr<B>> x; std::transform(v.begin(), v.end(), std::back_inserter(x), [](auto p) { return std::dynamic_pointer_cast<B>(p); }); ASSERT_THAT(x, testing::Each(testing::NotNull())); } Live demo
72,994,895
73,045,940
constructing completely private and anonymous static singleton
I was trying to think of a way how to deal with C libraries that expect you to globally initialize them and I came up with this: namespace { class curl_guard { public: curl_guard() { puts("curl_guard constructor"); // TODO: curl_global_init } ~curl_guard() { puts("curl_guard destructor"); // TODO: curl_global_cleanup } }; curl_guard curl{}; // nothing is ever printed to terminal } But when I link this into an executable and run it, there's no output, because it is optimized out (verified with objdump), even in debug build. As I understand, this is intended, because this type is never accessed in any way. Is there any way to mark it so that it is not excluded? Preferably without making it accessible to the user of the library. I'd prefer a general solution, but GCC-only also works for my purposes. I am aware of typical singleton patterns, but I think this is a special case where none of them apply, because I never want to access this even from internals, just simply have a class tucked away which has one simple job of initializing and deinitializing a C library which is caused by the library being linked in and not something arbitrary like "just don't forget to construct this in main" which is as useful as going back to writing C code.
The real solution was pretty simple - the code can't be separate and needs to be in one of compilation units that are used by the user of the library. libcurl needs to be initialized globally, and initialization is NOT thread safe, because libraries it depends on also cannot be initialized in thread-safe manner, so it is one of those things where global pre-main initialization is not only convenient, but useful. I in fact am using several other libraries which are like that, and I separate them from libraries that do use threads in the background, by putting those in the main as opposed to pre-main. And while there are some concerns with doing something like this at all, that's exactly what I need, including library aborting before main even runs if it's installed improperly. Sure, it's "good practice" to ignore critical errors just to please the users of libraries who insist on libraries aborting being oh so terrible, but I'm sure noone likes to know that in next 50 seconds, they will be dead due to flying vertically downwards due to something that could've been found and fixed early.
72,994,952
72,999,085
Convert Gdiplus::Region to ID2D1Geometry* for clipping
I am trying to migrate my graphics interface project from Gdiplus to Direct2D. Currently, I have a code that calculates clipping area for an rendering object: Graphics g(hdc); Region regC = Rect(x, y, cx + padding[2] + padding[0], cy + padding[3] + padding[1]); RecursRegPos(this->parent, &regC); RecursRegClip(this->parent, &regC); g.setClip(g); ... inline void RecursRegClip(Object *parent, Region* reg) { if (parent == CARD_PARENT) return; if (parent->overflow != OVISIBLE) { Rect regC(parent->getAbsoluteX(), parent->getAbsoluteY(), parent->getCx(), parent->getCy()); // Implementation of these function is not necceassary GraphicsPath path; path.Reset(); GetRoundRectPath(&path, regC, parent->borderRadius[0]); // source https://stackoverflow.com/a/71431813/15220214, but if diameter is zero, just plain rect is returned reg->Intersect(&path); } RecursRegClip(parent->parent, reg); } inline void RecursRegPos(Object* parent, Rect* reg) { if (parent == CARD_PARENT) return; reg->X += parent->getX() + parent->padding[0]; reg->Y += parent->getY() + parent->padding[1]; if (parent->overflow == OSCROLL || parent->overflow == OSCROLLH) { reg->X -= parent->scrollLeft; reg->Y -= parent->scrollTop; } RecursRegPos(parent->parent, reg); } And now I need to convert it to Direct2D. As You may notice, there is no need to create Graphics object to get complete calculated clipping region, so I it would be cool if there is way to just convert Region to ID2D1Geometry*, that, as far, as I understand from msdn article need to create clipping layer. Also, there is probably way to convert existing code (RecursRegClip, RecursRegPos) to Direct2D, but I am facing problems, because I need to work with path, but current functions get region as an argument. Update 1 There is Region::GetData method that returns, as I understand array of points, so maybe there is possibility to define either ID2D1PathGeometry or ID2D1GeometrySink by points? Update 2 Oh, maybe ID2D1GeometrySink::AddLines(const D2D1_POINT_2F *points, UINT32 pointsCount) is what do I need? Unfortunately, GetData of region based on just (0,0,4,4) rectangle returns 36 mystique values: Region reg(Rect(0, 0, 4, 4)); auto so = reg.GetDataSize(); BYTE* are = new BYTE[so]; UINT fi = 0; reg.GetData(are, so, &fi); wchar_t ou[1024]=L"\0"; for (int i = 0; i < fi; i++) { wchar_t buf[10] = L""; _itow_s(are[i], buf, 10, 10); wcscat_s(ou, 1024, buf); wcscat_s(ou, 1024, L", "); } // ou - 28, 0, 0, 0, 188, 90, 187, 128, 2, 16, 192, 219, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 64, 0, 0, 128, 64,
I rewrote the solution completely, it seems to be working: // zclip is ID2D1PathGeometry* inline void Render(ID2D1HwndRenderTarget *target) { ID2D1RoundedRectangleGeometry* mask = nullptr; ID2D1Layer* clip = nullptr; if(ONE_OF_PARENTS_CLIPS_THIS || THIS_HAS_BORDER_RADIUS) { Region reg = Rect(x, y, cx + padding[2] + padding[0], cy + padding[3] + padding[1]); RecursRegPos(this->parent, &reg); D2D1_ROUNDED_RECT maskRect; maskRect.rect.left = reg.X; maskRect.rect.top = reg.Y; maskRect.rect.right = reg.X + reg.Width; maskRect.rect.bottom = reg.Y + reg.Height; maskRect.radiusX = this->borderRadius[0]; maskRect.radiusY = this->borderRadius[1]; factory->CreateRoundedRectangleGeometry(maskRect, &mask); RecursGeoClip(this->parent, mask); target->CreateLayer(NULL, &clip); if(zclip) target->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), zclip), clip); else target->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), mask), clip); SafeRelease(&mask); } // Draw stuff here if (clip) { target->PopLayer(); SafeRelease(&clip); SafeRelease(&mask); SafeRelease(&zclip); } } ... inline void RecursGeoClip(Object* parent, ID2D1Geometry* geo) { if (parent == CARD_PARENT) return; ID2D1RoundedRectangleGeometry* maskParent = nullptr; if (parent->overflow != OVISIBLE) { Rect regC(parent->getAbsoluteX(), parent->getAbsoluteY(), parent->getCx(), parent->getCy()); ID2D1GeometrySink* sink = nullptr; ID2D1PathGeometry* path = nullptr; SafeRelease(&path); factory->CreatePathGeometry(&path); D2D1_ROUNDED_RECT maskRect; maskRect.rect.left = regC.X; maskRect.rect.top = regC.Y; maskRect.rect.right = regC.X + regC.Width; maskRect.rect.bottom = regC.Y + regC.Height; maskRect.radiusX = parent->borderRadius[0]; maskRect.radiusY = parent->borderRadius[1]; path->Open(&sink); factory->CreateRoundedRectangleGeometry(maskRect, &maskParent); geo->CombineWithGeometry(maskParent, D2D1_COMBINE_MODE_INTERSECT, NULL, sink); sink->Close(); SafeRelease(&sink); SafeRelease(&this->zclip); this->zclip = path; RecursGeoClip(parent->parent, this->zclip); } else RecursGeoClip(parent->parent, geo); SafeRelease(&maskParent); } Now I can enjoy drawing one image and two rectangles in more than 60 fps, instead of 27 (in case of 200x200 image size, higher size - lower fps) with Gdi+ -_- :
72,995,554
73,019,268
How to use cppcheck-suppress command to elimnate the error about "a parameter should be passed by reference"
In function "writeFile" below it has the following signature: writeFile(std::string fileId, std::string otherVariable){} when I run it, an error: Function parameter 'aFileId' should be passed by const reference. [passedByValue] is recieved. However I don't want to pass it by const reference because the function is going to be binary incompatiable with other files. I wanted to do a "cppcheck suppress" to make it igone this. I tried the following // cppcheck-suppress aFileId writeFile(std::string aFileId, std::string otherVariable){} but it does not really work and I still get the same error. To clarify more, I tried this as well... writeFile(std::string aFileId, // cppcheck-suppress aFileId std::string otherVariable) { // stuff }
You have to activate inline suppressions in general when calling cppcheck. Add the command line option --inline-suppr.
72,995,769
72,995,950
Using Boost Python 3.10 and C++ Classes
I'm really confused with initialzing C++ classes when usign boost::python. When compiling the follwing code with CMake I get no error, warning or something else at all: #include <boost/python.hpp> #include <iostream> class Test { public: Test(int x); ~Test(); }; void greet() { Test test(10); std::cout << "Test" << std::endl; } BOOST_PYTHON_MODULE(libTestName) { Py_Initialize(); using namespace boost::python; def("greet", greet); } With the follwoing CMakeLists.txt: cmake_minimum_required (VERSION 3.8) project (libTestLib) IF(NOT CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE "RELEASE") ENDIF() # Add all the files to the library so it can get created ADD_LIBRARY(TestLib SHARED main.cpp) # Set the Flags and the CXX command set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fconcepts") set(boostPython python3) find_package(PythonInterp 3.6 REQUIRED) find_package(PythonLibs 3.6 REQUIRED) include_directories(${PYTHON_INCLUDE_DIRS}) set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) FIND_PACKAGE(Boost REQUIRED COMPONENTS system program_options numpy ${boostPython}) if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) target_link_libraries(TestLib ${Boost_LIBRARIES} ${PYTHON_LIBRARIES}) else() message(FATAL_ERROR "Could not find boost.") endif() I get the follwoing error code when I try to import this lib into Python: >>> import build.libPathFinding Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: path/to/lib/libTestLib.so: undefined symbol: _ZN4TestD1Ev I fuígured out that it is possible to create a pointer to a new object with the follwoing code: void greet() { Test *test = new Test(10); std::cout << "Test" << std::endl; } But then I'm unable to free this pointer again by using delete because I'll get again an import error from Python.
Just use a constructor and destructor like: #include <boost/python.hpp> #include <iostream> class Test { public: Test(int x) {}; // Change ~Test() {}; // Change }; void greet() { Test test(10); std::cout << "Test" << std::endl; } BOOST_PYTHON_MODULE(libTestName) { Py_Initialize(); using namespace boost::python; def("greet", greet); }
72,995,844
72,997,881
c++ 17 std::filesystem can not run on other (windows 10) computer
I have a program, compiled using MinGW on and for windows 10, I want this program to run on other peoples computers, even if they do not have MinGW or any c++ compilers installed. Normally, this is easy. I just include the exe file and the dll files for any third party libraries, and it does indeed work ... unless I use one particular c++ standard library, the <filesystem> library from c++ 17, in which case my program can only run on the computer which did the compiling. For example, this program only prints what file it is currently in to a file. #include<fstream> #include<filesystem> using namespace std; int main(int argc, char* argv[]) { ofstream OUT("location.txt"); OUT<<filesystem::current_path()<<endl; OUT.close(); return 0; } I compile it with mingw32 as such: g++ stupid_program.cpp -o stupid_program.exe -std=c++17 -O2 -Wall -Wextra -Wpedantic This does work on the Windows 10 computer which did the compiling, running from terminal (or doubleclicking the .exe) file to creates a file containing the current executing location. However if I move this .exe file to another windows 10 computer, which did not compile it, doubleclicking the .exe file now causes an error popup to appear, teling me that the entrypoint _ZNKSt10filesystem7_cxx114path5_list13_impl_deletercIEPN"_5_ImpIE could not be found in the DLL-library C:\PATH_TO_PROGRAM\stupid_program.exe. But the filesystem library does not have any .dll file, because it is part of the standard library. I know the filesystem is a recent addition to the standard ... but I did include the argument -std=c++17 and that should have taken care of that. So is there any way I can make a program, which does use the filesystem library, work on some other Windows 10 computer than the one which compiled it? g++ is version 9.2.0 g++.exe (MinGW.org GCC Build-2) 9.2.0 Note, there was an old bug with older MinGW with g++ version 8.xx where the filesystem library could not compile, this is not it, because that bug completely prevented compilation; this cam compile, and run, just only on the compiling computer
Did you check that the libstdc++-6.dll Is available or the relevant libraries are statically included static linked libs
72,995,849
72,996,088
Statically build and linking with CMake
I'm trying to wrap my head around statically linking c++ applications using CMake. I have built libcurl statically: ./buildconf ./configure --disable-shared --with-openssl make -j$(nproc) make install Which produces a static /usr/local/lib/libcurl.a: $ ldd /usr/local/lib/libcurl.a not a dynamic executable My CMake is configured to build and link statically: include(CMakePrintHelpers) cmake_minimum_required(VERSION 3.17) project(static-build-test) set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") set(BUILD_SHARED_LIBS OFF) set(CMAKE_EXE_LINKER_FLAGS "-static") find_package(CURL REQUIRED) cmake_print_variables(CURL_LIBRARIES) add_executable(static-test main.cpp) target_link_libraries(static-test PRIVATE ${CURL_LIBRARIES}) But my build fails to link with many "undefined reference to" errors: $ make Scanning dependencies of target static-test [ 50%] Building CXX object CMakeFiles/static-test.dir/main.cpp.o [100%] Linking CXX executable static-test ... url.c:(.text+0xf6): undefined reference to `idn2_free' md5.c:(.text+0x6a): undefined reference to `MD5_Init' openssl.c:(.text+0x29a): undefined reference to `SSL_set_ex_data' ... My static build for libcurl.a completed without error but still fails to link with my application due to these undefined references. Why doesn't the static library for libcurl include the static libraries it depends on (openssl, etc.)? I presume I need to find all these missing references and track down their static libs as well. Is it that I need to link ALL of these libraries directly to my final executable?
For libraries, like CURL, that have first-class CMake package support, you should use it. Here is how I linked to CURL statically. First, we download and build CURL: $ git clone git@github.com:curl/curl.git $ cmake -G Ninja -S curl/ -B _build/curl -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=NO $ cmake --build _build/curl $ cmake --install _build/curl --prefix _local After this, we can write the correct CMakeLists.txt, which only links to imported targets. Notice that this build uses no variables. cmake_minimum_required(VERSION 3.23) project(test) find_package(CURL REQUIRED) add_executable(static-test main.cpp) target_link_libraries(static-test PRIVATE CURL::libcurl) And now we can build this, pointing CMake to our freshly built CURL package, via CMAKE_PREFIX_PATH: $ cmake -G Ninja -S . -B _build/test -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=$PWD/_local ... -- Found CURL: /path/to/_local/lib/cmake/CURL/CURLConfig.cmake (found version "7.85.0-DEV") -- Configuring done -- Generating done -- Build files have been written to: /path/to/_build/test and now we can run the build and see that all of the required libraries are there: $ cmake --build _build/test --verbose [1/2] /usr/bin/c++ -DCURL_STATICLIB -isystem /path/to/_local/include -O3 -DNDEBUG -MD -MT CMakeFiles/static-test.dir/main.cpp.o -MF CMakeFiles/static-test.dir/main.cpp.o.d -o CMakeFiles/static-test.dir/main.cpp.o -c /usr/local/google/home/reinking/test/main.cpp [2/3] : && /usr/bin/c++ -O3 -DNDEBUG CMakeFiles/static-test.dir/main.cpp.o -o static-test ../../_local/lib/libcurl.a -ldl -lpthread /usr/lib/x86_64-linux-gnu/libssl.so /usr/lib/x86_64-linux-gnu/libcrypto.so /usr/lib/x86_64-linux-gnu/libz.so && : As you can see, curl and its transitive dependencies, dl, pthreads, openssl, libcrypto, and libz, all appear correctly on the link line.
72,996,011
72,996,692
C++ program gives up when reading large binary file
I'm using a file from the MNIST website as an example; specifically, t10k-images-idx3-ubyte.gz. To reproduce my problem, download that file and unzip it, and you should get a file named t10k-images.idx3-ubyte, which is the file we're reading from. My problem is that when I try to read bytes from this file in one big block, it seems to read a bit of it and then sort of gives up. Below is a bit of C++ code that attempts to read (almost) all of the file at once, and then dumps it into a text file for debugging purposes. (Excuse me for the unnecessary #includes.) For context, the file is a binary file whose first 16 bytes are magic numbers, which is why I seek to byte 16 before reading it. Bytes 16 to the end are raw greyscale pixel values of 10,000 images of size 28 x 28. #include <array> #include <iostream> #include <fstream> #include <string> #include <exception> #include <vector> int main() { try { std::string path = R"(Drive:\Path\To\t10k-images.idx3-ubyte)"; std::ifstream inputStream {path}; inputStream.seekg(16); // Skip the magic numbers at the beginning. char* arrayBuffer = new char[28 * 28 * 10000]; // Allocate memory for 10,000 greyscale images of size 28 x 28. inputStream.read(arrayBuffer, 28 * 28 * 10000); std::ofstream output {R"(Drive:\Path\To\PixelBuffer.txt)"}; // Output file for debugging. for (size_t i = 0; i < 28 * 28 * 10000; i++) { output << static_cast<short>(arrayBuffer[i]); // Below prints a new line after every 28 pixels. if ((i + 1) % 28 == 0) { output << "\n"; } else { output << " "; } } std::cout << inputStream.good() << std::endl; std::cout << "WTF?" << std::endl; // LOL. I just use this to check that everything's actually been executed, because sometimes the program shits itself and quits silently. delete[] arrayBuffer; } catch (const std::exception& e) { std::cout << e.what() << std::endl; } catch (...) { std::cout << "WTF happened!?!?" << std::endl; } return 0; } When you run the code (after modifying the paths appropriately), and check the output text file, you will see that the file initially contains legitimate byte values from the file (integers between -128 and 127, but mostly 0), but as you scroll down, you will find that after some legitimate values, the printed values becomes all the same (in my case either all 0 or all -51 for some reason). What you see may be different on your computer, but in any case, they would be what I assume to be uninitialised bytes. So it seems that ifstream::read() works for a while, but gives up and stops reading very quickly. Am I missing something basic? Like, is there a buffer limit on the amount of bytes I can read at once that I don't know about? EDIT Oh by the way I'm on Windows.
Concerning OPs code to open the binary file: std::ifstream inputStream {path}; It should be: std::ifstream inputStream(path, std::ios::binary); It's a common trap on Windows: A file stream should be opened with std::ios::binary to read or write binary files. cppreference.com has a nice explanation concerning this topic: Binary and text modes A text stream is an ordered sequence of characters that can be composed into lines; a line can be decomposed into zero or more characters plus a terminating '\n' (“newline”) character. Whether the last line requires a terminating '\n' is implementation-defined. Furthermore, characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert '\n' to '\r\n' on output, and convert '\r\n' to '\n' on input). Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if each of the following is true: The data consist of only printing characters and/or the control characters '\t' and '\n' (in particular, on Windows OS, the character '\0x1A' terminates input). No '\n' character is immediately preceded by space characters (such space characters may disappear when such output is later read as input). The last character is '\n'. A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equal the data that were earlier written out to that stream, except that an implementation is allowed to append an indeterminate number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state. It's a good idea to use the std::ios::binary for stream I/O of binary files on any platform. It doesn't have any effect on platforms where it doesn't make a difference (e.g. Linux).
72,996,356
72,996,937
How to find the Postion of all matching substrings in a QStringList
i am looking for a way to find the cell position of all matching substrings in a QStringList. The List is filled form a txt file looking like that: 10:36:50,590/2002/1800 10:36:50,621/2002/1801 10:36:50,652/2002/1802 10:36:50,684/2002/1803 10:36:50,715/2002/1803 10:36:50,746/2002/1803 10:36:50,777/2002/1803/0/0/Target_Hit 10:36:50,809/2002/1802 10:36:50,840/2002/1802 10:36:50,871/2002/1802 10:36:50,965/2000/1831/0/0/Target_Hit Each cell of the QStringList contain one line of the txt file. Now i want to find the absolut number of hits and postion of the cells conatining the substring "Target_Hit". I tried to find the number of it like that: int number_of_hits = List.indexOf(QRegExp(".*\Target_Hit$)); but that returns a -1 so i guess the QRegExp is incorrect.
You cannot use indexOf for this because it would only return you one index, and it seems that you are looking for multiple. I would read the file line by line, check each line if it contains what you are looking for, and take note of that, effectively this pseudo code: initialise a counter to zero. initialise a position list to an empty list. read each line check if the line contains the search string. if it does: append the position into a list and increment the counter. continue the next line. Then, at the end, you could have all that you desired to have.
72,996,800
72,996,897
how can i initialize a bi-dimensional vector in a class in C++?
I need to define its size in runtime, so I need a vector. I tried the following, but I get a compiling error: error: 'V' is not a type #include<iostream> #include<vector> class graph { private: int V; std::vector<int> row(V); std::vector<std::vector<int>> matrix(V,row); public: graph(int v): V(v) {} }; Is there something I am failing to understand? Is it even allowed to initialize a vector this way?
The compiler considers these lines: std::vector<int> row(V); std::vector<std::vector<int>> matrix(V,row); as member function declarations with parameters that have unknown types and omitted names. It seems what you need is to use the constructor's member initializer list instead, like the following: class graph { private: int V; std::vector<std::vector<int>> matrix; public: graph(int v): V(v), matrix( v, std::vector<int>( v ) ) {} };
72,996,984
72,997,030
what is this syntax mean is c++ "class_name: class_ptr_1(nullptr), class_ptr_2(nullptr) {}"
I am not able to understand the syntax of class_name: class_ptr_1(nullptr), class_ptr_2(nullptr) {}
It seems you mean class_name() : class_ptr_1(nullptr), class_ptr_2(nullptr) {} ^^^ It is a constructor definition with a mem-initializer list. That is the class data members class_ptr_1 and class_ptr_2 are initialized in the mem-initializer list. Here is an example #include <iostream> #include <string> struct Beginner { Beginner() : first_name( "Deepak" ), last_name( "Singh" ) { } std::string first_name; std::string last_name; }; int main() { Beginner beginner; std::cout << "first name: " << beginner.first_name << ", last name: " << beginner.last_name << '\n'; } The program output is first name: Deepak, last name: Singh
72,997,015
72,997,561
Calling-convention for the 'this' parameter on Linux x64
I have a scenario where I need to call a function from LLDB (but it could be any C++ API) on Linux x64, from an app written in a different language. For that reason, I need to properly understand the calling-convention and how the arguments are passed. I am trying to call SBDebugger::GetCommandInterpreter, defined as: lldb::SBCommandInterpreter GetCommandInterpreter(); The full header file can be found here: https://github.com/llvm-mirror/lldb/blob/master/include/lldb/API/SBDebugger.h My assumption was that the method would expect a pointer to SBDebugger as the this argument, in the RDI register. However, when calling the function that way, I get a segmentation fault. If I look at the disassembly of the function, I see: push %r13 push %r12 mov %rsi,%r12 push %rbp push %rbx mov %rdi,%rbx The function is reading from both RDI and RSI, despite only expecting the this argument. The only explanation I see is that the function is expecting this as a value rather than a reference. SBDebugger has a size of 16 bytes (one shared_ptr), and the calling convention states that a single 16 bytes parameter would be split into the RDI and RSI registers, which matches what I'm seeing. However, that doesn't make sense to me for multiple reasons: If this is passed by value, how would it work if the method has any side-effect? The changes wouldn't be reflected on the caller The System V ABI states that: If a C++ object has either a non-trivial copy constructor or a non-trivial destructor 11, it is passed by invisible reference. The SBDebugger does have a custom destructor and copy-constructor: SBDebugger(); SBDebugger(const lldb::SBDebugger &rhs); SBDebugger(const lldb::DebuggerSP &debugger_sp); ~SBDebugger(); Despite this, I tried calling the method by passing SBDebugger by value and it seems to work, but I get a segmentation fault later when I try to use the returned SBCommandInterpreter, so it's possible the method is only returning garbage. There is something I don't understand about this method call, but I haven't been able to figure out what. What value should I pass in what registers, and why?
I figured it out. I was focusing on the arguments but the trick was the return value. Quoting the System V calling convention: A struct, class or union object can be returned from a function in registers only if it is sufficiently small and not too complex. If the object is too complex or doesn't fit into the appropriate registers then the caller must supply storage space for the object and pass a pointer to this space as a parameter to the function. Basically, because SBCommandInterpreter is considered as a complex object, the GetCommandInterpreter expects an additional hidden parameter, which is the address to which the return value will be written. So the "real" method signature is: lldb::SBCommandInterpreter* GetCommandInterpreter(SBCommandInterpreter& returnValue, SBDebugger* this); So the this argument is passed by reference as expected, I was just missing an additional hidden argument.
72,998,188
72,998,722
getting N values from getline(cin) for different data types
I have created a program, which requires user to define at least 2 arguments(3rd is optional). Arguments are: Command(string type) Date(custom type/class) Event(string type) - Optional. I have come up with the following idea: int main() { Database db /*my custom class */ string command; vector<string> arguments; while (getline(cin, command, ' ')) { arguments.push_back(command); } and after that the idea was to use indexing for arguments: if(arguments[0] == "Add"){ Date date arguments[1]; db.Add(date,arguments[2]) } } else if(arguments[0] == "Find"){ Date date = arguments[1]; db.Find(date); But unfortunately, Date date = arguments[1]; doesn't work. How can I handle a problem of user input arguments with different data types, with one argument optional. Here is my Date class: class Date { public: Date(){ }; Date(int new_year, int new_month, int new_day){ if(new_month > 12 || new_month < 1){ throw invalid_argument("Month value is invalid: " + to_string(new_month)); } else if (new_day > 31 || new_day < 1){ throw invalid_argument("Day value is invalid: " + to_string(new_day)); } year = new_year; month = new_month; day = new_day; } int GetYear() const{ return year; }; int GetMonth() const{ return month; }; int GetDay() const{ return day; }; private: int year; int month; int day; }; bool operator<(const Date& lhs, const Date& rhs){ if(lhs.GetYear() != rhs.GetYear()){ return (lhs.GetYear() - rhs.GetYear()) < 0; } else if(lhs.GetMonth() != rhs.GetMonth()){ return (lhs.GetMonth() - rhs.GetMonth()) < 0; } else { return (lhs.GetDay() - rhs.GetDay()) < 0; } }; bool operator>(const Date& lhs, const Date& rhs){ if(lhs.GetYear() != rhs.GetYear()){ return (lhs.GetYear() - rhs.GetYear()) > 0; } else if(lhs.GetMonth() != rhs.GetMonth()){ return (lhs.GetMonth() - rhs.GetMonth()) > 0; } else { return (lhs.GetDay() - rhs.GetDay()) > 0; } }; bool operator==(const Date& lhs, const Date& rhs){ if(lhs.GetYear() == rhs.GetYear() && lhs.GetMonth() == rhs.GetMonth() && lhs.GetDay() == rhs.GetDay()){ return true; } return false; }; ostream& operator<<(ostream& stream, const Date& date){ stream << date.GetYear() << '-' << date.GetMonth() << '-' << date.GetDay(); return stream; } istream& operator>>(istream& stream, Date& d) { //возвращать будем ссылку на поток //if (stream) return stream; int year,month,day; char c; stream >> year >> c >> month >> c >> day; if (stream && c == '-') d = Date(year,month,day); return (stream); }
But unfortunately, Date date = arguments[1]; doesn't work. Correct, because arguments[1] is a std::string, but Date does not have a constructor that accepts a std::string. So add one, eg: class Date { public: Date() { setDate(0, 1, 1); }; Date(int new_year, int new_month, int new_day) { setDate(new_year, new_month, new_day); } Date(const string &str) { int new_year, new_month, new_day; // parse str to extract new_year, new_month, new_day as needed... setDate(new_year, new_month, new_day); } void setDate(int new_year, int new_month, int new_day) { if(new_month > 12 || new_month < 1){ throw invalid_argument("Month value is invalid: " + to_string(new_month)); } else if (new_day > 31 || new_day < 1){ throw invalid_argument("Day value is invalid: " + to_string(new_day)); } year = new_year; month = new_month; day = new_day; } ... }; There are many ways to parse a string to extract sub values. For instance, you can use: string::find() + string::substr() + std::stoi() std::istringstream + operator>> std::sscanf() std::regex etc Use whatever you are most comfortable with. Just for demonstration purposes, let's use std::sscanf(): #include <cstdio> class Date { public: ... Date(const string &str) { int new_year, new_month, new_day; if ((sscanf(str.c_str(), "%4d-%2d-%2d", &new_year, &new_month, &new_day) != 3) && (sscanf(str.c_str(), "%4d/%2d/%2d", &new_year, &new_month, &new_day) != 3)) { throw invalid_argument("Str value is invalid: " + str); } setDate(new_year, new_month, new_day); } ... }; On a side note, you might consider using command-line arguments instead of input I/O, eg: int main(int argc, const char* argv[]) { ... vector<string> arguments; for (int i = 1; i < argc; ++i) { arguments.push_back(argv[i]); } ... } And then users can call your program like this: program.exe command date event Instead of running program.exe first and then entering command, date, and event separately.
72,998,231
73,000,113
How are object properties accessed internally?
In reference to this question: How are variable names stored in memory in C? It is explained that in C, the compiler replaces variable names from code with actual memory addresses. Let's take C++. I wonder how object properties are accessed in that context? obj.prop So obj gets replaced by the actual memory address. Does the compiler then replace prop with some sort of offset and add it to obj - ultimately replacing the whole expression with an absolute address?
For simple cases and hiding the language lawyer hat: obj.prop is *(&obj + &Obj::prop). The the second part is a member pointer, which is basically the offset of the property inside the object. The compiler can replace that with an absolute address if it knows the address of the obj at compile time. Assuming it has an obj in memory at all. The obj could be kept completely in registers. Or only parts of the obj may exist at all. But generally obj.prop would turn into pointer + offset. Note: for local variable the pointer could be the stack frame and the offset the offset of obj inside the stack frame + the offset of prop inside Obj.
72,998,527
72,998,784
Resolving circular dependency between concept and constrained template function
I am trying to learn more about concepts. I ran into some problems with circular dependencies between concepts and constrained template functions, and I've reproduced these errors in a simple example. I have a concept, Printable, that I want to be satisfied if and only if operator<< is defined on a type. I also have an overload of operator<< on vectors of printable types. To my surprise, std::vector<int> is not considered Printable, even though operator<< works on it. #include <iostream> #include <vector> template <class T> concept Printable = requires(std::ostream& out, T a) { out << a; }; template <Printable T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& vec) { out << '['; for (std::size_t i {}; i < vec.size(); i++) { out << vec[i]; if (i < vec.size() - 1) { out << ", "; } } return out << ']'; } static_assert(Printable<int>); // This works as expected. static_assert(Printable<std::vector<int>>); // This fails. int main() { std::vector<int> vec {1, 2, 3, 4}; std::cout << vec << '\n'; // This works as expected. } This fails on Clang++ 14.0.6_1 with the following message: stack_overflow/problem.cpp:26:1: error: static_assert failed static_assert(Printable<std::vector<int>>); // This fails. ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ stack_overflow/problem.cpp:26:15: note: because 'std::vector<int>' does not satisfy 'Printable' static_assert(Printable<std::vector<int>>); // This fails. ^ stack_overflow/problem.cpp:7:9: note: because 'out << a' would be invalid: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup out << a; ^ 1 error generated. So my question is: what can I do to make std::vector<T> considered Printable if T is Printable? Notes: I believe this compiles fine as is with g++, but I recently screwed up my setup for GCC so I cannot confirm this at the moment. If this is true, I would love to know why it works for g++ but not clang++. Update: Barry's comment reminded me that Compiler Explorer exists. I can now confirm that the above code compiles on g++ but not on clang++. I still am curious about why this difference exists. I believe I need to put the operator overload above the declaration of Printable. If I do this and remove the constraint, the code compiles fine. However, I want to keep the Printable constraint if possible, as I believe keeping constraints like this will simplify error messages in the future.
To my surprise, std::vector<int> is not considered Printable, even though operator<< works on it. It doesn't. Not really anyway. When you say std::cout << x; works what you really mean is that you can write that expression from wherever and that works - "from wherever" including in the definition of Printable. And in the definition of Printable, it... doesn't work. Unqualified lookup doesn't find it and argument-dependent lookup doesn't find it either. The same will likely be true in most other contexts, unless you carefully add a using operator<<; in the appropriate place(s). You could attempt to move the declaration of operator<< forward, so that the concept definition can see it - but that still wouldn't ultimately resolve the issue of any other code actually being able to call that operator. It can't really work unless this operator is declared in namespace std. And you're not allowed to add it in there. But if you could, then this would work fine: namespace std { template <class T> concept Printable = requires (ostream os, T const var) { os << var; } template <Printable T> ostream& operator<<(ostream&, vector<T> const&) { ... } } Or just use {fmt}
72,998,544
72,998,609
What is the difference between alignof(i) and alignof(decltype(i))?
#include <iostream> alignas(16) int i; int main() { std::cout << alignof(i) << std::endl; // output: 16 and warning std::cout << alignof(decltype(i)) << std::endl; // output: 4 } What does alignof(i) and alignof(decltype(i)) do? I would have expected alignof(i) not to compile and alignof(decltype(i)) to return 16.
alignof(i) is the alignment of the i variable, which is explicitly being set to 16, regardless of its type. alignof(decltype(i)), aka alignof(int), is the natural alignment (sizeof(int), ie 4 in this case) for all int variables that are not otherwise aligned.
72,999,271
72,999,497
CEF - how to call callback c++ form JS-code
How can I call a C++ function using JavaScript? For example, I am executing js code in a browser window using the method CefFrame::ExecuteJavaScript like this: (*frame).GetMainFrame()).ExecuteJavaScript("const elem = document.getElementsByClassName("my_class")[0];const rect = elem.getBoundingClientRect(); alert(rect.x + \":\" + rect.y)", "", 1); Is it possible to somehow call a C++ function for the place of the JS alert() function?
It can be done in two ways. They are almost equal: you can create several native functions at once with CefRegisterExtension, and you can create a single native function with CefV8Value::CreateFunction. The example bellow is just a sketch, nowhere can test it, small issues are possible, but the idea is clear: class MyAlertHandler : public CefV8Handler { public: bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) override { if (!arguments.empty()) { // arguments[0]->GetStringValue(); } return true; } }; CefRefPtr<CefV8Handler> handler = new MyAlertHandler; CefRefPtr<CefV8Context> v8_context = frame->GetMainFrame()->GetV8Context(); if (v8_context.get() && v8_context->Enter()) { CefRefPtr<CefV8Value> global = v8_context->GetGlobal(); CefRefPtr<CefV8Value> my_alert = CefV8Value::CreateFunction("my_alert", handler); global->SetValue("my_alert", my_alert, V8_PROPERTY_ATTRIBUTE_READONLY); v8_context->Exit(); } Calling Enter() and Exit() on a V8 context can be omitted if CefV8Value::CreateFunction is called from CefRenderProcessHandler functions. frame->GetMainFrame()->ExecuteJavaScript(R"( const elem = document.getElementsByClassName("my_class")[0]; const rect = elem.getBoundingClientRect(); my_alert(rect.x + ":" + rect.y);)", "", 1);
72,999,708
72,999,808
Passing a vector pointer and looping it to change its value
I'm trying to pass a vector to a function, loop over it, and modify the values before sending it back, but I'm having a very hard time with the pointer and reference to make it work: I understand that itr is a pointer. I'm confused about resource on the for loop. I believe it to be a reference, but I keep getting the error: error: no viable overloaded '='resource = resource + value ACTION test::addto(name player){ auto itr = player.require_find(wallet.value, USER_NOT_FOUND(wallet)); asset value1 = asset(100, ACTION_SYMBOL); asset value2 = asset(100, FOOD_SYMBOL); changeResourceValue(itr->resources, value1); changeResourceValue(itr->resources, value2); player.modify(itr, _self, [&](auto& p) { p.resources = resources; }); } void changeResourceValue(const vector<asset>* resources, asset value){ for (auto &resource : *resources){ if(resource.symbol == value.symbol){ resource = resource + value; } } }
For starters the first parameter of the function changeResourceValue is declared with the qualifier const void changeResourceValue(const vector<asset>* resources, asset value){ It means that you may not change elements of the vector pointed to by the pointer resources. So you need at least to remove the qualifier const. The second problem is that the operator = is not defined for objects of the type asset. Maybe the error message is a consequence that the variable resource is a constant reference. Also you need to check whether the member function require_find returns a pointer or an iterator in this record auto itr = player.require_find(wallet.value, USER_NOT_FOUND(wallet)); Old C++ versions of std::vector defined iterators as pointers. But in new versions of std::vector iterators are not pointers. So maybe the function should be declared like void changeResourceValue( std::vector<asset>::iterator resources, asset value);
72,999,850
72,999,926
C++ Is it safe to change an exported DLL function from int to BOOL?
I'm dealing with a legacy DLL that has may things that started from DOS C code back in the day where there was no concept of a boolean. But the DLL is still in active development and still evolving. Many of the older exported methods have signatures like: _declspec(dllexport) int IsConditionTrue(); By the appearance of the name, the function should return a TRUE/FALSE value, but since it's delcared as an int, the programmer has to assume the API could return anything. I'm in a round of making changes to the DLL, and am wondering if it's safe to change these declarations to use BOOL instead to clarify the intended API usage: _declspec(dllexport) BOOL IsConditionTrue(); BOOL is declared as typedef int BOOL;, so I would think that there should be no difference to the compiler or to already-compiled consumers of exported function, right? I just don't want to make the change to a dozen exported functions, then spend a week chasing down and recompiling broken executables that were consuming the exported int version.
BOOL is declared as typedef int BOOL;, so I would think that there should be no difference to the compiler or to already-compiled consumers of exported function, right? Yes, typedef is just syntactic sugar and has no impact on the resulting ABI. That said, BOOL does not make the code any safer for the end user, it can still return values other than TRUE, FALSE and compiler will happily accept such code. Furthermore, the user might become more "lazy" and not check these errors compared to ominous int which hopefully makes one actually check the documentation.
73,000,107
73,000,189
What does the XXXXXX in an sprintf format argument of "/tmp/%s-XXXXXX" mean?
In the following code, it seems XXXXXX asks to generate random characters to replace it. What does XXXXXX mean here? Is this some special reserved symbol in sprintf? sprintf(tempName, "/tmp/%s-XXXXXX", filename.c_str());
More context would help, but judging from the array name tempName, this sprintf call is probably composing a template for use with mktemp(), mkstemp(), mkdtemp() or a similar function. The Xs do not have any particular meaning for sprintf, but are interpreted by the next function called with tempName. These POSIX functions are declared in <unistd.h>: SYNOPSIS #include <unistd.h> char *mktemp(char *template); int mkstemp(char *template); char *mkdtemp(char *template); DESCRIPTION The mktemp() function takes the given file name template and overwrites a portion of it to create a file name. This file name is guaranteed not to exist at the time of function invocation and is suitable for use by the application. The template may be any file name with some number of Xs appended to it, for example /tmp/temp.XXXXXX. The trailing Xs are replaced with a unique alphanumeric combination. The number of unique file names mktemp() can return depends on the number of Xs provided; six Xs will result in mktemp() selecting one of 56800235584 (626) possible temporary file names. The mkstemp() function makes the same replacement to the template and creates the template file, mode 0600, returning a file descriptor opened for reading and writing. This avoids the race between testing for a file's existence and opening it for use. The mkdtemp() function makes the same replacement to the template as in mktemp() and creates the template directory, mode 0700. Note that unless tempName was allocated with enough space for filename.c_str() plus 12 characters and a null terminator, using snprintf() is highly recommended to avoid undefined behavior, and limit the number of characters from filename.c_str() to make sure all Xs are present at the end: char tempname[32]; snprintf(tempName, sizeof tempName, "/tmp/%.19s-XXXXXX", filename.c_str());
73,000,611
73,000,633
Shared variables in two threads
I'm writing a ros node with two threads to support client dynamic reconfiguration in C++. One thread is responsible for subscribing to a topic /error which is float, taking the sum of value sum_of_error, and incrementing batch_size. Another thread is responsible for taking the average of the value if batch_size reaches BATCH and then resetting sum_of_error and batch_size to 0. Both batch_size and sum_of_error are shared variables between two threads so I use mutex to prevent data race. The thread for subscription of a topic works well but the thread for taking the average and resetting batch_size and sum_of_error is stuck. I notice that the process gets stuck at while loop in the function get_value(). I think it has something to do with race conditions. Any idea? How can I change my code to solve this problem. #include <ros/ros.h> #include <string> #include <vector> #include <std_msgs/Float32.h> #include <dynamic_reconfigure/client.h> #include <calibration/HcNodeConfig.h> #include <mutex> #include <thread> using namespace std; mutex m; int batch_size = 0; float sum_of_error = 0; int BATCH = 10; float get_value() { while (batch_size < BATCH) { } float res = sum_of_error / batch_size; m.lock(); sum_of_error = 0.0; batch_size = 0; m.unlock(); return res; } void adjuster_callback(const hc::HcNodeConfig& data) { } void listener_callback(const std_msgs::Float32ConstPtr& msg) { float current_error = msg->data; m.lock(); batch_size++; sum_of_error += current_error; m.unlock(); } void start_listener(ros::NodeHandle n) { ros::Subscriber listener; ros::Rate loop_rate(BATCH); listener = n.subscribe("/error", BATCH, listener_callback); while (ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } } void start_adjuster(ros::NodeHandle n) { ros::Rate loop_rate(BATCH); hc::HcNodeConfig config; dynamic_reconfigure::Client<hc::HcNodeConfig> client("/lidar_front_left_hc", adjuster_callback); ros::Duration d(2); client.getDefaultConfiguration(config, d); while (ros::ok()) { float current_error = get_value(); if (current_error > 0.0) { config.angle = 0.0; client.setConfiguration(config); } ros::spinOnce(); loop_rate.sleep(); } } int main(int argc, char ** argv) { ros::init(argc, argv, "adjuster"); ros::NodeHandle n; thread t1(start_listener, n); thread t2(start_adjuster, n); t1.join(); t2.join(); return 0; }
while (batch_size < BATCH) { } The apparent intent of this is to wait until another execution thread increments batch_size until it reaches BATCH. However because this access to batch_size is not synchronized, at all, this results in undefined behavior. Other execution threads synchronize modifications to batch_size using the mutex. This execution thread must do the same. Something like this: int get_batch_size() { m.lock(); int s=batch_size; m.unlock(); return s; } // ... while (get_batch_size() < BATCH) ; This is, of course, busy-polling and would be horribly inefficient. A condition variable should be employed, together with this mutex, for optimal performance and results.
73,000,648
73,044,227
read multiple root tree file one by one
I am a beginner, This is related to assignment work. For one root tree file (here pp1.root), I can use the below code. If I am having 10 root files and I need to read each file one by one to get the statistical parameters. void pbtrue() { TFile *f = new TFile("pp1.root"); TTree *T1 = (TTree*)f->Get("T1"); int Tcharged ; int Neg_charged ; int Posi_charged ; int delta_charge; T1->SetBranchAddress("Totalcharge",&Tcharged); T1->SetBranchAddress("negativecharge",&Neg_charged); T1->SetBranchAddress("positivecharge",&Posi_charged); T1->SetBranchAddress("deltacharge",&delta_charge); int nentries = T1->GetEntries(); cout<< "Entries : "<<nentries<<endl; double sumT=0.0; double sumN=0.0; double sumP=0.0; double sumD=0.0; double meanT=0.0; double meanN=0.0; double meanP=0.0; double meanD=0.0; for (int i=0;i<nentries;i++) { T1->GetEntry(i); sumT += Tcharged; sumN += Neg_charged; sumP += Posi_charged; sumD += delta_charge; meanT=sumT/nentries; meanN=sumN/nentries; meanP=sumP/nentries; meanD=sumD/nentries; } cout << "mean of Total charge : "<<meanT<<endl; cout << "mean of Negative charge : "<<meanN<<endl; cout << "mean of positive charge : "<<meanP<<endl; cout << "mean of delta charge : "<<meanD<<endl; The way I have to do the calculation is by reading each root file one by one. Every root file contains the same branches and same variables. Please help me to do this.
Now I can do this using std::string and std::to_string to form filename and use its c_str method to get pointer to underlying character array (C-style string) to pass it to TFile constructor if it doesn't accept std::string: // ... for (int i = 1; i <= 100; ++i) { string filename = "pp"+to_string(i)+".root"; TFile *f = new TFile(filename.c_str()); // ... } // ... so it will read pp1.root, pp2.root, ..., pp100.root and process them in order.
73,000,778
73,000,861
Get object type without template parameters
I need to be able to have any object that takes a single bool as a template parameter, and obtain the type of that object without the bool, so I can then create a similarly typed object but of a different bool. This is what I came up with, but it does not compile. How can I achieve this aim please? template<template<bool> typename ClassName, bool TheBool> struct FT { using TYPE = ClassName; }; template<bool X> struct T {}; int main() { T<true> t; // Somehow get the type T (without the true) so I can then create a T<false> if I want... using RawType = FT<decltype(t)>::TYPE; RawType<false> f; } (I have searched beforehand but came up blanks, hence this question.)
A little ugly, but this works: template<bool NewBool, template<bool> typename ClassName, bool TheBool> ClassName<NewBool> FT(const ClassName<TheBool>&); template<bool X> struct T {}; int main() { T<true> t; decltype(FT<false>(t)) f; } Online Demo
73,001,485
73,003,513
C++ compiler reordering read and write across thread start
I have a piece of multithreaded that I'm not sure is not liable to a data race because of compiler reordering. Here is a minimal example: int main() { int x = 0; x = 5; auto t = std::thread([&x]() { ++x; }); t.join(); return 0; } Is the assignment of x = 5 guaranteed to be before the thread start?
Short answer: The code will work as expected. No reordering will take place Long answer: Compile time reordering Let's consider what's going on. You put a variable in automatic storage (x) You create an object that holds a reference to this variable (the lambda) You pass that object to an external function (the thread constructor) The compiler does escape analysis during optimization. Due to this sequence of events, the variable x has escaped once point 3 is reached. Which means from the compiler's point of view, any external function (except those marked as pure) may read or modify the variable. Therefore its value has to be stored to the stack before each function call and has to be loaded from stack after the function. You did not make x an atomic variable. So the compiler is free to ignore any potential multithreading effects. Therefore the value may not be reloaded multiple times from memory in between calls to external functions. It may still be reloaded if the compiler decides to not keep the value in a register in between uses. Let's annotate and expand your source code to show it: int main() { int x = 0; x = 5; // stores on stack for use by external function in next line auto t = std::thread([&x]() mutable { ++x; }); int x1 = x; // loads x from stack after thread constructor may (in theory) have modified it int x2 = x; // probably no reload because not an atomic variable x = 7; // new value stored on stack because join() could access it (in theory) t.join(); int x3 = x; // reload from stack because join() could have changed it return 0; } Again, this has nothing to do with multithreading. Escape analysis and external function calls are sufficient. Any access from main() between thread creation and joining would also be undefined behavior because it would be a data-race on a non-atomic variable. But that's just a side-note. This takes care of the compiler behavior. But what about the CPU? May it reorder instructions? Run time reordering For this, we can look at the C++ standard Section 32.4.2.2 [thread.thread.constr] clause 7: Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f. The constructor means the thread constructor. f is the thread function, meaning the lambda in your case. So this means that any memory effects are synchronized properly. The join() call also synchronizes. Therefore access to x after the join can not suffer from runtime-reordering. The completion of the thread represented by *this synchronizes with (6.9.2) the corresponding successful join() return. Side note Unlike suggested in some comments, the compiler will not optimize the thread creation away for two reasons: 1. No compiler is sufficiently magical to figure this out. 2. The thread creation may fail, which is defined behavior. Therefore it has to be included in the runtime.
73,001,544
73,001,675
How do I get a value from a class table in C++
Basically, I have a class in C++ class Commands { public: void help(); void userid(); void getCmd(std::string cmd) { } }; void Commands::help() { WriteLine("\n \ --------------------------------\n \ [ userid, id ]: Get's the UserID of your player\n \ [ placeid, game ]: Get's the game ID\n \ --------------------------------\n \ \ "); } void Commands::userid() { WriteLine("Your UserId is: 12345678"); } I have a while(true) loop that runs a function which checks what the user responds with [ like a command based console ] I was wondering how I could do this: Commands cmds; cmds["help"](); cmds["examplecmdhere"](); When I try to do it I get an error Severity Code Description Project File Line Suppression State Error (active) E0349 no operator "[]" matches these operands Command
Use std::map or std::unordered_map to map std::strings to std::function that represent the functions to be called, then overload operator[] to provide easy access to the map without exposing the map. #include <string> #include <map> #include <functional> #include <iostream> class Commands { // added: a map of strings to the function to call. private to keep // unwanted hands off std::map<std::string, std::function<void()>> cmds = { { "help", // Name of command [this](){ help(); } //Lambda expression that captures instance pointer // and uses it to invoke help function } }; public: void help(); void userid(); void getCmd(std::string cmd) { } // added: overload the [] operator to give access to the map defined earlier auto & operator[](const std::string & cmd) { return cmds[cmd]; } private: }; void Commands::help() { // I have no WriteLine function, so I'm subbing in `std::cout for // demonstration purposes std::cout << "\n \ --------------------------------\n \ [ userid, id ]: Get's the UserID of your player\n \ [ placeid, game ]: Get's the game ID\n \ --------------------------------\n \ \ "; } int main() { Commands commands; commands["help"](); //use operator[] to call help function } Result: -------------------------------- [ userid, id ]: Get's the UserID of your player [ placeid, game ]: Get's the game ID -------------------------------- See it in action: https://godbolt.org/z/Kh39jqq3T
73,001,623
73,001,671
Storing parameters as key value pairs in a text file and should be able to perform operations on the values
I'm trying to write a code in C++ which basically stores key value pairs in a file separated by a space. The condition is that if the key is already present, it should just update the value(increment by 1) and write that updated value to the text file. And if the key is not already present, it should write the entire key value pair to the text file(For eg: some_param 12). Also if there are many parameters as the example I've stated, it should take just the values of all the parameters and increment all of those values by 1. I am able to write the initial key value pair to the text file but after that I am not able to parse the file just for taking out the value to increment by 1. This is the code I have: fstream fn,fn1; key = "number_of_flights"; value = 1; fstream tempfile; fn.open("samplefile.txt"); if(fn){ cout << "File Exists" << endl; fn1.open("samplefile.txt", ios::in); if(fn1.is_open()){ cout << "File is open...." << endl; while(getline(fn1, line)){ line = "Hello"; pos = line.find(" "); cout << pos << endl; str = line.substr(pos+1); value = stoi(str); cout << str << endl; line[pos+1] = value+1; fn1 << line << endl; } fn1.close(); } } else{ cout << "File doesn't exist, creating file......." << endl; fn.open("samplefile.txt", ios::out); if(fn.is_open()){ cout << "File created and opened, writing to File........"; fn << key << " " << value << endl; fn.close(); } else{ cout << "Cannot open file"; } } Can someone please help as I'm trying to figure this out from a really long time. Thanks in advance.
So the code is a bit confused with some debugging stuff mixed in. But if you look at what you've written you are missing a couple of pieces. You convert the string to an integer value = stoi(str); so you can increment it. But you never convert the integer back to a string, instead you do this line[pos+1] = value+1; which makes no sense at all. Secondly although you extract the value from the string pos = line.find(" "); str = line.substr(pos+1); you never extract the key. When you put the key and the incremented value back together you are going to need the key. Here's a code fragment that does all these things pos = line.find(" "); // find a space key = line.substr(0, pos); // extract the key value_str = line.substr(pos+1); // extract the value value = stoi(value_str); // convert the value ++value; // increment the value value_str = std::to_string(value); // value back to a string again line = key + " " + value; // combine the key and incremented value fn1 << line << endl; // write to file This code is a bit long winded, I've broken it down so you can see all the steps. In reality you could combine some of the steps and get rid of some of the variables. One simple improvement is to convert the value back to a string by writing it out to the file, replace the last three lines above with fn1 << key << ' ' << value << endl; // write key and new value Your code has one other problem. You are trying to open the "samplefile.txt" file for reading and writing simultaneously, that cannot work. Instead just choose a different file name for the output file, and then rename the file at the end. Something like this (notice I use ifstream for input files and ofstream for output files). ifstream fin("samplefile.txt"); if (fin) // does the file exist { ofstream fout("samplefile.tmp"); // temporary filename ... fin.close(); // must close the files before trying fout.close(); // to delete and rename remove("samplefile.txt"); // delete the original file rename("samplefile.tmp", "samplefile.txt"); // rename the temporary file } else { ofstream fout("samplefile.txt"); ... }
73,001,864
73,002,048
How to write string stream to ofstream?
I am trying to write a stringstream into a file but it not working. int main() { std::stringstream stream; stream << "Hello world"; cout << stream.rdbuf()<<endl;//prints fine std::ofstream p{ "hi.txt" }; p << stream.rdbuf();//nothing is writtten p.close(); std::ifstream ip{ "hi.txt" }; std::string s; ip >> s; cout << s;//nothing printed p.close(); return 0; } This answer here follows the same process. But it's not working in my case.
Internally, the stringstream maintain a read pointer/offset into its data buffer. When you read something from the stream, it reads from the current offset and then increments it. So, cout << stream.rdbuf() reads the entire stream's data, leaving the read pointer/offset at the end of the stream. Thus, there is nothing left for p << stream.rdbuf() to read afterwards. In order to do that, you have to seek the read pointer/offset back to the beginning of the steam, eg: cout << stream.rdbuf() << endl; stream.clear(); // resets the error state, particularly eofbit stream.seekg(0); p << stream.rdbuf();
73,001,893
73,001,921
How to sort object's array with function pointer and template?
Here is my test code: template<typename T> void sort(Result* n_obj, int n, bool (*cmp)(T d,T f)){ for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if((*cmp)(d,f)){ swap(n_obj[i],n_obj[j]); } } } } Here is my problem - I get this output: In function 'void sort(Result*, int, bool (*)(T, T))': [Error] 'f' was not declared in this scope why 'f' was not declared? Note: don't care about 'swap' function
You can not use the generic function arguments of the function pointer as arguments. That makes no sense. You need to specify them: template<typename T> void sort(Result* n_obj, int n, bool (*cmp)(T,T), T d, T f){ for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if(cmp(d,f)){ std::swap(n_obj[i],n_obj[j]); } } } } You probably want to do this: template<typename T> void sort(Result* n_obj, int n, bool (*cmp)(T,T)){ for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if(cmp(n_obj[i], n_obj[j])){ std::swap(n_obj[i],n_obj[j]); } } } } With that being said, think about using std::function and std::array or std::vector instead of C-style syntax, if you want to work with C++. There's not really an argument to mix the two distinct languages.
73,002,024
73,002,055
Hotel Bookings Possible C++
Hotel Bookings Possible C++ from InterviewBit website. I've been working on it and I couldnt find a solution for it. The question is: A hotel manager has to process N advance bookings of rooms for the next season. His hotel has C rooms. Bookings contain an arrival date and a departure date. He wants to find out whether there are enough rooms in the hotel to satisfy the demand. Write a program that solves this problem in time O(N log N) . Input Format First argument is an integer array A containing arrival time of booking. Second argument is an integer array B containing departure time of booking. Third argument is an integer C denoting the count of rooms. Output Format Return True if there are enough rooms for N bookings else return False. Return 0/1 for C programs. Code: bool Solution::hotel(vector<int> &arrive, vector<int> &depart, int K) { vector<pair<int,int> >v; int n=arrive.size(); for(int i=0;i<n;i++){ v.push_back(make_pair(arrive[i],1)); v.push_back(make_pair(depart[i],-1)); } sort(v.begin(),v.end()); int count=0; for(int i=0;i<2*n;i++){ count+=v[i].second; if(count>K) return false; } return true; } and Im getting error for just this test case Your submission failed for the following input A : [ 1, 2, 3 ] B : [ 2, 3, 4 ] C : 1 The expected return value: 0 Your function returned the following: 1 Someone help!
You're processing departures before arrivals. In the sample test case, someone stays from days 1~2. That means, the room is occupied on day 2; and is only vacated on day 3. For some departure date x, you should process it on x+1 as that's when the guest leaves. So, you can simply update this loop: for(int i=0;i<n;i++){ v.push_back(make_pair(arrive[i],1)); v.push_back(make_pair(depart[i],-1)); } to: for(int i=0;i<n;i++){ v.push_back(make_pair(arrive[i],1)); v.push_back(make_pair(depart[i]+1,-1)); }
73,002,349
73,009,133
add_subdirectory not working with custom source macro
I'm pretty new to CMake, and have just gotten into setting it up. I've gone ahead and implemented a simple opengl boilerplate, whose tree is like this CMakeLists.txt include glad KHR src glad glad.c CMakeLists.txt main.cpp CMakeLists.txt lib .gitignore .gitmodules CMakePresets.json README.md My Root CMakeLists is this: cmake_minimum_required (VERSION 3.8) project ("GameBro") set(APP_NAME "GameBro") # Opengl stuff find_package( OpenGL REQUIRED ) # GLFW stuff set(BUILD_SHARED_LIBS OFF CACHE BOOL "") set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "") set(GLFW_BUILD_TESTS OFF CACHE BOOL "") set(GLFW_BUILD_DOCS OFF CACHE BOOL "") set(GLFW_INSTALL OFF CACHE BOOL "") # MSVC related stuff if( MSVC ) SET( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /ENTRY:mainCRTStartup" ) endif() # Macro to add sources from subdirs macro (add_sources) file (RELATIVE_PATH _relPath "${PROJECT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}") foreach (_src ${ARGN}) if (_relPath) list (APPEND sources "${_relPath}/${_src}") else() list (APPEND sources "${_src}") endif() endforeach() if (_relPath) # propagate SRCS to parent directory set (sources ${sources} PARENT_SCOPE) endif() endmacro() # Library subdir add_subdirectory( lib ) # Add sources add_subdirectory( src ) # Add executable include_directories( ${OPENGL_INCLUDE_DIRS} lib/glfw/include lib/glfw/deps include ) add_executable ( ${APP_NAME} ${sources} ) target_link_libraries (${APP_NAME} glfw ${GLFW_LIBRARIES}) My src CMakeLists is like this add_sources( main.cpp ) #add_sources( glad/glad.c ) add_subdirectory (glad) My src/glad CMakeLists is like this add_sources( glad.c ) The problem is, when i try to compile - i get errors like undefined reference to glad_glCreateShader etc.... But, when i put glad.c in the same dir as main.cpp and modify CMakeLists accordingly, it works properly and compiles, and displays a rectangle. WHat am I doing wrong here?
So, I seem to have finally fixed my problem. Here's how I did it. SO, as @fabian pointed out, PARENT_SCOPE only refers to the immediately above scope. NOT the top-level scope. To fix this what I did was to add set (sources ${sources} PARENT_SCOPE) to each and every CMakeLists.txt file. Although this is a hacky workaround - it solves my purpose.
73,002,840
73,003,266
Internal storage requirements of C++ UnorderedAssociativeContainer
I've been reading about C++ containers and iterators. For my question, I think the following observations are relevant: UnorderedAssociativeContainer is a Container. value_type is std::pair<const Key, T>. iterator is LegacyForwardIterator and dereferencing it returns container's value_type. Does this imply that any UnorderedAssociativeContainer must internally store items as value_type? My curiosity stems from a considering the memory footprint of containers. If I have std::unordered_map<int32_t, int64_t>, then on 64-bit systems std::pair<int32_t, int64_t> will have 32 unused bits due to alignment. I think we should be able to store things more compactly, but I don't see how to satisfy the requirements if the storage is organized in any other way than value_type. How could iterator return a reference to value_type if the internal storage were organized differently?
Technically, no. The implementation of the standard library is not constrained by the language standard (in fact, it is impossible to implement the full standard library without relying on compiler extensions). An implementation could rely on some exceedingly unusual processor functionality to tightly pack the elements while still exposing them (including their user-visible memory layout) as pairs. With that said, all standard library implementations I’m aware of do use pair for storage.
73,003,115
73,005,013
Is storing initializer_lists undefined behaviour?
This question is a follow up to How come std::initializer_list is allowed to not specify size AND be stack allocated at the same time? The short answer was that calling a function with brace-enclosed list foo({2, 3, 4, 5, 6}); conceptually creates a temporary array in the stackspace before the call and then passes the initializer list which (like string_view) just references this local temporary array (probably in registers): int __tmp_arr[5] {2, 3, 4, 5, 6}; foo(std::initializer_list{arr, arr + 5}); Now consider the following case where I have nested initializer_lists of an object "ref". This ref object stores primitives types or an initializer_list recursively in a variant. My question now is: Is this undefined behaviour? It appears to work with my code, but does it hold up to the standard? My reason for doubting is that when the inner constructor calls for the nested brace-enclosed lists return, the temporary array which the initializer list is refering to could be invalidated because the stack pointer is reset (thus saving the initializer_list in the variant preserves an invalid object). Writing to subsequent memory would then overwrite values refered to by the initializer list. Am I wrong in believing that? CompilerExplorer #include <variant> #include <string_view> #include <type_traits> #include <cstdio> using val = std::variant<std::monostate, int, bool, std::string_view, std::initializer_list<struct ref>>; struct ref { ref(bool); ref(int); ref(const char*); ref(std::initializer_list<ref>); val value_; }; struct container { container(std::initializer_list<ref> init) { printf("---------------------\n"); print_list(init); } void print_list(std::initializer_list<ref> list) { for (const ref& r : list) { if (std::holds_alternative<std::monostate>(r.value_)) { printf("int\n"); } else if (std::holds_alternative<int>(r.value_)) { printf("int\n"); } else if (std::holds_alternative<bool>(r.value_)) { printf("bool\n"); } else if (std::holds_alternative<std::string_view>(r.value_)) { printf("string_view\n"); } else if (std::holds_alternative<std::initializer_list<ref>>(r.value_)) { printf("initializer_list:\n"); print_list(std::get<std::initializer_list<ref>>(r.value_)); } } } }; ref::ref(int init) : value_{init} { printf("%d stored\n", init); } ref::ref(bool init) : value_{init} { printf("%s stored\n", init ? "true" : "false"); } ref::ref(const char* init) : value_{std::string_view{init}} { printf("%s stored\n", init); } ref::ref(std::initializer_list<ref> init) : value_{init} { printf("initializer_list stored\n", init); } int main() { container some_container = { 1, true, 5, { {"itemA", 2}, {"itemB", true}}}; } Output: 1 stored true stored 5 stored itemA stored 2 stored initializer_list stored itemB stored true stored initializer_list stored initializer_list stored --------------------- int bool int initializer_list: initializer_list: string_view int initializer_list: string_view bool
First of all, copying a std::initializer_list does not copy the underlying objects. (cppreference) and container some_container = { 1, true, 5, { {"itemA", 2}, {"itemB", true}}}; actually compiles to something like container some_container = { // initializer_list<ref> ref{1}, ref{true}, rer{5}, ref{ // initializer_list<ref> ref{ // initializer_list<ref> ref{"itemA"}, ref{2} }, ref{ // initializer_list<ref> ref{"itemB"}, ref{true} } } }; and all those object's lifetime* end at end of full expression (the ; here) *including all initializer_list<ref>, their underlying array, and all the belonging ref objects, but not the one in the constructor (copy elision may apply though) so yes it's fine to use those object in the constructor. those object are gone after the ; so you should not use the stored object (in initializer_list) anymore godbolt example with noisy destructor and action after the construction
73,003,136
73,003,172
How to solve this strange bug? (c++)
#include <iostream> #include <vector> int main() { std::string human = ""; std::vector <char> translate; std::cout << "Enter English words or sentences to tranlate it into Whale's language.\n"; std::cin >> human; for (int a = 0; a < human.size(); a++){ if (human[a] == 'a' || human[a] == 'i' || human[a] == 'o' || human[a] == '.' || human[a] == ',' || human[a] == '?' || human[a] == '!' || human[a] == ' ' || human[a] == 'A' || human[a] == 'I' || human[a] == 'O' || human[a] == '-'){ translate.push_back(human[a]);} if (human[a] == 'e' || human[a] == 'u' || human[a] == 'E' || human[a] == 'U'){ translate.push_back(human[a]); translate.push_back(human[a]);}} for (int b = 0; b < translate.size(); b++){ std::cout << translate[b];} } The program above is about to translate words into other words. There are two rules for the translation: Remove all the characters, except 'a', 'i', 'o', 'e', 'u'. Just double the occurrence of 'e' and 'u'. E.g. if I type "Hello world.",it should output "eeo o." But the question is, my code does not work like that, it just output "eeo", which is odd I think. Can someone explain why?
Reading from an ifstream into a string will break on whitespaces, hence cin >> human only reads what's effectively the first word. Change this: std::cin >> human; To this: std::getline(cin, human); While we're here, let's cleanup the code: #include <iostream> #include <unordered_set> #include <string> int main() { std::string human; std::string translate; std::unordered_set<char> keepers = {'a','i', 'o', 'A','I','O'}; std::unordered_set<char> doublers = {'e', 'u', 'E', 'U'}; std::cout << "Enter English words or sentences to translate it into Whale's language.\n"; std::getline(cin, human); for (char c : human) { if (keepers.find(c) != keepers.end() || ::ispunct(c) || ::isspace(c)) { translate += c; } else if (doublers.find(c) != doublers.end()) { translate += c; translate += c; } } std::cout << translate << std::endl; }
73,003,597
73,003,698
Assigning multiple elements of array in one statement(after initialization)
std::string mstring[5]; mstring[0] = "veena"; mstring[1] = "guitar"; mstring[2] = "sitar"; mstring[3] = "sarod"; mstring[4] = "mandolin"; I want to assign the array like above. I don't want to do it at initialization but assign later. Is there a way to combine 5 statements into one.
You can do that by using std::array<std::string, 5> instead of the raw array. For example #include <iostream> #include <string> #include <array> int main() { std::array<std::string, 5> mstring; mstring = { "veena", "guitar", "sitar", "sarod", "mandolin" }; for ( const auto &s : mstring ) { std::cout << s << ' '; } std::cout << '\n'; } The program output is veena guitar sitar sarod mandolin Another approach when a raw array is used is to use std::initializer_list in range-based for loop. For example #include <iostream> #include <string> int main() { std::string mstring[5]; size_t i = 0; for ( auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } ) { mstring[i++] = s; } for ( const auto &s : mstring ) { std::cout << s << ' '; } std::cout << '\n'; } The program output is the same as shown above veena guitar sitar sarod mandolin If your compiler supports C++ 20 then instead of these statements size_t i = 0; for ( auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } ) { mstring[i++] = s; } you can use just one range-based for loop for ( size_t i = 0; auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } ) { mstring[i++] = s; }
73,004,256
73,016,588
UWP.C++ How to toggle Adaptive Brightness from BackgroudTask
now i have PointerTo.BrightnessOverride from MyBackgroudTask aaa_bo = BrightnessOverride::GetDefaultForSystem();// OK VStudio & Phone I can Set Brightness from BackgroundTask.exe, but How can i toggle Adaptive Brightness ON / OFF ? I created class NullObject, but still compile error aa_OBJ_BO->SaveForSystemAsync(NullObject()); Error C2664 'Windows::Foundation::IAsyncOperation<bool> ^Windows::Graphics::Display::BrightnessOverride::SaveForSystemAsync(Windows::Graphics::Display::BrightnessOverride ^)': cannot convert argument 1 from 'BackgroundTask::NullObject' to 'Windows::Graphics::Display::BrightnessOverride ^' BackgroundTask 554 1 Build private ref class ClsDummy { public: virtual ~ClsDummy() {}; virtual void MakeSound() {}; }; //Windows::Graphics::Display::BrightnessOverride^ private ref class NullObject sealed : public ClsDummy { public: //virtual void MakeSound() const override {}; virtual void MakeSound() override {}; };
You could take a look at BrightnessOverride.SaveForSystemAsync(BrightnessOverride) Method. The method mentioned that if a NULL object is passed in, the system turns on auto-brightness. So you might need to call this method with a null value to turn on the auto-brightness.
73,004,374
73,004,430
Writing and reading data to binary file using fstream
I need to create a binary file and store inside it 10 numbers, and after that go one by one element of file and replace it with it's opposite number. #include <iostream> #include <fstream> int main() { std::fstream file("numbers.dat", std::ios::app | std::ios::in|std::ios::out|std::ios::binary); for (double i = 1; i <= 10; i++) file.write(reinterpret_cast<char*>(&i), sizeof i); int length_of_file = file.tellg(); int number_of_elements = length_of_file / sizeof(double); for (int i = 0; i < number_of_elements; i++) { double num; file.seekg(0); // change mode to reading file.seekg(i * sizeof (double)); file.read(reinterpret_cast<char*>(&num), sizeof num); num = num * -1; file.seekp(0); // change mode to writing file.seekp(i * sizeof (double)); file.write(reinterpret_cast<char*>(&num), sizeof num); } // after change file.seekg(0, std::ios::end); // position cursor to the end length_of_file = file.tellg(); number_of_elements = length_of_file / sizeof(double); for (int i = 0; i < number_of_elements; i++) { double num; file.seekg(i * sizeof (double)); file.read(reinterpret_cast<char*>(&num), sizeof num); std::cout << num << " "; } return 0; } OUTPUT: 1 2 3 4 5 6 7 8 9 10 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 If I don't use std::ios::app and make an empty file numbers.dat before running program, I would get correct output: -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 std::ios::app according to cpp reference means seek to the end of stream before each write Is there any way to create a file with mode that would seek to the beginning of stream before each write? Is there anyway to solve this without creating an empty file before running program? Note: It is not allowed to load file elements into an array or similar container data structure.
Your mode is wrong in two ways. Firstly std::ios::app | std::ios::binary does not allow you to read from the file, and secondly it means that all writes will be at the end of the file irrespective of the current position. The -1 file position that you see means the seekg call has failed, presumably because you tried to read from a file you hadn't opened with std::ios::in. You should use std::ios::in | std::ios::out | std::ios::binary although this requires the file to exist before you open it, or you could use std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary but this will destroy any existing contents of the file. BTW the repeated seekg and seekp aren't needed. You only need to set the position one time to change modes.
73,004,754
73,005,819
How to get a string within "\n" in c++?
Suppose I'm having- string s="Hello Hi Hey\n""Bye Bye good night"; Now,I want to get the string within "\n" ,i.e I want to get "Hello Hi Hey" How can i do so? I've thinking of stringstream, but it's not possible as "Hello Hi Hey" itself contains space.
Now,I want to get the string within "\n" ,i.e I want to get "Hello Hi Hey" How can i do so? I've thinking of stringstream, but it's not possible as "Hello Hi Hey" itself contains space. Just instantiate a std::istringstream and use std::getline() to read the separate lines into strings: string hellohihey; string byebyegoodnight; std::istringstream iss(s); std::getline(iss,hellohihey); std::getline(iss,byebyegoodnight); Also note that the literal doesn't need separate double quotes: string s="Hello Hi Hey\nBye Bye good night"; Or even use a raw string literal to get some kind of WYSIWYG feeling: string s=R"(Hello Hi Hey Bye Bye good night)";
73,005,897
73,005,920
implementing a linked list and it doesn't produce output
I am implementing a linked list but it doesn't display any output. implementing a linked list with 4 elements and making fuction insert and insertathead and display. #include <bits/stdc++.h> using namespace std; // class node to make node element. class node { public: int data; node *next; node{ } // constructor node(int val) { data = val; next = NULL; } // function to insert element at head. void insertAthead(node *&head, int val) { node *n = new node(val); n->next = head; head = n; return; } // function to insert in linked list. void insert(node *head, int val) { node *temp = head; if (head == NULL) { insertAthead(head, val); return; } node *n = new node(val); while (temp->next != NULL) { temp = temp->next; } temp->next = n; } // function to display each element in a linked list. void display(node *head) { while (head->next != NULL) { cout << head->data; head = head->next; } cout << head->data; } }; //main function int main() { node *head; // line at which I think there is a problem head->insert(head, 1); head->insert(head, 2); head->insert(head, 3); head->insert(head, 4); head->display(head); return 0; } I think the problem is at line 1 node *head; when I change this line with node *head=new node(any integer value) the code runs fine.
First you want to move insert, insertAtHead and display out of the Node class. These are list functions have have no need of special access to Node. Also you should initialise head to NULL (representing the empty list). This means changing main like this node *head = NULL; insert(head, 1); insert(head, 2); insert(head, 3); insert(head, 4); display(head); Then you want to change void insert(node *head, int val) to void insert(node *&head, int val) Just like you have done (correctly) with insertAtHead. If you wanted to take this further you could create a List class, along these lines class List { public: List() { root = NULL; } void insert(int val); void insertAtHead(int val); void display(); private: Node* root; }; then main would look like this int main() { List l; l.insert(1); l.insert(2); l.insert(3); l.insert(4); l.display(); }
73,006,563
73,012,136
How to add extra data to a tree item?
I'm trying to add extra data to a wx Tree Item using wxTreeItemData, but I cannot construct a wxTreeItemData object, because the constructor doesn't have any parameters. Here is my sample code: wxTreeCtrl treeCtrl = new wxTreeCtrl(parentWindow); treeCtrl->AddRoot("Root"); treeCtrl->AppendItem(root, "item", -1,-1, "some extra data"); /** Signature help for inline ​​​wxTreeItemId​ ​‌​​AppendItem​(const ​​​wxTreeItemId​ &​​‌parent​, const ​​​wxString​ &​​‌text​, int ​​‌image​ = -1, int ​​‌selImage​ = -1, ​​​wxTreeItemData​ *​​‌data​ = (​​​wxTreeItemData​ *)0). Summary: insert a new item in as the last child of the parent. Current parameter 3 of 5: , . **/ This gives me an error: E0413. no suitable conversion function from "std::string" to "wxTreeItemData *" exists But when I pass a wxTreeItemData object nothing happens, because the object is empty. The wxTreeItemData constructor is without any parameters! Does anyone know how to add data to a wxTreeItemData object? Another try I declared a new class that is derived from the `wxTreeItemData` class, then added a string that will hold the data, and then, I declared, and defined a method to return the data. Code sample: wxTreeItemId item = treeCtrl->AppendItem(Root, "item", -1,-1, new DataItem("some extra data")); // It should set the new DataItem object as a wxTreeItemData // I'll try to get the data object from the TreeCtrl: DataItem *data = treeCtrl->GetItemData(item); // Signature help for virtual ​​​wxTreeItemData​ * ​‌​​GetItemData​(const ​​​wxTreeItemId​ &​​‌item​) const. // Trying to print the data: std::cout << data->GetData(); // It should print the data. Error: E0144. a value of type "wxTreeItemData *" cannot be used to initialize an entity of type "DataItem *" Because the method GetItemData() returns a wxTreeItemData object. And if I tried to replace the DataItem to wxTreeItemData, I cannot invoke the GetData() method of my DataItem object. Helpful resources: [wxWidgets: wxTreeCtrl Class Reference][1] wxWidgets: wxTreeItemData Class Reference
You indeed need to derive your class from wxTreeItemData, as you've done, and you need to cast the returned value of GetItemData() to the correct value, i.e. write DataItem *data = static_cast<DataItem*>(treeCtrl->GetItemData(item)); This is safe as long as you only pass actual DataItem objects (and not something else) to SetItemData().
73,006,977
73,007,520
How to close a QDialog that uses a different ui file in Qt?
I've been trying to close a QDialog that uses a separate ui file. The dialog is used in a slot of a different class (TaskManager). Sorry for the question but I couldn't find a workaround anywhere. I'm creating a ToDo App as a University project (first year, first time using C++ and Qt): as the user clicks on the "Add Task" button in the TaskManager, the dialog is shown. The user inserts the tasks attributes in the dialog and then I take that data to create a Task object (different class) that is shown in the TaskManager (works fine if I close the dialog manually). This is a code snippet of the creation of the dialog: void TaskManager::on_pushButton_addTask_clicked() { Ui::AddTask addTaskDialog; // addTaskDialog takes the Ui of the file AddTask.ui QDialog dialog; addTaskDialog.setupUi(&dialog); dialog.exec(); // shows the dialog [More Code] } I wanted to close the QDialog when the user clicks on QDialogButtonBox: ok -> closes the dialog cancel -> closes and deletes the dialog. I have tried something like this, but it doesn't work (I get this build issue: "No matching member function for call to 'connect'): QPushButton* ok = addTaskDialog.buttonBox->button(QDialogButtonBox::Ok); connect(ok, &QPushButton::clicked, this, dialog.close()); Any help would be much appreciated!
connect(ok, &QPushButton::clicked, this, dialog.close()); - your connect is wrong, you don't pass a pointer to a member function as forth parameter but the return value of dialog.close(). Also the context is wrong -> connect(ok, &QPushButton::clicked, &dialog, QQDialog::close). btw: Your whole approach on how to create this dialog looks fishy - better create a new class derived from QDialog and do the stuff in there.
73,007,067
73,007,123
Return function pointer based on input type parameter C++
I have a class for managing function pointers. I want to use a template or something to call the function stored in the class via the [] operator. For example, I can do functions[malloc](0x123), which calls malloc via a pointer to the malloc function stored in the class. This is what I have: #include <cstdlib> #include <iostream> class DelayedFunctions { decltype(&malloc) malloc; decltype(&free) free; public: template <typename T> constexpr T operator[](T) { if (std::is_same_v<T, decltype(&malloc)>) return malloc; if (std::is_same_v<T, decltype(&free)>) return free; return 0; } }; I'm trying to get the template to expand/change the return type based on the function's arguments, but I'm not so sure how to go about getting it to work. The constructor which initializes the values of the private fields is omitted; all it does is get the addresses of the functions and then assign them to the fields. I'm trying to use C++20 to do this.
Works well with if constexpr #include <cstdlib> #include <type_traits> class DelayedFunctions { decltype(&std::malloc) malloc = std::malloc; decltype(&std::free) free = std::free; public: template <typename T> constexpr T operator[](T) { if constexpr (std::is_same_v<T, decltype(&std::malloc)>) return malloc; if constexpr (std::is_same_v<T, decltype(&std::free)>) return free; return {}; } }; DelayedFunctions functions; int main() { auto *p = functions[malloc](123); functions[free](p); }
73,007,186
73,007,259
Threads calling function in another class
I am trying to understand the multithreading in c++. I am trying to call a function in another class using two threads as shown below: vmgr.h class VMGR{ public: int helloFunction(int x); }; vmgr.cpp #include"vmgr.h" #include<iostream> int VMGR::helloFunction(int x){ std::cout<< "Hello World="<< x << std::endl; return 0; } main.cpp #include <stdlib.h> #include <iostream> #include<iostream> #include<thread> #include<chrono> #include<algorithm> #include "vmgr.h" using namespace std::chrono; int main(int argc, char* argv[]) { VMGR *vm= new VMGR(); std::thread t1(vm->helloFunction,20); std::thread t2(vm->helloFunction,30); t1.join(); t2.join(); return 0; } The error I am getting is Invalid use of non-static member function int VMGR:: helloFunction(int) Not sure how to resolve this error. Thank you in advance.
The constructor of std::thread uses std::invoke passing copies of the constructor parameters. std::invoke can, among other alternatives, be called with member function pointers. This requires syntax different to the one used in the question: std::thread t1( &VMGR::helloFunction, // member function pointer vm, // pointer to the object to call the function for 20 // function parameter ); std::thread t2(&VMGR::helloFunction, vm,30);
73,007,388
73,007,453
How can I set a c++ variable to permanently be the sum of two others?
I want to permanently set one variable to be the sum of two other integer variables in c++, such that the value of the sum variable will change as either or both of the original two variables change: #include <iostream> int main() { int myInt = 3; int myInt2 = 5; int mySum = myInt + myInt2; // Something here so that mySum changes with myInt and myInt2 std::cout << mySum << std::endl; // Should output 8 myInt = 10; std::cout << mySum << std::endl; // Should output 15 myInt2 = 30; std::cout << mySum; // Should output 40 } Is this possible to do, whether with references/pointers or some other method?
You cannot achieve this with the exact same syntax you're suggesting, but you can create a type containing 2 references to int that behaves reasonably similar to an int resulting in the desired behaviour: class Sum { public: Sum(const int& s1, const int& s2) noexcept : m_s1(s1), m_s2(s2) {} operator int() const noexcept { return m_s1 + m_s2; } private: const int& m_s1; const int& m_s2; }; std::ostream& operator<<(std::ostream& s, Sum const& sum) { s << static_cast<int>(sum); return s; } int main() { int myInt = 3; int myInt2 = 5; Sum mySum(myInt, myInt2); std::cout << mySum << std::endl; // outputs 8 myInt = 10; std::cout << mySum << std::endl; // outputs 15 myInt2 = 30; std::cout << mySum << std::endl; // outputs 40 std::cout << (mySum + 1) << std::endl; // outputs 41 }
73,007,468
73,007,577
Is a unique_ptr with custom deleter never invoked when initialized with nullptr
In scenarios where you interface with C libraries which manage the creation/deletion of pointers, I saw a recent buggy code where a struct was managed by a unique_ptr before the pointer was actually pointing to a valid memory location, so the raw ptr was nullptr before it was passed on to a C API. An example in code to simulate this: #include <memory> #include <iostream> struct Foo { std::string s; }; // A simple fn to simulate C libararies which use a outptr void init_foo(Foo** foo_ptr_ptr) { std::cout << "Initializing Foo\n"; Foo* f = new Foo; *foo_ptr_ptr = f; }; // custom resource deletion via the C API void delete_foo(Foo* foo) { std::cout << "Invoking destructor!\n"; if (foo != nullptr) { std::cout << "Deleting Foo\n"; delete foo; } } int main() { Foo * foo {nullptr}; // Ideally you should init_foo(&foo) here before creating a uniq_ptr std::unique_ptr<Foo, decltype(&delete_foo)> foo_ptr {foo, &delete_foo}; init_foo(&foo); // Buggy initialization, however delete_foo will never be invoked! return 0; } In case of a buggy initialization ie. you create the unique_ptr with ptr constructor before the ptr was actually valid, and you initialize it later what actually happens, is the destructor never invoked because it is UB to change the memory location of unique_ptr's managed raw ptr? For eg. in the above code where init_foo was called after unique_ptr was created, the destructor of the unique_ptr was never invoked. Is this because this is a Undefined behaviour? Of course calling the unique_ptr after init_foo will have the expected behaviour where the construction and the expected destructor is called.
[...] what actually happens, is the destructor never invoked because it is UB to change the memory location of unique_ptr's managed raw ptr? You never change the pointer managed by the std::unique_ptr to anything other than null and that's why the delete_foo is never invoked, not even with null as parameter. There's no undefined behaviour happending here, it's just that the code posted in the question doesn't behave the way you expect it to. std::unique_ptr contains a member variable holding the pointer and the constructor you're using in the question takes the pointer by value, i.e. it copies the current value of foo resulting in later changes of the value of foo in having no effect on foo_ptr. You could either call init_foo(&foo) before calling the constructor or provide the std::unique_ptr with ownership of the object later using std::unique_ptr::reset: Foo* foo{ nullptr }; // Ideally you should init_foo(&foo) here before creating a uniq_ptr std::unique_ptr<Foo, decltype(&delete_foo)> foo_ptr{ foo, &delete_foo }; init_foo(&foo); // Buggy initialization, however delete_foo will never be invoked! foo_ptr.reset(foo);
73,007,806
73,007,967
Why won't the pixels I try to draw into VGA memory show up?
I'm working on a little operating system, and I'm running into issues drawing pixels. It seems that no matter what I do, I am unable to get anything to appear. I'm trying to follow along with an article by OSDev Wiki, but so far all that works for me is text outputting. Here's my assembly bootloader code: [org 0x7c00] KERNEL_LOCATION equ 0x1000 mov [BOOT_DISK], dl xor ax, ax mov es, ax mov ds, ax mov bp, 0x8000 mov sp, bp mov bx, KERNEL_LOCATION mov dh, 2 mov ah, 0x02 mov al, dh mov ch, 0x00 mov dh, 0x00 mov cl, 0x02 mov dl, [BOOT_DISK] int 0x13 mov ah, 0x0 mov al, 0x3 int 0x10 ; text mode CODE_SEG equ GDT_code - GDT_start DATA_SEG equ GDT_data - GDT_start cli lgdt [GDT_descriptor] mov eax, cr0 or eax, 1 mov cr0, eax jmp CODE_SEG:start_protected_mode jmp $ BOOT_DISK: db 0 GDT_start: GDT_null: dd 0x0 dd 0x0 GDT_code: dw 0xffff dw 0x0 db 0x0 db 0b10011010 db 0b11001111 db 0x0 GDT_data: dw 0xffff dw 0x0 db 0x0 db 0b10010010 db 0b11001111 db 0x0 GDT_end: GDT_descriptor: dw GDT_end - GDT_start - 1 dd GDT_start [bits 32] start_protected_mode: mov ax, DATA_SEG mov ds, ax mov ss, ax mov es, ax mov fs, ax mov gs, ax mov ebp, 0x90000 ; 32 bit stack base pointer mov esp, ebp jmp KERNEL_LOCATION times 510-($-$$) db 0 dw 0xaa55 And here's my C++ kernel code: void draw_pixel(int pos_x, int pos_y, unsigned char colour) { unsigned char* location = (unsigned char*)0xA0000 + 320 * pos_y + pos_x; *location = colour; } void write_string( int colour, const char *string ) { volatile char *video = (volatile char*)0xB8000; while( *string != 0 ) { *video++ = *string++; *video++ = colour; } } extern "C" void main(){ for(int i = 0; i<10; i++) { draw_pixel(i,i,15); } write_string(15, "Hellop World"); return; } I'm rather new to Assembly, but I assume the issue lies in some incompatibility between my ASM code and my C++ code. For a bit more context, I'm trying to output to VGA 320x200 with 8 bit color palette.
The assembly code sets mode 0x03 (80x25 Text), you have even commented it as such. Nowhere does it appear that you are setting mode 0x13 (320x200 256 colour). Your code is writing to both the text and graphics frame buffer. Only the text framebuffer will be rendered in text mode. You cannot render both text and graphics simultaneously. To render text in a graphics mode, you will have to "draw" it. To set the VGA mode 13h: mov ah, 0x00 mov al, 0x13 int 0x10 To "draw" text to the graphics framebuffer, you will need character bitmaps. The simplest solution to that is to use the font tables used for translating ASCII codes to glyphs in text mode. That is described at https://wiki.osdev.org/VGA_Fonts Note that the BIOS call to switch mode (or indeed any BIOS call) must be done before entering protected mode. BIOS calls, or more particularly software interrupts do not work in protected mode.
73,007,915
73,008,231
Recompiling does not reflect changes
I am attempting to make a simple change to the bitcoin core codebase locally but my changes are not reflected after recompilation. Below are the steps to reproduce the issue: Clone the bitcoin source code: git clone https://github.com/bitcoin/bitcoin.git cd bitcoin Edit: src/rpc/rawtransaction.cpp and change something (anything). Here I just put "HELLO WORLD" in the signrawtransactionwithkey method as shown below and left everything else the same: static RPCHelpMan signrawtransactionwithkey() { return RPCHelpMan{"signrawtransactionwithkey", "\n HELLO WORLD Sign inputs for raw transaction (serialized, hex-encoded).\n" ... <code continues> ... Recompile: ./autogen.sh ./configure make -j 16 make command output: Making all in src make[1]: Entering directory '/home/bitcoinfacts/bitcoin/src' make[2]: Entering directory '/home/bitcoinfacts/bitcoin/src' make[3]: Entering directory '/home/bitcoinfacts/bitcoin' make[3]: Leaving directory '/home/bitcoinfacts/bitcoin' CXXLD qt/bitcoin-qt CXXLD test/fuzz/fuzz CXXLD qt/test/test_bitcoin-qt make[2]: Leaving directory '/home/bitcoinfacts/bitcoin/src' make[1]: Leaving directory '/home/bitcoinfacts/bitcoin/src' Making all in doc/man make[1]: Entering directory '/home/bitcoinfacts/bitcoin/doc/man' make[1]: Nothing to be done for 'all'. make[1]: Leaving directory '/home/bitcoinfacts/bitcoin/doc/man' make[1]: Entering directory '/home/bitcoinfacts/bitcoin' make[1]: Nothing to be done for 'all-am'. make[1]: Leaving directory '/home/bitcoinfacts/bitcoin' Run the signrawtransactionwithkey command: ./src/bitcoin-cli signrawtransactionwithkey The output does not include HELLO WORLD: error code: -1 error message: signrawtransactionwithkey "hexstring" ["privatekey",...] ( [{"txid":"hex","vout":n,"scriptPubKey":"hex","redeemScript":"hex","witnessScript":"hex","amount":amount},...] "sighashtype" ) Sign inputs for raw transaction (serialized, hex-encoded). ... <output continues> ... Why? What I am I doing wrong?
The reason was that I had to kill and restart bitcoind because that's where the change actually was (not bitcoin-cli, as I previously thought. Duh!)
73,007,919
73,008,573
imgui is not rendering with a D3D9 Hook
ok so basically I am trying to inject a DLL into a game for an external menu for debugging and my hook works completely fine, i can render a normal square fine to the screen but when i try to render imgui, some games DirectX just dies and some others nothing renders at all. The issue makes no sense because I've tried everything, i've switched libraries, tried different compile settings and just started doing random shit but still to no avail, the library i am using for hooking is minhook (was using kiero but from trying to figure out the issue switched to manually getting the D3D Device). My hooks work entirely fine as I said earlier, I can render a square to the screen without issues but I cant render imgui (and yes i checked it is the DX9 version of imgui), code: long __stdcall EndSceneHook(IDirect3DDevice9* pDevice) // Our hooked endscene { D3DRECT BarRect = { 100, 100, 200, 200 }; pDevice->Clear(1, &BarRect, D3DCLEAR_TARGET, D3DCOLOR_ARGB(255, 0, 255, 0), 0.0f, 0); if (!EndSceneInit) { ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplWin32_Init(TrackmaniaWindow); ImGui_ImplDX9_Init(pDevice); EndSceneInit = true; return OldEndScene(pDevice); } ImGui_ImplDX9_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); ImGui::ShowDemoWindow(); ImGui::EndFrame(); ImGui::Render(); ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); return OldEndScene(pDevice); // Call original ensdcene so the game can draw } And if you are considering saying i forgot to hook Reset I did but the game pretty much never calls it so I probably did it wrong, code for that: long __stdcall ResetHook(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS Parameters) { /* Delete imgui to avoid errors */ ImGui_ImplDX9_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); /* Check if its actually being called */ if (!ResetInit) { std::cout << "Reset called correctly" << std::endl; ResetInit = true; } /* Return old function */ return OldReset(pDevice, Parameters); } Just incase I did mess up the hooking process for 1 of the functions i will also include the code i used to actually hook them if (MH_CreateHook(vTable[42], EndSceneHook, (void**)&OldEndScene) != MH_OK) ThrowError(MinHook_Hook_Creation_Failed); if (MH_CreateHook(vTable[16],OldReset,(void**)&OldReset)!=MH_OK) ThrowError(MinHook_Hook_Creation_Failed); MH_EnableHook(MH_ALL_HOOKS);
Ok so I solved the issue already, but just incase anyone else needs help I have found a few fixes as to why it would crash/not render. First one being EnumWindow(), if you are using EnumWindows() to get your target processes HWND then that is likely one or your entire issue, For internal cheats, Use GetForegroundWindow() when the game is loaded, or you can use FindWindow(0,"Window Name") (works for both external and internal [game needs to be loaded]) void MainThread(){ HWND ProcessWindow = 0; WaitForProcessToLoad(GameHandle); // This is just an example of waiting for the game to load ProcessWindow = GetForegroundWindow(); // We got the HWND // or ProcessWindow = FindWindow(0,"Thing.exe"); } To start off with the 2nd possible issue, make sure your replacement functions for the functions your hooking are actually passing the right arguments (this is if your hook instantly crashes), and make sure you are returning the original function. Make sure your WndProc function is working correctly (if you dont know how then google DX9 Hooking Tutorials and copy + paste there code for that). Last fix is how you are rendering imgui to the screen, if imgui isnt rendering after the first fix then it is likely because you arent calling a function that is required, This is an example of correctly made imgui rendering long __stdcall EndSceneHook(IDirect3DDevice9* pDevice) // Our hooked endscene { if (!EndSceneInit) { ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); ImGui::StyleColorsDark(); ImGui_ImplWin32_Init(Window); ImGui_ImplDX9_Init(pDevice); EndSceneInit = true; return OldEndScene(pDevice); } ImGui_ImplDX9_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); ImGui::ShowDemoWindow(); ImGui::EndFrame(); ImGui::Render(); ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); return OldEndScene(pDevice); // Call original ensdcene so the game can draw } If none of these fixes worked then google the error or youtube DX9 hooking tutorials
73,008,323
73,184,958
Assert instead of throw
How can I set the error handling to assert instead of throw? I'd like it to debug break without attaching the debugger. Currently, I'm patching the source, adding __debugbreak() to assertions_impl.h in precondition_fail(). To be a bit more specific. There are a handful of global error handling functions. Their behavior is determined by checking flag from a function get_static_error_behaviour(). Currently, there are two constants to determine the behavior: THROW_EXCEPTION and CONTINUE. I'd like to add to it assert. This is an example that throws an exception (I found it somewhere, something about CCW order): #include <CGAL/Simple_cartesian.h> #include <CGAL/Polygon_2.h> #include <CGAL/Polygon_set_2.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef K::Point_2 CGALPoint; typedef CGAL::Polygon_2<K> CGALInnerPolygon; typedef CGAL::Polygon_set_2<K> CGALMultiPolygon; #include <iostream> using namespace std; int main() { CGALInnerPolygon cgalpoly; cgalpoly.push_back( CGALPoint( 0, 0 ) ); cgalpoly.push_back( CGALPoint( 1, 1 ) ); cgalpoly.push_back( CGALPoint( 1, 0 ) ); CGALMultiPolygon multipolygon; multipolygon.insert( cgalpoly ); printf( "bye\n" ); return 0; } Something has changed, either the new VS2022 or CGAL, but now it doesn't only print, it also throws an exception and VS breakpoints on the right line.
The behavior on assertion failure can be controlled, as documented here. If I am reading correctly, you want #include <CGAL/assertions_behaviour.h> int main(){ CGAL::set_error_behaviour(CGAL::ABORT); } or if that's not quite what you need, you can use CGAL::set_error_handler to provide your own handler.
73,008,424
73,008,537
Enable constructor iff two member functions are present in the passed template type
With this code: struct MyStructure { MyStructure(char* d, int size) {} template <typename T> MyStructure(T&& rhs) : MyStructure(rhs.data(), rhs.size()) {} }; How can I only enable the second constructor to be present if the data and size functions are present in whatever object is passed in?
Here is what Sam Varshavchik meant, which should work with C++11: struct MyStructure { MyStructure(char* d, int size) {} template <typename T, decltype(static_cast<char*>(std::declval<T &&>().data())) = nullptr, decltype(static_cast<int>(std::declval<T &&>().size())) = 0 > MyStructure(T&& rhs) : MyStructure(rhs.data(), rhs.size()) {} };
73,008,749
73,008,945
Why does the compiler issue a template recursion error?
I'm currently trying to deduce a std::tuple type from several std::vectors that are passed as parameters. My code works fine using gcc, but the compilation fails with Visual Studio Professional 2019 with the message "fatal error C1202: recursive type or function dependency context too complex". It has been mentioned for my previous post (C++ "fatal error C1202: recursive type or function dependency context too complex" in visual studio, but gcc compiles) that the problem is caused by template recursion as explained in C++ template compilation error - recursive type or function dependency. However, I don't see where the recursion occurs. So my questions are: Why is there an (infinite) recursion? How can it be resolved? Here is the code (I'm bound to C++11): #include <tuple> #include <vector> template <typename TT,typename Add> auto addTupBase(TT t,std::vector<Add> a) ->decltype (std::tuple_cat(t,std::make_tuple(a[0]))) { return std::tuple_cat(t,std::make_tuple(a[0])) ; } template <typename TT,typename Add,typename... Args> auto addTupBase(TT t,std::vector<Add> a,Args... args)-> decltype(addTupBase(addTupBase(t,a),args...)) { return addTupBase(addTupBase(t,a),args...); } template <typename T,typename... Args> auto addTup(std::vector<T> in,Args... args) ->decltype(addTupBase(std::make_tuple(in[0]),args...)) { return addTupBase(std::make_tuple(in[0]),args...); } int main() { using TupleType = decltype(addTup(std::vector<char>{2},std::vector<int>{5},std::vector<double>{32423})); TupleType t; std::get<2>(t) = 342.2; return 0; }
MSVC has some conformance issues when running in /permissive mode and "The Microsoft C++ compiler doesn't currently support binding nondependent names when initially parsing a template. This doesn't conform to section 14.6.3 of the C++ 11 ISO specification. This can cause overloads declared after the template (but before the template is instantiated) to be seen.". If you instead use /permissive- "The compiler [...] implements more of the requirements for two-phase name look-up" and will compile your program as-is. Also note that you aren't actually using C++11. MSVC 19.24 supports C++14 and up.
73,008,921
73,008,959
Obtain integer from collection of possible types at compile time?
The following code does not compile, because I don't know if what I want to do is possible, but it does show what I would like. I build, at compile time (if possible!), a collection of types and integer values; this is then used at compile time in the assignment operator which looks at the type that has been passed and stores that the corresponding integer from the collection in the member variable type_: struct MyStructure { MyStructure(char* d, int size) {} std::array<pair<TYPE, int>> map { { int, 1 }, { char, 2 }, { double, 4 }, { std::string, 8 } }; template <typename T> auto operator=(const T &arg) { // Depending on the type of 'arg', I want to write a certain value to the member variable 'type_' } int type_ = 0; }; int main() { MyStructure myStruct; myStruct = 1; // Should cause 1 to be stored in member 'type_ ' myStruct = "Hello world"; // Should cause 8 to be stored in member 'type_' } I need to solve this in C++17 please; extra respect for anyone who additionally gives a C++20 solution as that would be a learning opportunity!
Here's a basic blueprint that, with some cosmetic tweaks, can be slotted into your MyStructure: #include <string> #include <iostream> template<typename T> struct type_map; template<> struct type_map<int> { static constexpr int value=1; }; template<> struct type_map<char> { static constexpr int value=2; }; template<> struct type_map<double> { static constexpr int value=4; }; template<> struct type_map<std::string> { static constexpr int value=8; }; template<typename T> void some_function(const T &arg) { std::cout << type_map<T>::value << std::endl; } int main() { some_function(1); // Result: 1 some_function('a'); // Result: 2 some_function(std::string{"42"}); // Result: 8 return 0; }
73,009,104
73,009,131
SFINAE template specialization matching rule
I'm learning about SFINE with class/struct template specialization and I'm a bit confused by the matching rule in a nuanced example. #include <iostream> template <typename T, typename = void> struct Foo{ void foo(T t) { std::cout << "general"; } }; template <typename T> struct Foo<T, typename std::enable_if<std::is_integral<T>::value>::type> { void foo(T t) { std::cout << "specialized"; } }; int main() { Foo<int>().foo(3); return 0; } This behaves as expected and prints out specialized, however if I change the specialized function slightly to the following: template <typename T> struct Foo<T, typename std::enable_if<std::is_integral<T>::value, int>::type> { void foo(T t) { std::cout << "specialized"; } }; then it prints out general. What's changed in the second implementation that makes it less 'specialized'?
Re-focus your eyeballs a few lines higher, to this part: template <typename T, typename = void> struct Foo{ This means that when this template gets invoked here: Foo<int>().foo(3); This ends up invoking the following template: Foo<int, void>. After all, that's what the 2nd template parameter is, by default. The 2nd template parameter is not some trifle, minor detail that gets swept under the rug. When invoking a template all of its parameters must be specified or deduced. And if not, if they have a default value, that rescues the day. SFINAE frequently takes advantage of default template parameters. Now, let's revisit your proposed template revision: template <typename T> struct Foo<T, typename std::enable_if<std::is_integral<T>::value, int>::type> The effect of this specialization is that the 2nd template parameter in the specialization is int, not void. But Foo<int> is going to still use the default void for the 2nd template parameter because, well, that's the default value of the 2nd template parameter. So, only the general definition will match, and not any specialization.
73,009,176
73,009,321
Warning: null destination pointer [-Wformat-overflow=] with GCC 11.2.1
Here is my code: #include <iostream> #include <cstdio> int main() { char *str = new char[64] ; std::sprintf(str, "msg: %s", "hello world") ; std::cout << str << std::endl ; delete [] str ; return 0 ; } With GCC 11.2.1, using the following command: g++ -O -fsanitize=undefined -Wformat-overflow test.cpp I get: test.cpp:7:17: warning: null destination pointer [-Wformat-overflow=] 7 | std::sprintf(str, "msg: %s", "hello world") ; | ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I failed to understand the reason for the warning. Did I do anything wrong?
This seems like a bug/false-positive warning from the g++ compiler. The message is trying to warn you that using a pointer variable as the destination for the sprintf function could fail if that pointer is null (or points to a buffer of insufficient size). It is 'trivial' to suppress this warning: simply add a check that str is not null before calling sprintf: if (str) std::sprintf(str, "msg: %s", "hello world"); However, your code is fine as it stands, and that check is entirely superfluous, because the standard operator new [], as you have used it, cannot return a null pointer. You are using "Version (2)" of new as described on this cppreference page. Note, from that same page: Return value 1-4) non-null pointer to suitably aligned memory of size at least size If your new char[64] expression fails to allocate sufficient memory, then an exception will be thrown and (as your code stands) the sprintf function will not be called.
73,009,623
73,009,725
Inserting multiples values into text file from user input
I have this project where I need to insert multiples integers into text file by taking user input with certain range of that input in loop void append_text_multiple() { std::string file_name; std::cin >> file_name; std::ofstream getfile; getfile.open(("C:\\users\\USER\\Documents\\located_file\\" + file_name+ ".txt").c_str()); std::string verify_dtype; std::cin >> verify_dtype; if(verify_dtype == "int" || "INT") { int total_line; int item_append; std::cin >> total_line; for(int j=0; j<=total_line; j++) { std::cin >> item_append; getfile << item_append << '\n\'; getfile.close(); } } } Now that when I inserted 1 2 3 4 5 as my input while being inside the loop the output of that text file returns only single value which is 1 while I was expecting for 1 2 3 4 5. I'm not sure what's going on?
There are several issues in your code: Your for loop does total_line+1 iterations, instead of total_line. The loop should be for(int j=0; j<total_line; j++) (< instead of <=). You close the output file immediatly after writing the first value. Therefore the later writes are not performed. You should close it after all the values are written. Your condition for checking the value of verify_dtype is wrong, assuming you wanted to check whether the varaible has either 1 of the 2 values. Fixed version: #include <iostream> #include <fstream> void append_text_multiple() { std::string file_name; std::cin >> file_name; std::ofstream getfile; getfile.open(("C:\\users\\USER\\Documents\\located_file\\" + file_name + ".txt").c_str()); std::string verify_dtype; std::cin >> verify_dtype; if ((verify_dtype == "int") || (verify_dtype == "INT")) { int total_line; int item_append; std::cin >> total_line; for (int j = 0; j < total_line; j++) { std::cin >> item_append; getfile << item_append << "\n"; } getfile.close(); } } int main() { append_text_multiple(); }
73,009,682
73,009,730
Why dynamic_cast from reference causes a segmentation fault?
I have an expr_t base class, from which ident_t is derived. I wrote some to_string overloads to display differently between expr_t and ident_t: #include <iostream> #include <string> struct expr_t { virtual ~expr_t() {} }; struct ident_t : public expr_t { std::string name; ident_t(std::string name) : name(name) {} }; std::string to_string(expr_t& v) { if (auto* id = dynamic_cast<ident_t*>(&v)) { return to_string(*id); } return "error"; } std::string to_string(ident_t& v) { return v.name; } int main() { expr_t* b = new ident_t("c"); std::cout << to_string(*b) << std::endl; // segfault delete b; return 0; } However, no output is generated and seg-fault occurs when debugging with GDB.
The problem is that at the point of the call return to_string(*id) the compiler doesn't have a declaration for the second overload std::string to_string(ident_t& v). Thus the same first version will be recursively called eventually resulting in a seg fault. To solve this you can either move the second overload's definition before the first overload or forward declare the second overload before the definition of the first overload as shown below: //moved the 2nd overload above first overload std::string to_string(ident_t& v) { return v.name; } std::string to_string(expr_t& v) { if (auto* id = dynamic_cast<ident_t*>(&v)) { return to_string(*id); //now compiler knows about std::string to_string(ident_t& v) } return "error"; } Demo Method 2 //forward declaration for 2nd overload std::string to_string(ident_t& v); std::string to_string(expr_t& v) { if (auto* id = dynamic_cast<ident_t*>(&v)) { return to_string(*id); //now compiler knows about std::string to_string(ident_t& v) } return "error"; } //definition for 2nd overload std::string to_string(ident_t& v) { return v.name; } Demo
73,009,957
73,010,002
Is it possible to have a function-try-block per member initialiser?
During the member initialisation of a class with multiple members, it seems desirable to be able to catch an exception generated by any specific member initialiser, to wrap in additional context for rethrowing, but the syntax of a function-try-block doesn't appear to accomodate that. #include <stdexcept> #include <string> #include <sstream> using namespace std::literals::string_literals; [[noreturn]] int thrower() { throw std::runtime_error("unconditional throw"s); } int nonThrower() { return 3; } class C { int x; int y; public: C(); }; class XError : public std::runtime_error { public: XError(const std::string& what) : std::runtime_error((std::stringstream() << "xerror: "s << what).str()) {}; }; class YError : public std::runtime_error { public: YError(const std::string& what) : std::runtime_error((std::stringstream() << "yerror: "s << what).str()) {}; }; C::C() try: x(nonThrower()), y(thrower()) {} catch(const std::exception& e) { /* ... */ } In the above trivial example, on the final line, I would very much like to be able to throw XError() if the exception occurs in initialisation of .x, and YError() if the exception occurs in initialisation of .y. Ideally I'd like to be able to do something like // -std=c++3000 C::C(): try: x(nonThrower()) catch(const std::exception& e) { throw XError(e.what()); }, try: y(thrower()) catch(const std::exception& e) { throw YError(e.what()); } {} But it seems my only option is to write separate functions per initialiser member which wrap the exceptions themselves, then use those in the member initialisers. Given how ghastly member initialiser syntax is, this will probably read better, but it's less compact and more non-linear, which is less than ideal. For completeness: int makeX() { try { return nonThrower(); } catch(const std::exception& e) { throw XError(e.what()); } } int makeY() { try { return thrower(); } catch(const std::exception& e) { throw YError(e.what()); } } C::C(): x(makeX()), y(makeY()) {} Please excuse any antipatterns or mistakes in my C++. I am both very new to the language and not as smart as you might hope me to be.
Is it possible to have a function-try-block per member initialiser? No, that is not possible. Sidebar: it seems like you're overusing and/or overthinking exceptions. Most people don't write much exception-handling code, because most programs are fine with just terminating if an exception is thrown, in most places. Of course there are exceptions to this rule, but if you're new to C++ and you're getting hung up on this, you should probably revisit your approach and not make your program so reliant on fine-grained exception handling.
73,010,151
73,010,336
Why it takes me a long time to compile this simple C++ code
When I try to compile C++ code like this, it takes me 71s: #include<bits/stdc++.h> struct S{int v=1;}a[1<<25]; int main(){ return 0; } However, when I change the 1 to 0, it compiles in just 1s: #include<bits/stdc++.h> struct S{int v=0;}a[1<<25]; int main(){ return 0; } I know I can use something like S(){v=1;}, but I just want to know about this interesting difference. System: MacOS 12.4 Compiler: g++-11 (Homebrew GCC 11.3.0_2) 11.3.0
In your original case with struct S{int v=1;}a[1<<25];, a's initialization is a constant expression. Therefore the compiler needs to evaluate the value of the whole array at compile-time and store the result in the executable. (Generally in the .data segment.) The constant evaluation and keeping track of the stored value probably takes some significant overhead for the compiler. (Someone with knowledge of the GCC internals may be able to give more details on that.) If you add a constructor of the form S(){v=1;}, then because this constructor is not constexpr and will be chosen to construct the array elements, a will not be constant-initialized. Instead of evaluating and storing the array value, the compiler will just add instructions to the executable asking the program loader to allocate (and zero-initialize) memory for the array when the program is executed (generally via the .bss segment) and will then properly initialize the array before entering main at runtime. If you use int v=0; instead of int v=1;, then you still have constant-initialization, but the value of the whole array will be zero. This means again that the compiler only needs to add instructions for memory to be allocated for the array when the program starts. Such memory is automatically zero-initialized before execution of the program starts, so no further runtime initialization is required, keeping in line with the constant-initialization requirements. The compiler seems to be clever enough to recognize that here and seems to also optimize the evaluation/storage of the constant expression evaluation for this common case. At some point if the array is large enough, the initialization will again become non-constant-initialization and therefore potentialy compile more quickly, because there is an implementation-defined limit on the number of operations in a constant expression. If this limit is exceeded the initialization is no longer a constant expression and initialization of the array will happen at runtime again. Still, the compiler probably has to evaluate that many operations first before noticing that the limit is exceeded, which may also take significant compilation time. Compilers typically have configuration options for that limit, e.g. for GCC -fconstexpr-ops-limit and others, although I couldn't manage to get them to compile here faster. MSVC and Clang do actually seem to apply the limit (in the default configuration) and compile your initial example quickly as well.
73,010,411
73,011,489
CUDA customized atomicCAS for floating point types (like double)
atomicCAS allows using integral types of various lengths (according to specs word sizes of 16/32/64 bit). It works fine for integral types like int, unsigned long long,... I want to use atomic operations for non integral types of same length. My naive thought is to simply type-cast the data to an integral type of same length like double to uint64_t (unsigned long long). To avoid implicit conversion I do it via a pointer. Example double cmp = 0.0; double val = 4.6692016091; double dst = 0.0; uint64_t old = atomicCAS((uint64_t*)&dst, *((uint64_t*)&cmp), *((uint64_t*)&val)); Problem Threads quit as soon as the atomicCAS command is executed. I couldn't find any details why that happens. Is there a way to use atomicCAS that way in CUDA context? In case it's relevant: I use CUDA 11.7, --machine 64 nvcc switch and compute_61,sm_61 (Pascal architecture).
As @Homer512 pointed out, atomicCAS is implemented for global and shared memory, as it makes no sense in non concurrent scenarios (like thread local variables used in the example above) to use atomic operations (at least I can't think of any). Following vectorized example works instead. const unsigned int idx = (blockIdx.x * blockDim.x) + threadIdx.x; const unsigned int nThreads = 64; if (idx >= nThreads) return; __shared__ double s[nThreads]; const double cmp = s[idx] = 0.0; double val = 4.6692016091; uint64_t old = atomicCAS((uint64_t*)&s[idx], *((uint64_t*)&cmp), *((uint64_t*)&val));
73,010,535
73,010,671
How to make plot from file WinAPI
We have txt file with numbers: 60 0 120 4 180 20 60 -28 180 28 30 -28 30 28 30 -28 60 0 I need a plot with first column in horizontal coordinate line and the second column in vertical coordinate line like on this picture. But now I have smth like this std::ifstream omega_file("test.txt"); MoveToEx(hdc, 0, 0, NULL); // start point double T_new = 0; while (!omega_file.eof()) { omega_file >> T >> Omega; T_new = T_new + T; LineTo(hdc, T_new / 60 * horizontal_step_grid, - Omega * vertical_step_grid); MoveToEx(hdc, T_new / 60 * horizontal_step_grid, - Omega * vertical_step_grid, NULL); }
You will need to draw two lines (horizontal, then vertical) instead of one per one coordinate. Also note that LineTo() sets the current position, so MoveToEx() to the same coordinate is redundant. Try this: std::ifstream omega_file("test.txt"); MoveToEx(hdc, 0, 0, NULL); // start point int currentY = 0; double T_new = 0; while (omega_file >> T >> Omega) { T_new = T_new + T; int x = T_new / 60 * horizontal_step_grid; int nextY = - Omega * vertical_step_grid; LineTo(hdc, x, currentY); LineTo(hdc, x, nextY); currentY = nextY; }
73,010,742
73,010,823
Hello guys, ask a question about the address of C++
Why are mySwap02 and mySwap03 addresses different? #include<iostream> using namespace std; //1. Passing Directly void mySwap01(int a, int b) { cout << "mySwap01's address a:" << &a << endl; cout << "mySwap01's address b:" << &b << endl; int temp = a; a = b; b = temp; } //2. Passing by Pointer void mySwap02(int* a, int* b) { cout << "mySwap02's address a:" << &a << endl; cout << "mySwap02's address b:" << &b << endl; int temp = *a; *a = *b; *b = temp; } //3. Passing by Reference void mySwap03(int& a, int& b) { cout << "mySwap03's address a:" << &a << endl; cout << "mySwap03's address b:" << &b << endl; int temp = a; a = b; b = temp; } int main() { int a = 10; int b = 20; // Memory address cout << "Memory address a:" << &a << endl; cout << "Memory address b:" << &b << endl; mySwap01(a, b); cout << "a:" << a << " b:" << b << endl; mySwap02(&a, &b); cout << "a:" << a << " b:" << b << endl; mySwap03(a, b); cout << "a:" << a << " b:" << b << endl; system("pause"); return 0; } Memory Address a:000000220E3BFA5C Memory Address b:000000220E3BFA58 mySwap01's address a:000000220E3BFA18 mySwap01's address b:000000220E3BFA1C a:10 b:20 mySwap02's address a:000000220E3BFA10 mySwap02's address b:000000220E3BFA18 a:20 b:10 mySwap03's address a:000000220E3BFA5C mySwap03's address b:000000220E3BFA58 a:10 b:20
Let's take a look at what mySwap03 is doing. Note that I've translated some of the Chinese here; I've submitted the edits, but they have yet to be approved, at least for now. (Edit: My edits have been approved.) void mySwap03(int& a, int& b) { cout << "mySwap03's address a:" << &a << endl; cout << "mySwap03's address b:" << &b << endl; ... Here, you pass a and b by reference. Then, you use & to take the address of a and b. As you are passing by reference, this address will be the same as the address of the temporary variables you created in int main(). Now, let's look at mySwap02. void mySwap02(int* a, int* b) { cout << "mySwap02's address a:" << &a << endl; cout << "mySwap02's address b:" << &b << endl; ... Here, a and b are two pointers. They aren't actually ints. Now, you're taking the address with & of the two pointers, not the original integers. This means that you've created two pointers which point to the temporary variables created in int main(), and here you're printing the addresses of the pointers, not the addresses of the original variables. You can fix this in a few ways. You could try to dereference the pointers first, and then take the address of that. Something like this: void mySwap02(int* a, int* b) { cout << "mySwap02's address a:" << &(*a) << endl; cout << "mySwap02's address b:" << &(*b) << endl; ... Though, this is obviously redundant; & and * cancel each other out. So, you could do this: void mySwap02(int* a, int* b) { cout << "mySwap02's address a:" << a << endl; cout << "mySwap02's address b:" << b << endl; ... Now, the results of mySwap02 and mySwap03 are the same.
73,010,922
73,011,131
Generate nested for loops using C preprocessor
I want to generate nested for-loops instead of using recursion using the C preprocessor. The depth of this loop structure is bounded. An example nested for-loop with depth 3 is as below: for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < p; k++) { // do_computation() } } } The depth can be between 2 to 10. I have many variations of do_computation() function, so manually writing code for every depth with the combination of the function is making the code look bloated. Some of the answers in stack overflow point to using the boost preprocessor but unfortunately I will not be able to include boost in my application.
having #define MAKE_N_LOOP() would have been great! First generate MAKE_LOOP_# macros overloads for every count of arguments. Then write a MAKE_LOOP macro overloaded on number of arguments that redirects to each overload. #include <stdio.h> #define MAKE_LOOP_2(i, mi) for(int i = 0; i < mi; ++i) #define MAKE_LOOP_4(i, mi, ...) MAKE_LOOP_2(i, mi) MAKE_LOOP_2(__VA_ARGS__) #define MAKE_LOOP_6(i, mi, ...) MAKE_LOOP_2(i, mi) MAKE_LOOP_4(__VA_ARGS__) #define MAKE_LOOP_8(i, mi, ...) MAKE_LOOP_2(i, mi) MAKE_LOOP_6(__VA_ARGS__) // etc. #define MAKE_LOOP_N(_8,_7,_6,_5,_4,_3,_2,_1,N,...) MAKE_LOOP_##N #define MAKE_LOOP(...) MAKE_LOOP_N(__VA_ARGS__,8,7,6,5,4,3,2,1)(__VA_ARGS__) int main() { MAKE_LOOP(i, 5, j, 4, k, 10) { printf("%d-%d-%d\n", i, j, k); } } You might also be interested in Generating Nested Loops at Run Time in C .
73,011,448
73,011,689
Invalid read on a vector with size initialized by a variable using assert()
The simple function I've written catches a segfault on the test asserts that return 0 (false). #include <vector> #include <cassert> using namespace std; // checks whether the elements of a vector are some permutation of range [1..vector.size()] int isPermutation(vector<int> &&A) { int res = 1; int vecSize = A.size(); // vector to store elements already found in vector A vector<int> B(vecSize, 0); for (auto& it : A) { if (B[it - 1] != 0 || it > vecSize) { res = 0; break; } // element already exists in B or is outside the permutation range else { B[it - 1] = 1; } // register element } return res; } int main() { assert(isPermutation({4, 1, 3, 2}) == 1); assert(isPermutation({4, 1, 3, 2}) != 0); assert(isPermutation({1, 3}) == 0); assert(isPermutation({2}) == 0); assert(isPermutation({1}) == 1); assert(isPermutation({1, 2}) == 1); assert(isPermutation({4, 1, 3}) == 0); assert(isPermutation({4, 1, 2, 3, 6, 5, 8, 7}) == 1); return 0; } Valgrind points to the operator new[] which is used to manipulate the vector inside the function. Error 1/3 (same on lines 34 and 37): ==212== Invalid read of size 4 ==212== at 0x109306: isPermutation(std::vector<int, std::allocator<int> >&&) (main.cpp:16) ==212== by 0x109598: main (main.cpp:33) ==212== Address 0x4dade18 is 0 bytes after a block of size 8 alloc'd ==212== at 0x483BE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==212== by 0x10A6B7: __gnu_cxx::new_allocator<int>::allocate(unsigned long, void const*) (new_allocator.h:114) ==212== by 0x10A5CB: std::allocator_traits<std::allocator<int> >::allocate(std::allocator<int>&, unsigned long) (alloc_traits.h:443) ==212== by 0x10A427: std::_Vector_base<int, std::allocator<int> >::_M_allocate(unsigned long) (stl_vector.h:343) ==212== by 0x10A2C0: std::_Vector_base<int, std::allocator<int> >::_M_create_storage(unsigned long) (stl_vector.h:358) ==212== by 0x109F6A: std::_Vector_base<int, std::allocator<int> >::_Vector_base(unsigned long, std::allocator<int> const&) (stl_vector.h:302) ==212== by 0x109BF2: std::vector<int, std::allocator<int> >::vector(unsigned long, int const&, std::allocator<int> const&) (stl_vector.h:521) ==212== by 0x10928B: isPermutation(std::vector<int, std::allocator<int> >&&) (main.cpp:12) ==212== by 0x109598: main (main.cpp:33) Asserts that return 1 do not face this problem. Initializing the vector B using some constant instead of vecSize also clears the errors. Any ideas?
There is a bug in if (B[it - 1] != 0 || it > vecSize) If it is larger than the size of the vector you first try to access an invalid element which causes UB. You should switch this to if (it > vecSize || B[it - 1] != 0) so that you are sure that you only evaluate B[...] when the index is valid. (In addition you may want to check that it > 0)
73,011,722
73,014,415
Why are port numbers stored as strings?
The question is: Why can't I pass port numbers to DNS resolution functions as 16-bit unsigned ints to prevent std::string to unsigned short conversions? Background: I am looking at the Networking TS and the boost.asio implementation of the function tcp::ip::resolver::resolve. The function takes as input the web address and the port number of the service you want to connect to and performs DNS name resolution. The signature of this function is results_type resolve(string_view host, string_view service, ...); As an example, boost::asio::io_context serv{}; boost::asio::ip::tcp::resolver res{serv}; std::string web_address{ "www.google.com" }; std::string port_number{ "80" }; auto result = res.resolve(web_address, port_number); performs DNS lookup for www.google.com. Ultimately, in the TCP header, the port number will need to be stored as a 16-bit unsigned int. If the user wants to save on the std::string to unsigned short conversion, the user could have just written unsigned short port_number{ 80 }; However, there is no signature in the Networking TS or the boost.asio library for results_type resolve(string_view host, PortType service, ...); (where PortType will be a 16-bit unsigned int). Why is that?
Because it is a thin wrapper around the POSIX getaddrinfo(3), which takes a const char* service. Since a string has to be created to pass to getadddrinfo() anyways, there's not actually much benefit to having additional overloads that take uint16_t port numbers. Using resolve(web_address, std::to_string(integer_port_number)); works fine, and the overhead of string construction+formatting is dwarfed by the time it takes to do a DNS lookup. There could absolutely be overloads that takes a uint16_t port. It could do the string formatting to some internal buffer on the stack. The savings would be tiny because of short string optimization, but at least the API user won't have to convert integers. This seems like a thing to suggest to the Boost.Asio developers and Networking TS people. It has precedent in other networking APIs with Python's getaddrinfo taking ports as numbers or numeric strings, converting as necessary. And as an aside, ports are not specified by the internet protocol (layer 3 in the OSI model), but separately by UDP and TCP (on the transport layer, layer 4), and this is meant to be a generic resolver for anything on the IP stack. You can imagine some different transport layer where ports aren't 16 bit integers, but 32 bit integers or file names or something else entirely.
73,011,795
73,217,895
How to multiply two images with different encoding
I have two textures map, one albedo and another ambient occlusion. The albedo one is srgb encoded .jpg whereas the ambient occlusion is linear encoded .jpg. Now, I want to load these two images (preferably in node.js) and multiply their rgb values evenly(0.5 weight) and output the image in .jpg format with sRGB encoding. I tried to simply read and write a linear encoded normal map using the sharp library(npm, node.js) as a test, with the following code, but the output image looks slightly darker now. import sharp from 'sharp'; const img = sharp('assets/normal.jpg'); const processedImg = img .resize(1024) .jpeg({ quality: 100 }); processedImg.toFile('assets/__normal.jpg'); Even, the metadata() function on the image says the image is in srgb space, but I had exported the maps from Quixel Bridge and I know that those are linear encoded, still the metadata returns that they are in srgb space. I can't find any hints from the sharp.js documentation on how to force change the input file encodings. Basically, I want to replicate this operation in blender, but using code in node.js or c++. I can use some other library, if recommened. I am even open to c or c++ solutions if it can't be done in nodejs or gets complicated. Thank you in advance.
Well I found out a trick with which we can trick sharp to work with linear encodings. So, we know that our file is linear encoded. But since it has no metadata, sharp assumes it to be sRGB encoded. So what can we do? Hmm.. sharp(ifile) .pipelineColourspace('srgb') .toColourspace('srgb') .toBuffer(); We say to sharp that please while processing our file don't gamma correct our linear encoded file(i.e. sharp would think its sRGB, and would have applied gamma correction) to linear (which it normally does), but instead work with supposedly ``sRGB(i.e. linear```) values. .pipelineColourspace('srgb') tells sharp to do the image-processing with sRGB values, and since sharp wrongly assumed that our file is sRGB, it doesn't gamma correct our file, cause it thinks it already in the required format. .toColourspace('srgb') tells sharp to output the iamge as srgb values, now again since to sharp our pipeline was sRGB it doesnt gamma correct it again, and just simply spits the buffer received from pipeline. This way we tell sharp to avoid applying gamma correction on our image. Cool. Now lets answer the whole question, on how to multiply srgb albedo, linear ao, and output to a sRGB image. export const multiplyTexture = async (albedo: Buffer, ao: Buffer) => { return sharp(albedo) .pipelineColorspace('linear') .composite([ { input: await sharp(ao) .pipelineColourspace('srgb') .toColourspace('srgb') .toBuffer(), blend: 'multiply', gravity: 'center', }, ]) .toColorspace('srgb') .toBuffer(); };
73,011,966
73,012,797
Unable to compile C++ program with Clang-14
I am currently trying to compile a small program I have been working on with Clang and am getting the following error on compilation using scons as the build system: /usr/bin/clang++ -o src/PluGen/main.o -c -std=c++17 -fPIC -I. -O2 -fno-strict-aliasing -fpermissive -fopenmp --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security -fpermissive -fPIC -I. -O2 -flto -fwrapv -fno-strict-aliasing -pipe -fstack-protector-strong -DHAVE_PYTHON -D_REENTRANT -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DLARGE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_PERL -DREENTRANT -DHAVE_R -I/usr/include -I/usr/local/include -Isrc -I/usr/include/python3.10 -I/usr/lib/perl5/5.36/core_perl/CORE -I/usr/include/R -I/usr/lib/R/library/Rcpp/include -I/usr/lib/R/library/RInside/include -I/usr/lib/R/site-library/RInside/include -I/usr/lib/R/site-library/Rcpp/include -I/usr/local/lib/R/library/Rcpp/include -I/usr/local/lib/R/library/RInside/include -I/usr/local/lib/R/site-library/RInside/include -I/usr/local/lib/R/site-library/Rcpp/include -I/usr/local/lib/R/site-library/RInside/lib src/PluGen/main.cxx ... /usr/bin/clang++ -o PluGen/plugen -rdynamic -Wl,-E -Wl,-rpath,/usr/lib/perl5/5.36/core_perl/CORE -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now src/PluGen/main.o src/PluGen/PluginGenerator.o -L/lib -L/usr/lib -L/usr/local/lib -L/usr/lib/perl5/5.36/core_perl/CORE -L/usr/lib/R/lib -L/usr/lib/R/library/RInside/lib -L/usr/lib/R/site-library/RInside/lib -L/usr/local/lib/R/library/RInside/lib -L/usr/local/lib/R/site-library/RInside/lib -Llib -lc -lc++ -lstdc++fs src/PluGen/main.o: file not recognized: file format not recognized clang-14: error: linker command failed with exit code 1 (use -v to see invocation) main.o is being generated as a IR bitcode file src/PluGen/main.o src/PluGen/main.o: LLVM IR bitcode Running the linker outside of the scons builder yields the following message: clang version 14.0.6 Target: x86_64-pc-linux-gnu Thread model: posix InstalledDir: /usr/bin Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-pc-linux-gnu/12.1.0 Found candidate GCC installation: /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0 Selected GCC installation: /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0 Candidate multilib: .;@m64 Candidate multilib: 32;@m32 Selected multilib: .;@m64 "/usr/bin/ld" -pie -export-dynamic --eh-frame-hdr -m elf_x86_64 -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o PluGen/plugen /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0/../../../../lib64/Scrt1.o /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0/../../../../lib64/crti.o /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0/crtbeginS.o -L/lib -L/usr/lib -L/usr/local/lib -L/usr/lib/perl5/5.36/core_perl/CORE -L/usr/lib/R/lib -L/usr/lib/R/library/RInside/lib -L/usr/lib/R/site-library/RInside/lib -L/usr/local/lib/R/library/RInside/lib -L/usr/local/lib/R/site-library/RInside/lib -Llib -L/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0 -L/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/bin/../lib -L/lib -L/usr/lib -E -rpath /usr/lib/perl5/5.36/core_perl/CORE -O1 --sort-common --as-needed -z relro -z now src/PluGen/main.o src/PluGen/PluginGenerator.o -lc -lc++ -lstdc++fs -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0/crtendS.o /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.1.0/../../../../lib64/crtn.o src/PluGen/main.o: file not recognized: file format not recognized The program does compile correctly using GCC. Just not with Clang. What is going on?
You are using -flto when compiling, but not when linking. clang can't do that. -c -flto compiles to LLVM IR bitcodes which the linker cannot use directly. You should either drop -flto everywhere, or use it everywhere. $ clang++ -flto -c hello.cpp $ file hello.o hello.o: LLVM IR bitcode $ clang++ -o hello hello.o && echo Ok hello.o: file not recognized: file format not recognized clang: error: linker command failed with exit code 1 (use -v to see invocation) $ clang++ -o hello hello.o -flto && echo Ok Ok gcc works differently. It compiles to "fat objects" with both machine code and internal compiler representation baked in. Linker can use these, and apply the LTO plugin automatically. $ g++ -c hello.cpp -flto $ file hello.o hello.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped $ g++ -o hello hello.o && echo Ok Ok
73,012,005
73,012,066
Expansion of multiple parameter packs of types and integer values
I previously asked this question, which basically asked how do I change the following "pseudo code" to get the result the comments show: struct MyStructure { std::array<pair<TYPE, int>> map { { int, 1 }, { char, 2 }, { double, 4 }, { std::string, 8 } }; template <typename T> auto operator=(const T &arg) { // Depending on the type of 'arg', I want to write a certain value to the member variable 'type_' } int type_ = 0; }; int main() { MyStructure myStruct; myStruct = 1; // Should cause 1 to be stored in member 'type_ ' myStruct = "Hello world"; // Should cause 8 to be stored in member 'type_' } I obtained a suitable answer in the linked question, but now I have a different requirement. I would like to be able to pass the possible integer values and types through as template arguments, and somehow expand them to auto-generate the specialisations as given on the accepted answer. The reason for this is that MyStructure now has to specify the possible values that can be assigned to it, so the 'hard coded' solution approach would not work. My first thought was to create a new class that MyStructure derives from, that takes the types parameter pack and the ints parameter pack... template<typename... Types, int...ints> class Base_Type { // Somehow expand the packs to generate the specialisations }; template<typename... Types, int...ints> struct MyStructure : Base_Type<Types..., ints...> { // template <typename T> auto operator=(const T &arg) { // Check T is within 'Types' // Query Base_Type for the T specialization to get the corresponding integer value to write to 'type_' } int type_ = 0; }; Unfortunately I can't see how to do this because - for a start - I can only apparently have one template parameter pack: 'Types': if a class template has a template parameter pack it must appear at the end of the template parameter list Is what I want to achieve here possible with C++ 17?
It's not possible to generate specializations, but you don't actually need those. It's not possible to have more than one template parameter pack per class template, so we'll have to work with a single one, with a helper struct that combines both a type and its index into a single type. #include <cstddef> #include <iostream> #include <type_traits> template <typename T, int I> struct Type { using type = T; static constexpr int value = I; }; template <typename ...P> struct Foo { int index = 0; template <typename T, std::enable_if_t<(std::is_same_v<T, typename P::type> || ...), std::nullptr_t> = nullptr> Foo &operator=(const T &) { (void)((std::is_same_v<T, typename P::type> ? (index = P::value, true) : false) || ...); return *this; } }; int main() { Foo<Type<int, 10>, Type<float, 20>> x; x = 42; std::cout << x.index << '\n'; // 10 x = 42.f; std::cout << x.index << '\n'; // 20 // x = 42L; // Error. } (X || ...) is a fold expression. It repeats X multiple times, once per element of P. Every use of P in X is replaced with its i-th element. We use it as a poor man's loop. When the types match and ? : returns true, the loop stops. The cast to (void) silences the "unused result" warning.
73,012,092
73,018,927
Getting cable a connected/disconnect notification
On Windows with Qt5.15, I implemented a cable connected/disconnected notifier based on QNetworkInterface. It calls allinterfaces() every second and checks the flags. It works. However now I'm wondering what are the alternatives. Is there a simpler way, perhaps a native Windows thing that I should just listen?
There is not really a signal for this in QNetworkInterface. Polling is the only way to achieve this cross-platform using the isUp method. I would not compromise the cross-platform behaviour for a Windows specific API as that would have an impact on the portability of the application. Polling may not be ideal for you, but it is cross-platform. Which seems to be a strong value in a Qt application. Moreover, cable disconnection is not the only reason why an interface may be unavailable. This is also why often there is a "ping timeout" for such things to detect all sorts of cases when a network interface goes down. If you think that there ought to be a signal for this, you can open a ticket on the Qt Project tracker (Jira) explaining your use case. If they think that your request is reasonable, someone may eventually implement it for you. Even better if you submit a patch yourself.
73,012,226
73,012,257
Trim the last letter of a string
Lets say that I have a text file "myfile.txt" that assigned to a string variable and I want to get rid of the dot and the rest of extension file character .txt #include <stdio.h> #include <string> #incldue <iostream> int main() { std::string F = "myfile.txt"; return 0; } So the output I want to achieve is "myfile". Using std::size doesn't look like it's gonna works on my case aswell, is there a way that I can construct what I wanted?
When you're dealing with paths, using std::filesystem is helpful. #include <filesystem> #include <string> #include <iostream> int main() { std::string F = "myfile.txt"; std::filesystem::path p(F); std::cout << p.stem(); // prints "myfile" } or if you want it back as a string: #include <string> #include <iostream> #include <filesystem> int main() { std::string F = "myfile.txt"; F = std::filesystem::path(F).stem().string(); std::cout << F << '\n'; // prints myfile } (or use replace_extension as in wohlstads answer)
73,012,556
73,035,564
Code::Blocks Debugger : how to `step into` functions on line-by-line execution?
When debugging a C++ program on Code::Blocks 20.03, I press SHIFT+F7 to step into the program, then I begin pressing F7 to go to the next line and watch variables changing in "real time". But Code::Blocks 20.03's debugger won't enter any functions beside main, making it pretty useless, or forcing me to not use any function besides main (a bad programming practice). How can I make Code::Blocks 20.03's debugger enter the functions too?
Set a breakpoint (red circle) exactly on the line the function main is defined; Instead of pressing F8 (the same as clicking Debug->Start/Continue), which would make the program just run until the last line and exit (only flashing on the screen before disappearing), press Shift+F7 (the same as clicking Debug->Step Into), in order to make the debugger enter the function and not just run it completely and return its result; Press F7 (the same as clicking Debug->Next line) to keep watching the program run "step-by-step"; When any other function is called, and the debugger is on that line (yellow arrow), you may enter that other function too, by repeating step 2. Reference: ImageCraft - CodeBlocks Debugger Functions. Source Line Stepping Once paused, you can continue execution: Debug->Start/Continue runs the program until the next breakpoint. Debug->next line runs the program until the next source line. If the current source line contains a function call, it will “step over” the function call. Debug->Step into will “step into” a function call, and pause at the next source line. Debug->Step out will continue program execution until the function call returns to its caller. Debug->Next instruction and Debug->Step into instruction are assembly debugging commands, and should not be used within the CodeBlocks IDE. Instead, the corresponding commands in the ADT should be used.
73,012,635
73,021,315
Check if given keypair is valid C++
I want to check if the given key pair is valid, I had found solution, but it didn't work because object of the RSA class doesn't have parameter n. #include <openssl/rsa.h> #include <openssl/pem.h> int main() { RSA *pubkey = PEM_read_RSA_PUBKEY(...); RSA *privkey = PEM_read_RSAPrivateKey(...); if (!BN_cmp(pubkey->n, privkey->n)) { // same modulus, so the keys match } return 0; } How to solve my problem, or is there another way to test if the key pair is valid?
OpenSSL 3.x OpenSSL 3.x provides EVP_PKEY_get_bn_param. It can be used like this (error handling for reading the keys etc. has to be added accordingly of course): #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/core_names.h> ... EVP_PKEY *priv_key= NULL, *pub_key= NULL; BIGNUM *rsa_pub_n = NULL, *rsa_priv_n = NULL; ... PEM_read_PUBKEY(fp_pub, &pub_key, NULL, NULL) PEM_read_PrivateKey(fp_priv, &priv_key, NULL, NULL) ... //extract n with EVP_PKEY_get_bn_param for the keys... if (EVP_PKEY_is_a(priv_key, "RSA")) { if (!EVP_PKEY_get_bn_param(priv_key, OSSL_PKEY_PARAM_RSA_N, &rsa_priv_n)) { //error message and exit } //finally compare with BN_cmp See documentation here: https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_get_bn_param.html OpenSSL 1.x For OpenSSL 1.x the function RSA_get0_key can be used. Please note that this function is marked as deprecated in OpenSSL 3.x. #include <openssl/rsa.h> #include <openssl/pem.h> ... BIGNUM *rsa_pub_n = NULL, *rsa_priv_n = NULL; ... RSA *pub = RSA_new(); PEM_read_RSA_PUBKEY(fp_pub, &pub, NULL, NULL) RSA *priv = RSA_new(); PEM_read_RSAPrivateKey(fp_priv, &priv, NULL, NULL) ... RSA_get0_key(pub, &rsa_pub_n, NULL, NULL); RSA_get0_key(priv, &rsa_priv_n, NULL, NULL); ... //finally compare with BN_cmp Make sure to check the return codes for each function and add proper error handling. More information here: https://www.openssl.org/docs/manmaster/man3/RSA_get0_key.html
73,012,745
73,013,308
How I can keep aggregate initialization while also adding custom constructors?
If I don't define a constructor in a struct, I can initialize it by just picking a certain value like this: struct Foo { int x, y; }; Foo foo = {.y = 1}; But if I add new default constructor then I lose this feature: struct Bar { int x, y; Bar(int value) : x(value), y(value) {} }; Bar bar1 = 1; Bar bar2 = {.y = 2}; // error: a designator cannot be used with a non-aggregate type "Bar" Is it possible to have both ways? I tried adding the default constructor Bar () {} but it seems to not work either.
Similar to what ellipticaldoor wrote: struct FooBase { int x = 0, y = 0; }; struct Foo : FooBase { Foo(int x_) : FooBase{.x = x_} { } Foo(FooBase &&t) : FooBase{t} {} }; Foo foo = {{.y = 1}}; Foo foo2{1};
73,013,124
73,013,992
How to cast a void pointer to another type of pointer and assign it
What I've tried: Main.h #pragma once union TBufferRec { int ID; }; extern TBufferRec BufferRec; Main.cpp #include "Main.h" void CastPointer(void* PPointer) { static_cast<TBufferRec*>(*BufferRec) = static_cast<TBufferRec*>(PPointer); } Errors: E0349 no operator "*" matches these operands C2679 binary '=': no operator found which takes a right-hand operand of type 'TBufferRec *' (or there is no acceptable conversion) How can I make BufferRec point to another address? SOLVED: Very informative feedback, thank you. Main.h #pragma once union TBufferRec { int ID; }; extern union TBufferRec* BufferRec; extern void MovePointer(void* PPointer); Main.cpp #include "Main.h" TBufferRec* BufferRec; void MovePointer(void* PPointer) { BufferRec = static_cast<TBufferRec*>(PPointer); }
Let's do it step by step, solving one problem at a time and building upon previous solituons. Suppose you have two pointers to TBufferRec objects, how to assign one object to the other? Given a pointer, you access the pointed-to object by dereferencing (the unary asterisk operator). void assign0(TBufferRec* lhs, TBufferRec* rhs) { *lhs = *rhs; } OK now one of the pointers is still pointing to a TBufferRec, but has type void*, what to do? You convert a pointer of one type to a pointer of another type by casting. void assign1(TBufferRec* lhs, void* rhs) { assign0(lhs, static_cast<TBufferRec*>(rhs)); // or the same as // *lhs = *static_cast<TBufferRec*>(rhs); } OK now instead of a pointer, you have an actual variable, what to do? Given a variable, you obtain a pointer to it by using the address-of operator (the unary ampersand, the opposite of dereferencing) void assign2(void* rhs) { extern TBufferRec lhs; assign1(&lhs, rhs); // or the same as // assign0(&lhs, static_cast<TBufferRec*>(rhs)); // or the same as // *(&lhs) = *static_cast<TBufferRec*>(rhs); // or the same as // lhs = *static_cast<TBufferRec*>(rhs); }
73,013,185
73,013,265
Opengl GLSL value changes for no reason
I recently decided to make my own voxel game with opengl in C++ (using glfw). I'm looking to add textures to the blocs (I already done the chunk system). To do this, I add for every bloc added to the vertices array and ID for the texture (1 = cobblestone, 2 = dirt, ...) and I take the ID back directly in the shader to apply the texture. When I launch my game with only cobblestone, it works perfectly : Image link : https://www.mediafire.com/view/xh28aq5z1vcsacl/COBBLE.png/file But the problem is when I use dirt blocs : Image link : https://www.mediafire.com/view/6lkacdmdkb1fibd/DIRT.png/file Here is my vertex shader : #version 330 core layout (location = 0) in vec3 aPos ; layout (location = 1) in vec3 aNormal ; layout (location = 2) in vec2 aTexCoords ; layout (location = 3) in float type ; //I am importing here the ID uniform mat4 model ; uniform mat4 view ; uniform mat4 projection ; out vec3 Normal ; out vec3 FragPos ; out vec2 TexCoords ; out float BlockType ; void main(){ gl_Position = projection * view * model * vec4(aPos, 1.0f) ; FragPos = vec3(model * vec4(aPos, 1.0f)) ; Normal = aNormal; TexCoords = aTexCoords ; BlockType = type ; //I send it to the fragment shader //I have already tried to send a constant value : //BlockType = 2 ; //To be sure that the problem does not come from the vertices array //And It changes nothing so the problem is after sending } And the fragment shader : #version 330 core #define NR_POINT_LIGHTS 1 #define NB_TEXTURES_TYPE 3 out vec4 FragColor ; struct Material { sampler2D diffuse[NB_TEXTURES_TYPE]; //Those sampler2D contains the textures sampler2D specular[NB_TEXTURES_TYPE]; float shininess; }; in vec2 TexCoords; in vec3 FragPos; in float BlockType ; uniform Material material; //I create the uniform that permit to import the textures here void main(){ //Here I convert the ID into integer to use it for an array int btype = int(BlockType) ; if(btype > 0){ btype -= 1 ; //I reduce by 1 the ID because 0 is equivalent to air from my C++ program but here this is the cobble (because an array start by 0). } FragColor = vec4(vec3(texture(material.diffuse[btype], TexCoords)), 1.0) ; //And finally I send the result. //I already done to add a constant instead of the btype variable : //FragColor = vec4(vec3(texture(material.diffuse[1], TexCoords)), 1.0) ; //And when I do this, it works, I obtain the dirt texture. } I have the impression that the value of the ID of the bloc changes for no reason between the vertex shader and the fragment shader I don't know why.
"I have the impression that the value of the ID of the bloc changes for no reason between the vertex shader and the fragment shader" Of course, the value of the fragment shader input is interpolated between the outputs of the vertex shader associated with the primitive. If you don't want the input to be interpolated, you must use the flat Interpolation qualifiers: vertex shader flat out float BlockType; fragment shader flat in float BlockType;
73,013,608
73,013,622
Returning vector array from a function
I am actually trying to solve the K rotate question where we have to rotate the key number of elements to the right and place them on the left. I have checked the whole code using a normal array instead of a vector and it works fine but the function with the vector array never returns anything when i run this. I have checked all the online resources and cannot identify what exactly is the error as the logic and syntax are both correct. pls, help out with this !! #include<bits/stdc++.h> using namespace std; vector<int> rotate_array(vector<int> arr, int n, int key) { int i,j=0; vector<int> subst; for(i=n-1; i>=n-key; i--) { subst[j] = arr[i]; j++; } j=0; for(i=key; i<n; i++) { subst[i] = arr[j]; j++; } return subst; } int main() { vector<int> arr = {1, 2, 3, 4, 5}; // output for this should be -- {4, 5, 1, 2, 3} int n = arr.size(); int key = 2; vector<int> array = rotate_array(arr, n, key); for(int i=0; i<n; i++) { cout<<array[i]<<" "; } }
The vector subst in the function rotate_array has no elements, so accessing its "elements" (subst[j] and subst[i]) is illegal. You have to allocate elements. For example, you can do that using the constructor: vector<int> subst(n); // specify the number of elements to allocate
73,014,358
73,014,488
How to implement Singleton C++ the right way
I am currently trying to implement a class with the Singleton Pattern in C++. But I get following linking error: projectgen.cpp:(.bss+0x0): multiple definition of `Metadata::metadata'; C:\Users\adria\AppData\Local\Temp\ccdq4ZjN.o:main.cpp:(.bss+0x0): first defined here collect2.exe: error: ld returned 1 exit status What's the error's cause? Metadata.h: (Singleton class) #pragma once class Metadata { public: Metadata(Metadata &other) = delete; void operator=(const Metadata &other) = delete; static Metadata *getInstance() { return metadata; } static void createInstance(Ctor &params) { if (!metadata) { metadata = new Metadata(params); } } protected: Metadata(Ctor &params) { m_vars = params; } static Metadata *metadata; private: Ctor m_vars; } Metadata* Metadata::metadata = nullptr; main.cpp: #include "metadata.h" int main(void) { Ctor ctor; Metadata::createInstance(ctor); Metadata* data = Metadata::getInstance(); return 0; } projectgen.cpp: #include "metadata.h" void ProjectGenerator::test() { Metadata* data = Metadata::getInstance(); }
An #include statement is logically equivalent to taking the included header file and physically inserting it into the .cpp file that's including it. Metadata* Metadata::metadata = nullptr; In the included header file, this defines this particular static class member. Therefore, every .cpp file that includes this header file defines this class member. You have two .cpp files that include this header file, and each one defines the same static class member. This violates C++'s One Definition Rule. An object can be defined exactly once. Simply move this definition to one of your .cpp files.
73,014,412
73,014,582
How to understand const Someclass& a in constructor
I'm trying to understand the code below. More specifically, why is b.x in the main function 5? As far as I understand, I have a constructor Someclass(int xx):x(xx){} in the class which sets my attribute x to xx. Therefore, a.x in the main function is 4. But what do the lines Someclass(const Someclass& a){x=a.x;x++;} and void operator=(const Someclass& a){x=a.x;x--;} do? Is the first one also a constructor? And I think the second one overrides the '=' operation. But with what? And what is this a in the class? Since I am still quite new to programming, I would really appreciate your help! class Someclass{ public: int x; public: Someclass(int xx):x(xx){} Someclass(const Someclass& a){x=a.x;x++;} void operator=(const Someclass& a){x=a.x;x--;} }; int main() { Someclass a(4); Someclass b=a; cout<<"a:"<<a.x<<endl; //prints 4 cout<<"b:"<<b.x<<endl; //prints 5 return 0; }
When you instantiate a with the following line: Someclass a(4); You are calling the "normal" constructor, namely: class Someclass { public: int x; public: Someclass(int xx):x(xx){} // <= This one Someclass(const Someclass& a){x=a.x;x++;} void operator=(const Someclass& a){x=a.x;x--;} }; When you instantiate b with the following line: Someclass b=a; You are creating a new object (b) from an already existing one (a). This is what the copy constructor is for. class Someclass { public: int x; public: Someclass(int xx):x(xx){} Someclass(const Someclass& a){x=a.x;x++;} // <= This one void operator=(const Someclass& a){x=a.x;x--;} }; To put it simply, the equals operator is for the already instantiated object. This operator would be called if you wrote the following: Someclass a(4); Someclass b = a; b = a; std::cout << b.x << std::endl; // Prints 3
73,015,147
73,016,378
Why r-value reference to pointer to const initialized with pointer to non-const doesn't create an temporary and bind it with it?
If we want to initialize an reference with an different type, we need to make it const (const type*) so that an temporary can be generated implicit and the reference binded to with. Alternativaly, we can use r-value references and achieve the same [1]: Rvalue references can be used to extend the lifetimes of temporary objects (note, lvalue references to const can extend the lifetimes of temporary objects too, but they are not modifiable through them) : [...] Samples Case 1 double x = 10; int &ref = x; //compiler error (expected) Case 2 double x = 10; const int &ref = x; //ok Case 3 double x = 10; int &&ref = x; //ok If we try to do the same with reference to const pointer (const type* &) and initialize it with non-const pointer (type*), different than I expected, only the case 2 works. Why the case 3 leads to compiler error? Why the temporary isn't generated? Case 1 int x = 10; int *pX = &x; const int* &ref = pX; //compiler error (expected) Case 2 int x = 10; int *pX = &x; const int* const &ref = pX; //ok (expected) Case 3 int x = 10; int *pX = &x; const int* &&ref = pX; //compiler error (why?) In gcc 12.1.0 and clang 14.0.4 with flag -std=c++20 (and some others) the case 3 above don't compile. gcc : 'error: cannot bind rvalue reference of type 'const int*&&' to lvalue of type 'int*'' clang: 'error: rvalue reference to type 'const int *' cannot bind to lvalue of type 'int *' Why in the case of int&, int&&, etc., all worked well, and in this case with pointer there was compiler error? Is there some imprecision in my current knowledge? (I'm novice) If we do the same with an pr-value (int*), everything works well Case 3 int x = 10; //int *pX = &x; const int* &&ref = &x; //ok (why?) Related questions: <Non-const reference to a non-const pointer pointing to the const object> <const reference to a pointer not behaving as expected> Similar questions but both suggest using reference to const (type* const &). I wonder why r-value reference dont works with pointer, but work with int, etc., and that wasn't asked. <What does T&& (double ampersand) mean in C++11?> r-value reference (&&) References [1] https://en.cppreference.com/w/cpp/language/reference
The standard has a concept of two types being reference-related. This is fulfilled by two types being similar, which basically means if they are the same type with the same number of pointers but possibly different cv-qualifiers (e.g., int and const int are similar, int* const ** volatile and volatile int** const * are similar, and crucially int* and const int* are similar). The standard says that ([dcl.init.ref]p(5.4.4)): If T1 is reference-related to T2: if the reference is an rvalue reference, the initializer expression shall not be an lvalue. And since const int* &&ref = pX;, an rvalue reference, and T1 = const int* is reference-related to T2 = decltype(pX) = int*, this applies and so this just isn't allowed. const int* &&ref = std::move(pX); doesn't run into this issue, since the initializer is no longer an lvalue. And of course, explicitly doing the const conversion const int* &&ref = (const int*) pX; also works. Presumably, this is so const T x; T&& y = x; (binding y to a temporary copy of x) isn't allowed, but by a quirk of the standard it also extends to pointers.
73,015,262
73,020,965
Is it possible to install different versions of a library in one place?
The Requirement I want to have multi versions of a library installed in one place(e.g. the default system prefix path) using CMake to be used like: find_package(Package 1.0.0 REQUIRED). Why just don't set some paths? Because I'm an idiot at remembering paths and flags and other related stuff and I think it's the CMake's find_package job to handle it. The Problem The find_package's version parameter is just an ordinary parameter that will be passed to the package *VersionConfig.cmake file for version checking and if that file doesn't exists CMake will treat it as an error. So we couldn't install different version in the same place. Minimal CMake Configuration file(WRITE Library.H "void Function();") file(WRITE Library.C "void Function() {}") add_library(Library SHARED Library.H Library.C) target_include_directories(Library PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}> $<INSTALL_INTERFACE:include/Library> ) set_target_properties(Library PROPERTIES VERSION 1.0.0) install(TARGETS Library EXPORT LibraryConfig) install(FILES Library.H DESTINATION include/Library) install(EXPORT LibraryConfig DESTINATION lib/cmake/Library) include(CMakePackageConfigHelpers) write_basic_package_version_file( ${PROJECT_BINARY_DIR}/LibraryConfigVersion.cmake VERSION 1.0.0 COMPATIBILITY SameMajorVersion ) install( FILES ${PROJECT_BINARY_DIR}/LibraryConfigVersion.cmake DESTINATION lib/cmake/Library ) Possible Solution I just apply version to the target name in form of ${PROJECT_NAME}-${PROJECT_VERSION}: I changed the export name: install(TARGETS Library EXPORT Library-1.0.0Config) install( EXPORT Library-1.0.0Config DESTINATION lib/cmake/Library-1.0.0Config ) And the INSTALL_INTERFACE for the include directories: target_include_directories(Library PUBLIC $<INSTALL_INTERFACE:include/Library-1.0.0> ) And the OUTPUT_NAME property of the target: set_target_properties(Library PROPERTIES OUTPUT_NAME Library-1.0.0 ) The result: file(WRITE Library.H "void Function();") file(WRITE Library.C "void Function() {}") add_library(Library SHARED Library.H Library.C) target_include_directories(Library PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}> $<INSTALL_INTERFACE:include/Library-1.0.0> ) set_target_properties(Library PROPERTIES OUTPUT_NAME Library-1.0.0) install(TARGETS Library EXPORT Library-1.0.0Config) install(FILES Library.H DESTINATION include/Library-1.0.0) install(EXPORT Library-1.0.0Config DESTINATION lib/cmake/Library-1.0.0) But with this approach, I always have to specify the version: find_package(Target-1.0.0 REQUIRED).
You are working in Config Mode of find_package, so the search mode according to the documents is like: <prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/ (U) <prefix>/(lib/<arch>|lib*|share)/<name>*/ (U) <prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (U) So you need to: Change the INSTALL_INTERFACE to point to a directory tagged with the library version(with whatever policy you prefer for version matching). Install your package's config files in a directory tagged with the library version(again with your preferred version matching policy). Provide a version config file and installed it beside the config files. A version config file is required for version matching. Change the OUTPUT_NAME property of the target to a name tagged with the version. If you instead set VERSION or SOVERSION property, the result will be a non-version tagged symlink to the tagged one. It will be overridden by other versions and It could cause problems if anyone used it without using CMake. So your sample with above modifications could be like: file(WRITE Library.H "void Function();") file(WRITE Library.C "void Function() {}") add_library(Library SHARED Library.H Library.C) target_include_directories(Library PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}> $<INSTALL_INTERFACE:include/Library-1.0.0> ) set_target_properties(Library PROPERTIES OUTPUT_NAME 1.0.0) install(TARGETS Library EXPORT LibraryConfig) install(FILES Library.H DESTINATION include/Library-1.0.0) install(EXPORT LibraryConfig DESTINATION lib/cmake/Library-1.0.0) include(CMakePackageConfigHelpers) write_basic_package_version_file( ${PROJECT_BINARY_DIR}/LibraryConfigVersion.cmake VERSION 1.0.0 COMPATIBILITY SameMajorVersion ) install( FILES ${PROJECT_BINARY_DIR}/LibraryConfigVersion.cmake DESTINATION lib/cmake/Library-1.0.0 ) With this approach doesn't matter how many version of the library is installed using the same prefix path, the only important thing is the EXACT version name. And the usage could be requesting for a version find_package(Target 1.0.0) or the last available version find_package(Target)(based on the search policy and the version matching policy).
73,016,267
73,016,419
Casting structs with non-aggregate members
I am receiving an segmentation fault (SIGSEGV) when I try to reinterpret_cast a struct that contains an vector. The following code does not make sense on its own, but shows an minimal working (failing) example. // compiler: g++ -std=c++17 struct Table { std::vector<int> ids; }; std::vector<std::byte> storage; // put that table into the storage Table table = {.ids = {3, 5}}; auto convert = [](Table x){ return reinterpret_cast<std::byte*>(&x); }; std::byte* bytes = convert(table); storage.insert(storage.end(), bytes, bytes + sizeof(Table)); // ... // get that table back from the storage Table& tableau = *reinterpret_cast<Table*>(&storage.front()); assert(tableau.ids[0] == 3); assert(tableau.ids[1] == 5); The code works fine if I inline the convert function, so my guess is that some underlying memory is deleted. The convert function makes a local copy of the table and after leaving the function, the destructor for the local copy's ids vector is called. Recasting just returns the vector, but the ids are already deleted. So here are my questions: Why does the segmentation fault happen? (Is my guess correct?) How could I resolve this issue? Thanks in advance :D
I see at least three reasons for undefined behavior in the shown code, that fatally undermines what the shown code is attempting to do. One or some combination of the following reasons is responsible for your observed crash. struct Table { std::vector<int> ids; }; Reason number 1 is that this is not a trivially copyable object, so any attempt to copy it byte by byte, as the shown code attempts to do, results in undefined behavior. storage.insert(storage.end(), bytes, bytes + sizeof(Table)); Reason number 2 is that sizeof() is a compile time constant. You might be unaware that the sizeof of this Table object is always the same, whether or not its vector is empty or contains the first billion digits of π. The attempt here to copy the whole object into the byte buffer, this way, therefore fails for this fundamental reason. auto convert = [](Table x){ return reinterpret_cast<std::byte*>(&x); }; Reason number 3 is that this lambda, for all practical purposes, is the same as any other function with respect to its parameters: its x parameter goes out of scope and gets destroyed as soon as this function returns. When a function receives a parameter, that parameter is just like a local object in the function, and is a copy of whatever the caller passed to it, and like all other local objects in the function it gets destroyed when the function returns. This function ends up returning a pointer to a destroyed object, and subsequent usage of this pointer also becomes undefined behavior. In summary, what the shown code is attempting to do is, unfortunately, going against multiple core fundamentals of C++, and manifests in a crash for one or some combination of these reasons; C++ simply does not work this way. The code works fine if I inline the convert function If, by trial and error, you come up with some combination of compiler options, or cosmetic tweaks, that avoids a crash, for some miraculous reason, it doesn't fix any of the underlying problems and, at some point later down the road you'll get a crash anyway, or the code will fail to work correctly. Guaranteed. How could I resolve this issue? The only way for you to resolve this issue is, well, not do any of this. You also indicated that what you're trying to do is just "store multiple vectors of different types in the same container". This happens to be what std::variant can easily handle, safely, so you'll want to look into that.
73,017,117
73,017,238
How to disallow increment operator when operated multiple times on a object?
How do I overload the increment operator so that this code becomes invalid - Point p(2, 3); ++++p; while allowing the following - Point p(2, 3), a(0, 0), b(1, 4); a = ++p + b; Like in C this would be invalid - int a = 2; ++++a;
One way you could do this is to make your operator++() return a const reference. That would prevent subsequent modification of the returned value, as in a 'chained' ++++p;. Here's an outline version that also includes the required binary addition operator, implemented as a non-member function (as is normal): #include <iostream> class Point { public: int x{ 0 }, y{ 0 }; Point(int a, int b) : x{ a }, y{ b } {} const Point& operator++() { ++x; ++y; return *this; } Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } }; inline Point operator+(Point lhs, const Point& rhs) { lhs += rhs; return lhs; } int main() { Point p(2, 3), a(0, 0), b(1, 4); a = ++p + b; // OK: The result of the ++p is passed by value (i.e. a copy) std::cout << a.x << " " << a.y << "\n"; // ++++a; // error C2678: binary '++': no operator found which takes a left-hand operand of type 'const Point' return 0; }
73,017,855
73,017,935
add "std::mutex" as a member field into an only-movable class without manually code "move constructor" (std::unique_ptr<> is ugly)
By design, class B is uncopiable but movable. Recently, I enjoy that B has automatically-generated move constructor and move assignment operator. Now, I add std::mutex to class B. The problem is that std::mutex can't be moved. #include <iostream> #include <string> #include <vector> #include <mutex> class C{ public: C(){} public: C(C&& c2){ } public: C& operator=(C&& c2){ return *this; } //: by design, I don't allow copy, can only move }; class B{public: int a=0; C c; //------ 10+ trivial fields --- //private: std::mutex mutexx; //<=== uncomment = uncompilable }; int main(){ B b1; B b2; b1=std::move(b2); } Is there a solution to make it compile? My poor workaround 1 (manual) Manually create 2 move functions. class B{public: int a=0; C c; //------ 10+ trivial fields --- private: std::mutex mutexx; public: B(B&& b2){ this->c=std::move(b2.c); //--- copy other trivial fields (long and hard to maintain) -- //:: intentionally omit move/copy of mutex } public: B& operator=(B&& b2){ ... } }; This workaround creates the effect that I want. My poor workaround 2 (unique_ptr) Use std::unique_ptr<std::mutex>, but there are 3 minor disadvantages :- Very ugly Add a bit of extra heap & cpu cost. The cost might be little, but I will resent it forever. I also need to refactor some of my code from mutexx.lock() to mutexx->lock() Edit : My poor workaround 3 (encapsulate mutex) (Add after get the first answer) Encapsulate std::mutex into a new class, and create 2 move functions that do nothing. If future reader may use this approach, beware that my question itself is questionable. Thank "ALX23z" and "j6t" for warning.
I enjoy that B has automatically-generated move constructor Why don't rename class B and use it as a base class? #include <iostream> #include <string> #include <vector> #include <mutex> class C{ public: C(){} public: C(C&& c2){ } public: C& operator=(C&& c2){ return *this; } //: by design, I don't allow copy, can only move }; class B1{public: int a=0; C c; //------ 10+ trivial fields --- }; class B : public B1 { public: B& operator=(B&& b2){ return *this; } private: std::mutex mutexx; }; int main(){ B b1; B b2; b1=std::move(b2); }
73,018,270
73,047,050
C++ Google Type-Parameterized and Value-Parameterized Tests combined?
I would like to be able to parameterize my tests for various types through the following code snippet: template <typename T> class MyTestSuite : public testing::TestWithParam<tuple<T, vector<vector<T>>, T, T>> { public: MyTestSuite() { _var = get<0>(GetParam()); // and the rest of the test params } protected: T _var; }; TYPED_TEST_SUITE_P(MyTestSuite); TYPED_TEST_P(MyTestSuite, MyTests) { ASSERT_EQ(this->_expected, this->DoSomething(this->_var)); } REGISTER_TYPED_TEST_SUITE_P(MyTestSuite, MyTests); using MyTypes = ::testing::Types<size_t>; INSTANTIATE_TYPED_TEST_SUITE_P( MyGroup, MyTestSuite, ::testing::Combine( ::testing::Values(4, vector<vector<size_t>>{{1, 2}, {1, 3}, {3, 4}}, 1, 1), ::testing::Values(10, vector<vector<size_t>>{{1, 2}, {1, 3}, {3, 4}}, 1, 2), ::testing::Values(20, vector<vector<size_t>>{{1, 2}, {1, 3}, {3, 4}}, 1, 4))); and bump into the following compilation error: error: there are no arguments to ‘GetParam’ that depend on a template parameter, so a declaration of ‘GetParam’ must be available [-fpermissive] [build] 284 | _var = get<0>(GetParam()); This post has been quite some time: Google Test: Is there a way to combine a test which is both type parameterized and value parameterized? Is it still not possible to kill these 2 birds with one stone, judging from the compilation error above?
Decided to use a template base test fixture class with parameterized tests: template <typename T> class MyTestFixture { protected: void SetUp(...) {} T _var; }; class MyTestSuite1 : public MyTestFixture<size_t>, public testing::TestWithParam<tuple<size_t, vector<vector<size_t>>, size_t, size_t>> { public: void SetUp() override { MyTestFixture::SetUp(get<0>(GetParam())); // and the rest of the test params } }; class MyTestSuite2 : public MyTestFixture<long>, public testing::TestWithParam<tuple<size_t, vector<vector<long>>, size_t, long>> { public: void SetUp() override { MyTestFixture::SetUp(get<0>(GetParam())); // and the rest of the test params } }; TEST_P(MyTestSuite1, MyTests1) { ASSERT_EQ(this->_expected, this->DoSomething(this->_var)); } TEST_P(MyTestSuite2, MyTests2) { ASSERT_EQ(this->_expected, this->DoSomething(this->_var)); } INSTANTIATE_TEST_SUITE_P( MyGroup, MyTestSuite1, ::testing::Values(make_tuple<size_t, ...>(4, vector<vector<size_t>>{{1, 2}, {1, 3}, {3, 4}}, 1, 1), make_tuple<size_t, ...>(10, vector<vector<size_t>>{{1, 2}, {1, 3}, {3, 4}}, 1, 2), make_tuple<size_t, ...>(20, vector<vector<size_t>>{{1, 2}, {1, 3}, {3, 4}}, 1, 4)));
73,018,299
73,018,592
How do I convert a regular expression match into a "struct"?
Regular Expression: ([0-9]*)|([0-9]*\.[0-9]*) String: word1 word2 0:12:13.23456 ... example string match: 0,12,13.23456 Requirement: convert to a struct -> struct Duration { unsigned int hours; unsigned int minutes; double seconds; }; Current matcher: Duration duration; std::regex regex("([0-9]*):([0-9]*):([0-9]*.[0-9]*)"); auto begin = std::sregex_iterator(data.begin(), data.end(), regex); // data is an std::string instance auto end = std::sregex_iterator(); for (auto it = begin; it != end; it++) { auto match = *it; // how to cycle through the data values of the instance of Duration? }
I recommend using std::regex_search instead of iterators and loops. Then you get a match result which you can index to get the separate matches. Once you have the separate matches, you can call std::stoul or std::stod to convert the matched strings to their numeric variants. Perhaps something like this: #include <iostream> #include <string> #include <regex> struct Duration { unsigned int hours; unsigned int minutes; double seconds; }; int main() { std::string input = "word1 word2 0:12:13.23456"; std::regex regex("([0-9]*):([0-9]*):([0-9]*.[0-9]*)"); std::smatch matches; std::regex_search(input, matches, regex); Duration duration = { static_cast<unsigned int>(std::stoul(matches[1])), static_cast<unsigned int>(std::stoul(matches[2])), std::stod(matches[3]) }; std::cout << "Duration = { " << duration.hours << ", " << duration.minutes << ", " << duration.seconds << " }\n"; } [Note: There's no error checking, or checking the amount of actual matches in matches, which should really be done in a "real" program]
73,018,590
73,021,254
Program crash when using boost::iter_split?
my main function in vs2022-v143 and boost-v1.79: struct func_info { func_info(const std::wstring& _var, const std::wstring& _name) :var(_var), func_name(_name) { } std::wstring var; std::wstring func_name; std::vector<std::wstring> values; }; void main_function(){ for (unsigned i = 0; i < 1; ++i) { func_info _func{ L"zz1",std::wstring{}}; get_split(L"abcxyz(c2,c3)", _func.values); } // <-- program crash } //myfunc.h void get_split(const wstring& input, std::vector<std::wstring>& result){ ... boost::iter_split(result, input, boost::algorithm::first_finder(L",")); } I got the expected result but my problem is program crashes when exiting or next the loop is there a problem with _func.values? I don't know where the cause is. _CONSTEXPR20 void _Container_base12::_Orphan_all_unlocked_v3() noexcept { if (!_Myproxy) { // no proxy, already done return; } // proxy allocated, drain it for (auto& _Pnext = _Myproxy->_Myfirstiter; _Pnext; _Pnext = _Pnext->_Mynextiter) { // TRANSITION, VSO-1269037 _Pnext->_Myproxy = nullptr; } _Myproxy->_Myfirstiter = nullptr; }
You have Undefined Behavior elsewhere. The problem is not in the code shown (modulo obvious typos): Live On MSVC as well as GCC with ASAN: #include <boost/algorithm/string.hpp> #include <iomanip> #include <iostream> #include <string> #include <vector> // myfunc.h void get_split(const std::wstring& input, std::vector<std::wstring>& result) { // ... boost::iter_split(result, input, boost::algorithm::first_finder(L",")); } struct func_info { func_info(std::wstring _var, std::wstring _name) : variable(std::move(_var)), func_name(std::move(_name)) {} std::wstring variable; std::wstring func_name; std::vector<std::wstring> values; }; int main() { for (unsigned i = 0; i < 10; ++i) { func_info _func{L"zz1", {}}; get_split(L"abcxyz(c2,c3)", _func.values); for (auto& s : _func.values) { std::wcout << L" " << std::quoted(s); } std::wcout << L"\n"; } } Prints "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)" "abcxyz(c2" "c3)"
73,020,562
73,021,029
Extract all declared function names from header into boost.preprocessor
I have a C header file containing various declarations of functions, enums, structs, etc, and I hope to extract all declared function names into a boost.preprocessor data structure for iteration, using only the C preprocessor. All function declarations have two fixed distinct macros around the return type, something like, // my_header.h FOO int * BAR f(long, double); FOO void BAR g(); My goal is to somehow transform it into one of the above linked boost.preprocessor types, such as (f, g) or (f)(g). I believe it is possible by cleverly defining FOO and BAR, but have not succeeded after trying to play around with boost.preprocessor and P99. I believe this task can only be done with the preprocessor as, As a hard requirement, I need to stringify the function names as string literals later when iterating the list, so runtime string manipulation or existing C++ static reflection frameworks with template magic are out AFAIK. While it can be done with the help of other tools, they are either fragile (awk or grep as ad-hoc parsers) or overly complex for the task (LLVM/GCC plugin for something robust). It is also a motivation to avoid external dependencies other than those strictly necessary i.e. a conforming C compiler.
I don't think this is going to work, due to limitations on where parentheses and commas need to occur. What you can do, though, is the opposite. You could make a Boost.PP sequence that contains the signatures in some structured form and use it to generate the declarations as you showed them. In the end, you have the representation you want as well as the compiler's view of the declarations.
73,020,842
73,021,515
c++ OpenSSL, writing a public key in to a file and reading it from same file does not return correct key
I have generated an 256 bytes RSA keypair and I am now trying to write the public key into a PEM file. I am using this code: // Put the public key inside a pem file ofstream file("temppubkey.pem"); file.close(); FILE * pemFile = fopen("temppubkey.pem", "w"); PEM_write_PUBKEY(pemFile, servTempPubKey); fclose(pemFile); // Retreive key from pem file as a test FILE * pem = fopen("temppubkey.pem", "r"); EVP_PKEY * key = EVP_PKEY_new(); PEM_read_PUBKEY(pem, &key, NULL, NULL); fclose(pem); // TEST cout << "Pub key:\n"; BIO_dump_fp(stdout, (const char *) servTempPubKey, tempKeySize); cout << "test key:\n"; BIO_dump_fp(stdout, (const char *) key, tempKeySize); The result I get is usually good for 16 to 32 bytes but I always end up with a different key that I had to start with. Does anyone has any hints on what I am doing wrong here ? EDIT Here is the file written -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmHKT/jXk5CwCVheWcWE2 DrIHml4EsO/IQ5/sDdbrzakryB4YLmu+z90ShE5sYKixHq2oDrjnDbrTL2RYJSrC xQmUOztztFXqvh6yWaKlA0la/ehsCQSW8o2OONu84d9Pr3ZgQz4gTdjIeKqF96qm hhyLTrVA5qQD0aUgJRTxSbnESQBBvipdNFzGLT/I0kMK3lCbDfANDuhNL8iX8jp8 KNd6KqrOf3FfzYOII0uIvwVO0OCSm4rXCtIK2euskmCOEVYQZEbWgnzVf/Uos/9J bIEDKFks9pcia7uAhlPA/2CZjClQjHde/PcCFq7hRKwn4okoiM5zB9wl688uL/iX LQIDAQAB -----END PUBLIC KEY----- It seems relatively correct from my experience pem files usually look like this.
BIO_dump_fp dumps raw binary bytes from a structure into the file. Doing this kind of comparison, this way, only works if EVP_PKEY points to a trivial type, with no padding. OpenSSL's documentation makes no guarantees, whatsoever, what EVP_PKEY's underlying object is. In fact, the definition of its contents is completely hidden from OpenSSL's public header files. Here's the verbatim definition of EVP_PKEY taken from OpenSSL's types.h header file: typedef struct evp_pkey_st EVP_PKEY; The End. No definition of what evp_pkey_st is, anywhere. It'll remain an unsolveable mystery, forever. It's considered to be private information, not even accessible from the public header files. You cannot make any assumption, whatsoever, what it's pointing to. It is an opaque handle, a pointer to some object whose allocation and deallocation is managed by OpenSSL, and you have no direct access to it, whatsoever. It is unclear where the shown code obtains tempKeySize from, or what it means, but it is unlikely to be the correct size of the underlying structure, of what the pointer is pointing to. OpenSSL does not make this information available, either. In short, dumping some arbitrary number of bytes from wherever a particular EVP_PKEY points to will not accomplish anything useful, and is likely to be undefined behavior, anyway.