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
74,402,231
74,402,348
summation of elements of a 2D vector into a 1D vector. C++
Help me please. Tell me how to sum each vector in a two-dimensional vector and write the result into a one-dimensional vector. On C++. Input: std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; Required Output: b = { 9, 12 } I found how to sum all the elements in a 2D vector, but I don't know how to sum the vectors in an existing 2D vector and write the result to a 1D vector #include <iostream> #include <vector> int main() { std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; std::vector<double> b; std::vector<int> v; int sum = 0; for (int i = 0; i < a.size(); i++) for (int j = 0; j < a[i].size(); j++) { sum += a[i][j]; } std::cout << sum; return 0; }
From your example I assume that in the sums vector that you require, element in index i, is the sum of all elements in index i in the vectors in a. This requires that all elements in a have the same size. You can do it in the following way: Traverse the elements in a. For each element: traverse the element (which is a vector itself) and sum element i into the ith bin of the output vector. Something like: #include <iostream> #include <vector> #include <assert.h> int main() { std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; size_t num_of_sums = a[0].size(); // we assume all elements in a have the same size std::vector<double> sums(num_of_sums); for (auto const & v : a) { assert(v.size() == num_of_sums); for (int j = 0; j < num_of_sums; j++) { sums[j] += v[j]; } } for (auto d : sums) { std::cout << d << ", "; } std::cout << std::endl; return 0; } Output: 9, 12, Note that my sums vector contains doubles, like your input data (unlike your sum which is an int and seems improper to sum double values).
74,402,911
74,402,978
error use of deleted function when trying to pass rvalue to a tuple
Original context: I am trying to pass a tuple of (object, expected_value_of_some_property) to a test function I created a simple class to reproduce the error I am facing: template <typename T> class Vector { private: size_t m_size; std::unique_ptr<std::vector<int>> m_vector; public: Vector(); Vector(const Vector<int>&); ~Vector() = default; void push_back(T); T get(int) const; size_t size() const; }; template <typename T> Vector<T>::Vector() :m_size(0), m_vector(new std::vector<T>) {} template <typename T> Vector<T>::Vector(const Vector<int>& v) :m_size(v.size()), m_vector(new std::vector<T>) { for (size_t i = 0; i < v.size(); i++) { this->push_back(v.get(i)); } } template <typename T> void Vector<T>::push_back(T value) { m_vector->push_back(value); m_size ++; } template <typename T> T Vector<T>::get(int index) const { return m_vector->operator[](index); } template <typename T> size_t Vector<T>::size() const { return m_size; } The error is triggered when trying to produce a tuple of Vector object and an int somewhere in a test code: int main(int argc, char const *argv[]) { std::tuple<Vector<int>, int> vector_test; vector_test = std::make_tuple(Vector<int>{}, 0); int size = std::get<0>(vector_test); Vector<int> vector = std::get<1>(vector_test); // .. test code return 0; } Output: error: use of deleted function ‘std::tuple<Vector<int>, int>& std::tuple<Vector<int>, int>::operator=(const std::tuple<Vector<int>, int>&)’ 20 | vector_test = std::make_tuple(Vector<int>{}, 0); | ^ ^ What am I doing wrong here?
Since your Vector class has a unique_ptr member, that means your class itself has the copy-assignment implicitly deleted. Therefore this assignment will fail std::tuple<Vector<int>, int> vector_test; vector_test = std::make_tuple(Vector<int>{}, 0); // <--- this Instead you can just directly initialize in one step std::tuple<Vector<int>, int> vector_test = std::make_tuple(Vector<int>{}, 0);
74,403,740
74,403,788
How to accept empty input in C++
Accepting user empty input and passing default value from the constructor I just start learning C++. Now I was trying creating a simple requestion header. What I was expected is the "ABC Industries" should be used as a default value for the purchaser name and "XYZ Supplier" should be used as a default for the vendor name. I created a default constructor and a param constructor. Here is my code: class Requisition{ private: string purchaser, vendor; public: Requisition() :purchaser("ABC Industries"),vendor("XYZ Supplier"){} Requisition(string pname, string vname) :purchaser(pname),vendor(vname){} void getStaffInput(){ cout << "Enter a purchaser name: "; cin>>purchaser; cout << "Enter a vendor name: "; cin>>vendor; } void printHeader(){ cout << "\n********************************************************\nPurchaser: " << purchaser <<"\nVendor: "<<vendor <<"\n********************************************************"<<endl; } }; Here is my question: How can I accept user inputting a empty string (user direct press enter or spacing) because in C++ will force to input something to continue. If user doesn't key in any data, or just inputting either one of the data (purchaser or vendor), How can I pass the default value to the print function? int main(){ Requisition req; req.getStaffInput(); req.printHeader(); } My program output is forcing the user to input something (can't be blank and spacing), the program should accepting those blank or spacing input and get the default value from the default constructor and display it. Thanks.
cin into a string will read, effectively, one token. The exact rules are complicated, but it basically pulls content until a space or newline. If you don't input any content, it waits until there's something. You're looking for getline, which reads until the next newline and returns whatever it finds, even if what it finds is nothing at all. std::getline(std::cin, purchaser);
74,403,780
74,404,368
Reading from file with special characters into a string
I have an c++ program that should read a text from a file named "Pontaje.txt" and store it into a string. The problem is that in that file is an special character and the program can't use it properly. Pontaje.txt [604] Dumy | 17501 — Today at 12:01 AM Note that "—"(is a special character) is not "-"(from the keyboard) main.cpp #include <iostream> #include <string> #include <fstream> int main() { std::ifstream test("Pontaje.txt"); std::string test2; std::getline(test, test2); std::cout << test2; } Output: ∩╗┐[604] Dumy | 17501 ΓÇö Today at 12:01 AM How can I assign in test2 that line properly? Note that I've tried using std::wifstream , std::wstring and std::wcout but i get the same result
ΓÇö is a tell-tale sign: it's three characters instead of one. That happens when the input is encoded using UTF-8 (a multi-byte character set) but the output is done with a single-byte character set. I can't directly eyeball what character set contains all of ΓÇö, though. IOW the problem is not the input or the output, but the assumption that they're using the same character set. And std::string makes no assumptions at all about character sets.
74,403,792
74,403,839
Code::Blocks builder error: undefined reference to `WinMain'
How to fix the following error message when trying to compile C++ console application project on Code::Blocks? undefined reference to `WinMain' All other questions on Stack Overflow are about "WinMain@16", which is not the case here.
WinMain is linked to in windows when you want to create a windows application. https://learn.microsoft.com/en-us/windows/win32/learnwin32/winmain--the-application-entry-point For the complier to look for the main function you will have to change at the linker stage that it is a console application and not a windowed one. Or you might just need to restart CodeBlocks: C++ undefined reference to WinMain@16 (Code::Blocks) Or you might have just have deleted main() ;)
74,403,919
74,404,000
C++ - issues with writing sorting function
I have a problem with sorting function. I have following struct: struct Object { int value, height; Object(int v, int h) { this->value = v; this->height = h; } }; I am storing vector of this objects: std::vector<Object> v And I'd like to sort it such that if the height is greater than some i then it should go at the end, and if it is less or equal sort by value. I've tried this before: // some value int i = 4; std::sort(v.begin(), v.end(), [ & ](Object a, Object b) { if (b.height > i) { return false; } if (a.height > i) { return false; } return a.value > b.value; }); But it does not seem to work.. When I have these elements: std::vector<Object> v = {{3, 10}, {5, 2}, {3, 2}, {2, 10}, {2, 1000000000}}; and i = 2 When I print values of v, after sorting I see that they appear in the exact same order And I'd like them in the following order: {{5, 2}, {3, 2}, {3, 10}, {2, 10}, {2, 1000000000}}
It seems you want something like: std::sort(v.begin(), v.end(), [ & ](const Object& lhs, const Object& rhs) { return std::make_pair(lhs.height > i, rhs.value) < std::make_pair(rhs.height > i, lhs.value); });
74,404,106
74,404,685
pointer to pointer of vector yields 3D vector?
I have been looking through some legacy code and found this little snippet: std::vector<int>** grid = new std::vector<int>*[10]; for (int k = 0; k < 10; k++) grid[k] = new std::vector<int>[10]; And then later on, the original developer is calling this command here: grid [i][j].push_back(temp); I was under the impression that the [i][j] would return the value in the nested vector, but by using push_back implies that there is a pointer to a vector at that location? I'm confused where this third vector arises from. Also, is there a better approach? would a triple nested vector also achieve the same results as the above code? Thanks in advance!
grid[i][j] is a reference to a std::vector<int>. Rewriting things may clarify what you have. [Demo] #include <fmt/ranges.h> #include <vector> int main() { using line_t = std::vector<int>; // line is a vector of ints using matrix_t = line_t*; // matrix is an array of lines using grid_t = matrix_t*; // grid is an array of matrices // Same as: grid_t grid{ new std::vector<int>*[3] }; grid_t grid{ new matrix_t[3] }; int v{}; for (int k = 0; k < 3; k++) { // we walk each matrix auto& matrix{ grid[k] }; matrix = new line_t[3]; for (int l = 0; l < 3; l++, v++) { // we walk each line // Same as: auto& line{ grid[k][l] }; auto& line{ matrix[l] }; line = std::vector<int>(3, v); } } fmt::print("Grid\n\n"); for (int k{0}; k < 3; k++) { fmt::print("Matrix {}\n", k); auto& matrix{ grid[k] }; for (int l{0}; l < 3; l++) { auto& line{ matrix[l] }; fmt::print("{}\n", line); } fmt::print("\n"); } } // Outputs: // // Grid // // Matrix 0 // [0, 0, 0] // [1, 1, 1] // [2, 2, 2] // // Matrix 1 // [3, 3, 3] // [4, 4, 4] // [5, 5, 5] // // Matrix 2 // [6, 6, 6] // [7, 7, 7] // [8, 8, 8] Using std::vectors instead of built-in arrays would simplify things a lot. [Demo] #include <algorithm> // fill #include <fmt/ranges.h> #include <vector> int main() { using line_t = std::vector<int>; // line is a vector of ints using matrix_t = std::vector<line_t>; // matrix is a vector of lines using grid_t = std::vector<matrix_t>; // grid is a vector of matrices grid_t grid(3, matrix_t(3, line_t(3))); int v{}; for (auto& matrix : grid) { for (auto& line : matrix) { std::ranges::fill(line, v++); } } fmt::print("Grid\n\n"); for (int k{0}; k < 3; k++) { fmt::print("Matrix {}\n", k); fmt::print("{}\n\n", fmt::join(grid[k], "\n")); } }
74,404,314
74,404,846
Is there a way to express fraction in MOSEK c++?
I am trying to make objective function by MOSEK c++. But there is a problem. When I try to make function like below, there is no dividing function in MOSEK. a is variable and b,c are parameter. I made a (numerator) and b+ac (denominator) respectivley, but I don't know how to divide them. So I made code like below. Variable::t a_numerator = M->variable(); Parameter::t b_denominator_1 = M->parameter(); Parameter::t c_denominator_2 = M->parameter(); Expression::t b_add_ac = Expr::add(b_denominator_1, Expr::mul(a_numerator, c_denominator_2); Is there any way to express faction in MOSEK?
You are using Fusion which means you have to state the problem in conic form. You can read about that in https://docs.mosek.com/modeling-cookbook/index.html But I suggest you first consider whether the function a/(b+a*c) is convex. (I kind of doubt that.) If it is not convex, there is no hope to express it in conic form. The plot https://www.wolframalpha.com/input?i=x%2F%281%2Bx%29 shows that the function might be nasty. Btw this https://en.wikipedia.org/wiki/Linear-fractional_programming might be useful.
74,404,545
74,404,599
I don't understand the logic of a working program class
All, being brief as possible, I’m working on an exercise from C++ Primer Plus Sixth Ed. by Stephen Prata. Chapt 10 Ex 6 for those playing along at home. I wasn’t sure what the exercise was asking. I found someone online who had done the exercises. I thought seeing the program in action, I’d understand the requirement and recreate my own. The program I downloaded works perfectly. My lack of understanding of why is works is my issue. I’m hoping someone here can clear up what I’m not understanding. MOVE.H class Move{ private: double x; double y; public: Move(double a = 0, double b = 0); // sets x, y to a, b void showmove() const; Move add(const Move & m) const; void reset(double a = 0, double b = 0); // resets x,y to a, b }; MOVE.CPP (there are other class methods that deal with display and reset. I excluded them to conserve space.) Move::Move(double a, double b) { x = a; y = b;} Move Move::add(const Move & m) const { double m_x, m_y; m_x = this-\>x + m.x; m_y = this-\>y + m.y; Move newMove(m_x, m_y); return newMove; } MAIN.CPP (There of other line items for display etc.) Move move1; //Nothing sent so defaults to (x=0,y=0)per the constructor Move move2(1.5, 2.5); // constructor set move2 x =1.5 & y=2.5 Move move3(1.5, 2.1); // constructor set move3 x=1.5 & y=2.1 Move move4(move2.add(move3)); // this is where my confusion lies. When creating move4, I expected the constructor to look for nothing being sent or a combination of 2 doubles. Move2::add returns a reference or address of a newly created Move class called newMove. How does the constructor of move4 know to extract the x and y from newMove of class move2. The program works as expected. Move4 X=3 and Y=4.6. I’m obviously missing something. One of the downsides to learning without a teacher / tutor. Thanks.
How does the constructor of move4 know to extract the x and y from newMove of class move2. Your class does not explicitly define or delete its copy constructor, and all of its fields can be copied, so you get a copy constructor for free. Effectively, you get a constructor that does Move(const Move& that) : x(that.x), y(that.y) {} but the compiler provides it for you. You can always provide a Move(const Move&) function yourself which will replace the compiler-generated one. And if you don't want one at all (common in smart pointer types that uniquely own a resource), you can delete it Move(const Move& that) = delete;
74,404,977
74,405,543
Why wouldn't a C++ compiler implement <cstdint>?
I am porting some C++ code to SHArC processor, and I noticed the SHArC C++ compiler doesn't implement <cstdint>. What's the reason for this, and how do I port numerous #include <cstdint> from the original code?
There's nothing tricky about <cstdint>, a valid version is as follows: #pragma once /* or include-guard macro */ #include <stdint.h> namespace std { typedef ::uint64_t uint64_t; typedef ::uint64_fast_t uint64_fast_t; typedef ::uint64_least_t uint64_least_t; typedef ::int64_t int64_t; /* similar for other stdint types */ }
74,405,029
74,405,995
How to use RtAudio as a CMake dependency
I am trying to use RtAudio in my project. I installed it by executing : git clone ... cmake -B target -D CMAKE_PREFIX_PATH=$HOME/.local cmake --build target cmake --install target PKG_CONFIG_PATH=$HOME/.local/lib/pkgconfig pkg-config --cflags --libs rtaudio returns -pthread -I$HOME/.local/include/rtaudio -D__UNIX_JACK__ -D__LINUX_ALSA__ -D__LINUX_PULSE__ -D_REENTRANT -L$HOME/.local/lib -lrtaudio But when I'm using the following CMakeLists.txt file project(test_rtaudio) set(CMAKE_CXX_STANDARD 17) set(CMAKE_FIND_DEBUG_MODE ON) add_executable(${PROJECT_NAME} main.cpp) find_package(RtAudio REQUIRED) message(STATUS "RtAudio include dirs : " ${RtAudio_INCLUDE_DIRS}) message(STATUS "RtAudio lib dirs :" ${RtAudio_LIBS}) include_directories(${RtAudio_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} ${RtAudio_LIBS}) The RtAudioConfig.cmake is found but there is no INCLUDE_DIRS or LIBS CMake Debug Log at $HOME/.local/share/rtaudio/RtAudioConfig.cmake:26 (find_package): find_package considered the following paths for FindThreads.cmake: The file was found at /usr/share/cmake/Modules/FindThreads.cmake Call Stack (most recent call first): CMakeLists.txt:8 (find_package) CMake Debug Log at CMakeLists.txt:8 (find_package): find_package considered the following paths for FindRtAudio.cmake: /usr/share/cmake/Modules/FindRtAudio.cmake The file was not found. $HOME/.local/share/rtaudio/RtAudioConfig.cmake -- RtAudio include dirs : -- RtAudio lib dirs : -- Configuring done -- Generating done -- Build files have been written to: $HOME/Documents/project/sandbox/rtaudio/target CMake actually find RtAudioConfig.cmake while it is looking for pthread lib. There is no error, but as there is no include or lib files, as soon as I am trying to compile my project : cmake --build target FAILED: CMakeFiles/test_rtaudio.dir/main.o /usr/bin/c++ -std=gnu++17 -MD -MT CMakeFiles/test_rtaudio.dir/main.o -MF CMakeFiles/test_rtaudio.dir/main.o.d -o CMakeFiles/test_rtaudio.dir/main.o -c $HOME/Documents/project/sandbox/rtaudio/main.cpp $HOME/Documents/project/sandbox/rtaudio/main.cpp:47:10: erreur fatale: RtAudio.h : Aucun fichier ou dossier de ce type 47 | #include <RtAudio.h> | ^~~~~~~~~~~ ninja: build stopped: subcommand failed. RtAudio.h is not found. NB : I have already tried to install the lib at the default location and the same error occurs. I am not a professional CMake user and I can't determine if there is a miss configuration in my project or a lack of configuration while building or installing RtAudio. If somebody have a solution or any idea
The call find_package(RtAudio) actually creates the IMPORTED target RtAudio::rtaudio, so you could simply link with that target: find_package(RtAudio REQUIRED) ... target_link_libraries(${PROJECT_NAME} RtAudio::rtaudio) Not sure why they don't mention that in their documentation. Alternatively, it is possible to use pkg-config for extract properties of the package: find_package(PkgConfig REQUIRED) pkg_check_modules(RtAudio REQUIRED IMPORTED_TARGET rtaudio) ... target_link_libraries(${PROJECT_NAME} PkgConfig::RtAudio) (More information about using pkg-config in CMake could be found in that question.
74,405,108
74,405,208
Compile-time check for existence of a template specialization of a function using C++20 requires expression
I am developing a sort of event system where the event listeners are determined at compile-time. To achieve this, I need a function which can tell me whether the parameter class T implements a specific specialization of the OnEvent() function. My current attempt uses a C++20 requires expression: template<class T> class ScriptComponent { static_assert(std::is_base_of_v<Script, T>, "T must derive from Script!"); private: T m_ScriptInstance; public: // Should return true if t.OnEvent<E>(e) can compile, false otherwise. template<typename E> constexpr static bool ImplementsEventFunction() { constexpr bool isImplemented = requires(const T& t, const E& e) { t.OnEvent<E>(e); }; return isImplemented; } }; Example of a class which can listen to events: class SomeScript : public Script { public: // delete any non-specialized templates template<typename E> void OnEvent(const E&) = delete; // the template specialization I want to check for template<> void OnEvent<SomeEvent>(const SomeEvent& e) { // do stuff } }; Usage of ImplementsEventFunction() : // should return true (there is a OnEvent() specialization for SomeEvent) constexpr bool a = ScriptComponent<SomeScript>ImplementsEventFunction<SomeEvent>(); // should return false (there is no OnEvent() specialization for SomeOtherEvent) constexpr bool b = ScriptComponent<SomeScript>ImplementsEventFunction<SomeOtherEvent>(); ImplementsEventFunction() always returns false no matter what the template parameters are. Obviously, I seem to be using the requires expression wrong, but I cannot find my mistake.
There is no reason to require OnEvent to be implemented as a template. This feels like being overly-controlling of the user's code. Concepts are not for telling the user how exactly to implement something. You are going to call an interface in a certain way, and users should implement their code such that that call syntax is valid. And your code ought to be using t.OnEvent(e). There is no reason why your code needs to specify the template argument explicitly at the call site. Users should be able to implement OnEvent for some particular E as a non-template function (or multiple non-template overloads), or as a template function with template argument deduction taking care of the template parameter. As such, the proper concept would be: template<typename T, typename E> concept has_event_for = requires(T t, E e) { t.OnEvent(e); }; class SomeScript : public Script { public: void OnEvent(const SomeEvent& e) { // do stuff } //No need to delete anything or use templates. }; Don't treat concepts like you would base classes, where you explicitly spell out the exact parameters which derived class interfaces must exactly follow. If however you absolutely must do this, you have to use the template keyword at the call site: template<typename T, typename E> concept has_event_for = requires(T t, E e) { t.template OnEvent<E>(e); }; This is yet another reason not to do it this way.
74,405,116
74,405,196
Method of referencing each row of 2d array with for loop in C++
I was practicing array problems and I stuck by this one: Given a declaration of 2D array: int a[][2] = { {2,2}, {3,3}, {4,4} }; write a nested for loop to print all the values of a. First, since 2D array is an array of rows (means each element of this array is a row vector), I tried a for loop like this: for (int& x[]: a) for (int y: x) cout << y << " "; The outer for-loop means I want to reference each row of a, give it a name "x"; the inner for-loop means I want to reference each element of x, give it a name "y". I thought the declaration in the outer for-loop is valid as I specified x as array in integer type, but error showed up while compiling. I checked out the solution and it indicated that x has to be declared as auto type, which means I should write the outer loop as " for(auto& x: a) ". The solution also indicated that this is the only way, but I was not sure whether it is true or not. Hence, I want to figure out couple things: Why it was not working when I wrote a line like " for (int& x[]: a) " ? What is the data type of x in the line " for (auto& x : a) " ? What did auto detected? Is using auto really the only way in this situation? Thank you!
In for (int& x[] : a) x is an array of references. Arrays of references are not legal C++. The type is int[2]. You can avoid auto by writing for (int (&x)[2] : a). The extra parentheses around &x are crucial, without the parens you have an array of references (not legal), with the parens you have a reference to an array.
74,405,122
74,442,398
Factory method pattern with multiple constructors having various sets of arguments
I am trying to make a factory function that will be able to create objects derived from a base class using different constructors based on the given parameters. With some help from other posts here I have been able to make an example that works for a constructor that takes no parameters, but I cannot find a solution for multiple constructors. I have the following: #include <iostream> #include <string> #include <map> #include <typeinfo> #include <functional> using namespace std; class BaseObject { public: BaseObject(){cout<<"BaseObject def constructor\n";}; BaseObject(int type){cout<<"BaseObject non-def constructor\n";} virtual ~BaseObject() = default; virtual string name() = 0; }; class Object1 : public BaseObject { public: Object1(){cout<<"Object1 def constructor\n";}; Object1(int type){cout<<"Object1 non-def constructor\n";} virtual string name() override { return "I am Object1"; } }; class Object2 : public BaseObject { public: Object2(){cout<<"Object2 def constructor\n";}; Object2(int type){cout<<"Object2 non-def constructor\n";} virtual string name() override { return "I am Object2"; } }; struct Factory { public: typedef std::map<std::string, std::function<std::unique_ptr<BaseObject>()>> FactoryMap; template<class T> static void register_type(const std::string & name) { getFactoryMap()[name] = [](){ return std::make_unique<T>(); }; } static std::unique_ptr<BaseObject> get_object(const std::string name) { return getFactoryMap()[name](); } static std::unique_ptr<BaseObject> get_object(const std::string name, int type) { return getFactoryMap()[name](type); } // use a singleton to prevent SIOF static FactoryMap& getFactoryMap() { static FactoryMap map; return map; } }; int main() { Factory::register_type<Object1>("Object1"); Factory::register_type<Object2>("Object2"); // make Object1 using default constructor std::unique_ptr<BaseObject> o1 = Factory::get_object("Object1"); // make Object2 using non-default constructor std::unique_ptr<BaseObject> o2 = Factory::get_object("Object2", 1); std::cout << o1->name() << std::endl; std::cout << o2->name() << std::endl; std::cout << "exit" << std::endl; return 0; } Both Object1 and Object2 have two constructors (it is simplified, in practice the one with the parameter will get some saved data) and Factory has two versions of get_object() each with the name of the object to be created and the corresponding additional parameters. The problem with the second get_object static std::unique_ptr<BaseObject> get_object(const std::string name, int type) { return getFactoryMap()[name](type); } is that the call to the constructor inside passes type parameter, but the type of the function (as defined by typedef FactoryMap) has no parameters (std::function<std::unique_ptr<BaseObject>()>). I explored variadic templates but was not able to figure out how it should be done. One of the helpful post was this one, unforunately it does not have a full working code example.
Inspired by the answer by @numzero, I finally adopted a solution that uses less magic/templates and thus it looks more elegant to me. This solution works for constructors having fields of complex types, on the other hand it is limited by a requirement of all BaseObject descendants to have the same set of constructors (but that was the idea from the start): #include <iostream> #include <string> #include <array> #include <vector> #include <unordered_map> using namespace std; class BaseObject { public: virtual ~BaseObject() = default; virtual string name() { return "I am BaseObject"; } }; class Object1 : public BaseObject { public: Object1(const int i){cout<<"Object1 int constructor\n";} Object1(const std::string s){cout<<"Object1 string constructor\n";} Object1(const std::vector<double> params){cout<<"Object1 vector constructor\n";} virtual string name() override { return "I am Object1"; } }; class Object2 : public BaseObject { public: Object2(const int i){cout<<"Object2 int constructor\n";} Object2(const std::string s){cout<<"Object2 string constructor\n";} Object2(const std::vector<double> params){cout<<"Object2 vector constructor\n";} virtual string name() override { return "I am Object2"; } }; using constructor1_t = std::function<std::unique_ptr<BaseObject>(const int)>; using constructor2_t = std::function<std::unique_ptr<BaseObject>(const std::string s)>; using constructor3_t = std::function<std::unique_ptr<BaseObject>(const std::vector<double>)>; using constructors_t = std::tuple<constructor1_t, constructor2_t, constructor3_t>; using constructors_map_t = std::unordered_map<std::string, constructors_t>; template <class T> std::function<constructors_t()> object_constructors = [](){ return constructors_t{ [](const int i){return std::make_unique<T>(i); }, [](const std::string s){return std::make_unique<T>(s); }, [](const std::vector<double> v){return std::make_unique<T>(v); } }; }; constructors_map_t constructors_map = { {"Object1", object_constructors<Object1>()}, {"Object2", object_constructors<Object2>()} }; int main() { int i = 12; std::string s = "abc"; std::vector<double> v(4, 0.0); auto c1 = constructors_map["Object1"]; std::unique_ptr<BaseObject> o1 = std::get<0>(c1)(i); std::unique_ptr<BaseObject> o2 = std::get<1>(c1)(s); std::unique_ptr<BaseObject> o3 = std::get<2>(c1)(v); std::cout << o1->name() << std::endl; std::cout << o2->name() << std::endl; std::cout << o3->name() << std::endl; std::cout << "----" << std::endl; auto c2 = constructors_map["Object2"]; std::unique_ptr<BaseObject> o4 = std::get<0>(c2)(i); std::unique_ptr<BaseObject> o5 = std::get<1>(c2)(s); std::unique_ptr<BaseObject> o6 = std::get<2>(c2)(v); std::cout << o4->name() << std::endl; std::cout << o5->name() << std::endl; std::cout << o6->name() << std::endl; return 0; }
74,405,184
74,405,262
C++ error: expression cannot be used as a function (find_if)
The essence of the program: get a map, where the values are char from the passed string, and the key is the number of these values in the string using namespace std; map<char, int> is_merge(const string& s) { map<char, int> sCount {}; for (auto lp : s) { if (find_if(sCount.begin(), sCount.end(), lp) != sCount.end()) { sCount[lp] += 1; } else { sCount.insert(make_pair(lp, 0)); } } return sCount; } int main() { string test = "aba"; map <char, int> res = is_merge(test); for (auto lp : res) { cout << lp.first << ":" << lp.second << endl; } return 0; } But an error occurs in the console: /usr/include/c++/12/bits/predefined_ops.h:318:30: error: expression cannot be used as a function 318 | { return bool(_M_pred(*__it)); } | ~~~~~~~^~~~~~~
std::find_if takes a predicate not a value. Hence the error that lp is not a callable. To find a key in a map you should use std::map::find because it is O(logn) compared to O(n) for std::find/std::find_if (as a rule of thumb you can remember: If a container has a member function that does the same as a generic algorithm the member function is at least as effcient, often better). However, there is not need to check if the key is present via find. The function can be this: map<char, int> is_merge(const string& s) { map<char, int> sCount {}; for (auto lp : s) { ++sCount[lp]; } return sCount; } std::map::operator[] already does insert an element when none is found for the given key. You don't need to do that yourself. PS: And if you do call insert then there is no need for std::make_pair : sCount.insert({lp, 0});. std::make_pair is for when you need to deduce the type of the pair from arguments to std::make_pair, but you don't need that here. PPS: And if you do use std::find you need to consider that the element type of your map is std::pair<const char, int>, not char.
74,405,519
74,405,675
Is there a way to assign a templated type to a defined class structure?
I am trying to create a simple binary tree capable of holding data of multiple types. The binary tree will be hard coded with data (compile time could work for this). Here is my code: class BTree { template <typename T> struct Node { Node* left_ = nullptr; Node* right_ = nullptr; T data_; explicit Node(T value) : data_(value) {} }; Node<int>* root_ = nullptr; public: BTree() { root_ = new Node<int>(2); auto ptr = root_; ptr->left_ = new Node<const char*>("SomeString"); } }; I get the error message "Cannot assign to type Node<int>* from Node<const char*>*". Now, I fully understand what the error message is saying and I know there is no way to convert a char* into an int, but is there a way to have my left_ and right_ pointer members to point at a templated type? For this project, I cannot include any third-party libraries. I tried changing them to Node<T>* but it still doesn't work because when the initial root_ node is created, it is created with an int type. I also tried making a custom = operator: Node<T>& operator=(const Node<const char*>* ptr) { left_ = nullptr; right_ = nullptr; data_ = *ptr->data_; return this; } This also does not work and at this point I'm a little bit out of my scope.
You can solve the immediate problem of being able to build the tree of pointers by using inheritance. struct NodeBase { NodeBase* left = nullptr; NodeBase* right = nullptr; }; template <typename T> struct Node : NodeBase { T data; explicit Node(T value) : data(value) {} }; NodeBase* root = nullptr; Now you can build the tree and walk through it. But you can't do anything with the values in each node unless you have external knowledge of the type of each one.
74,406,229
74,552,824
"undeclared identifier" with MSVC++ 17.34 (VS 22) within decltype-based SFINAE expression
We are trying to update a C++17 project from VS 19 to VS 22, and all of a sudden, our code does not compile anymore. The problem in question arises in two headers of the foonathan/memory libraries, pretty far from our code. The library's own tests compile fine with VS 22. With my limited MSVC++ skill, I was unable to get any information about the actual template instantiation from the error message, which might potentially help. The errors are all error C2065: '<some-identifier>': undeclared identifier, where <some-identifier> is the name of a function parameter appearing in a decltype expression intended to utilise SFINAE. One of the 4 locations is allocator_storage.hpp:140, excerpted here: namespace foonathan::memory { ... template <class StoragePolicy, class Mutex> class allocator_storage : FOONATHAN_EBO(StoragePolicy, ...) { ... template <class OtherPolicy> allocator_storage(const allocator_storage<OtherPolicy, Mutex>& other, FOONATHAN_SFINAE(new storage_policy(other.get_allocator()))) // <--- HERE, this is line 140 : storage_policy(other.get_allocator()) {} ... }; ... } The full error message I get from MSVC is not helpful, the only extra information is the name of the template being instantiated, without the actual type substitutions: C:\...\foonathan\memory\allocator_storage.hpp(315): note: see reference to class template instantiation 'foonathan::memory::allocator_storage<StoragePolicy,Mutex>' being compiled C:\...\foonathan\memory\allocator_storage.hpp(140): error C2065: 'other': undeclared identifier With FOONATHAN_SFINAE(Expr) being defined as decltype((Expr), int()) = 0 (no platform configuration whatsoever to be seen anywhere), that error message looks clearly wrong to me - there is an obvious definition of other right there. I'm looking for any hints on what is going on here, or what I could do to help understand the issue. Is there a way to make MSVC print the type it is substituting into the template parameters, like clang and gcc nowadays do? Is there a known issue with MSVC and decltype-based SFINAE in method arguments?
A minimal example for the issue is (live on godbolt; thanks to Maciej Polański on whose original reproduction attempt this code is based) template <class StoragePolicy> struct allocator_storage { template <class OtherPolicy> allocator_storage( allocator_storage<OtherPolicy> const & other, decltype(new StoragePolicy(other.storage_policy), int()) = 0) : storage_policy(other.storage_policy) { } allocator_storage() = default; StoragePolicy storage_policy; }; int main() { allocator_storage<int> A{}; allocator_storage<long> B(A); } Both clang and gcc compile it, but MSVC causes an error when using C++17 with /permissive- (but not in C++17 with /permissive, which in C++17 is equal to not specifying anything) and also with C++20 (regardless of the permissive flag). As a side note, /std:c++20 enables /permissive- by default. The latest MSVC version (after 19.33) provides a bit more information, namely <source>(22): note: Failed to specialize function template 'allocator_storage<long>::allocator_storage(const allocator_storage<OtherPolicy> &,unknown-type)' <source>(22): note: With the following template arguments: <source>(22): note: 'OtherPolicy=int' <source>(22): note: while trying to match the argument list '(allocator_storage<int>)' while versions <=19.33 do not show this error message. Unfortunately, it doesn't really provide more information. There are some bug reports on developer-community (for example this or this) that look related, i.e. use SFINAE with decltype. Considering all that (clang and gcc compile the code; existing bug reports), I'd say this is pretty surely a bug in MSVC. A possible workaround was already mentioned, by replacing the reference to the parameter other in the decltype with std::declval (godbolt): decltype( new StoragePolicy(std::declval<allocator_storage<OtherPolicy>>().storage_policy), int()) = 0 I have noticed that you already reported this on github.
74,406,506
74,446,669
const and non-const parameter function overloads with a single definition
I have the following 2 function overloads: template<typename F, typename T> void func(F f, std::vector<T>& v) { ... } template<typename F, typename T> void func(F f, const std::vector<T>& v) { ... } The body of both of them is the same. Is there an easy way to define them both with a single definition to avoid code duplication using C++17 or earlier standard? Just to clarify, I want the functions to be constrained based on the std::vector part but I want to allow const and non-const references to be passed. The reason I need both overloads is that the F function object will be applied to the vector and sometimes F will modify the vector and sometimes it will only observe the vector (and I want to allow the vector to be declared const in the second case). I guess I can use C++20 concepts to constrain the function template parameter but I was wondering if there's an easy way to achieve the same thing using C++17 or earlier version of the standard.
I found another solution but it still adds a little bit of overhead: template<typename F, typename VecT> auto func_vec(F f, VecT& vec) { //actual code } template<typename F, typename T> auto func(F f, std::vector<T>& vec) { return func_vec(f, vec); } template<typename F, typename T> auto func(F f, const std::vector<T>& vec) { return func_vec(f, vec); } A third function is defined (func_vec) which holds the actual implementation of func. Note that typename VecT can accept both const and non-const arguments. func overloads are just used to constrain the argument to be of type std::vector<T>& with or without a const qualifier. The good thing about this solution is that it doesn't use SFINAE and is fairly easy to read. The bad thing is that you have to introduce another function template for the actual implementation.
74,406,743
74,408,766
how to get around const size value when initializing char arrays in c++
I am very new to C++, and for a project I am working on, I am trying to initialize a char array buffer with the following code: const int nodeCount = pList->getNumNodes(); const size_t bufferSize = sizeof(Node) * nodeCount; char buffer[bufferSize]; and gets an error saying the size must be constant. I understand that this is because the compiler needs to know the size at compile time. But the size of the buffer in this case depends on the number of nodes in the list, which I have no way of knowing beforehand. How can I get around this restriction? Any help is appreciated, thank you. I should add that this is for school and the professor does not allow STLs.
You can create any size buffer in heap memory at run-time char* buffer = new char[sizeof(Node) * pList->getNumNodes()];
74,407,336
74,407,937
CMake run custom command with externalproject's target
I have a subproject in my project for generating code used in the project, however i want to include it using ExternalProject so it can be built and ran regardless of the toolchain i use for the main project. It mostly works except i can't figure out how to use it in add_custom_command, since i want it to use the target rule specified in the docs: If COMMAND specifies an executable target name (created by the add_executable() command), it will automatically be replaced by the location of the executable created at build time [...] Simple example of my project setup that replicates the issue: https://godbolt.org/z/of8G4c4Gf Replacing the ExternalProject_Add with a simple add_subdirectory makes it work, but wouldn't do what i want in the case of using a different toolchain.
ExternalProject_Add will add the codegen target. However, CMake has no idea what that target is doing and what output it will provide, as that info is now hidden away in the external CMake run. So the outer CMake run has no idea about the codegen binary produced by that step and where it will be located. You need to provide the full path to the executable to add_custom_command manually. ExternalProject_Add will build codegen and place the resulting binary in a subdirectory inside your build directory. The exact location is toolchain dependent, so it can be tricky to reconstruct the full target path. The most robust way to solve this is: Add an install step to the codegen project. This will allow you to portably specify which path the installed binary will end up in relative to the install root directory. Set the INSTALL_DIR option on ExternalProject_Add to a subdirectory inside your PROJECT_BINARY_DIR. Hardcode the full path to the installed codegen binary in the custom command of the outer CMake project. To work on multiple platforms, you may need to make use of the CMAKE_EXECUTABLE_SUFFIX variable.
74,407,858
74,407,967
Why is the value not transferred?
First time using GRPC. I am calling my Stat function, which should return info on a File I am interested in. When I call the Stat function from within the parent Fetch function, I get a response value of 0. Here is what my code looks like: StatusCode DFSClientNodeP1::Stat(const std::string &filename, void *file_status) { StatusCode return_status; grpc::ClientContext context; dfs_service::File request; dfs_service::File_Metadata response; request.set_filename(this->WrapPath(filename)); this->service_stub->get_status(&context, request, &response); std::cout << "SHOULD BE " << response.filesize() << std::endl; file_status = &response; return return_status; } StatusCode DFSClientNodeP1::Fetch(const std::string &filename) { StatusCode return_status; dfs_service::File_Metadata response; return_status = Stat(filename, &response); std::cout << "WHAT IT IS " << response.filesize() << std::endl; return StatusCode::OK; } Here is the output: SHOULD BE 232762 WHAT IT IS 0 I am just curious where I am going wrong here. I tried to be very particular and static_cast the void* handling, but when I did that I got very large numbers, so it seemed the memory did not exist. For that reason I believe it is a memory persistence issue. I also read GRPC documentation, seems that Messages do not persist when the message transfer completes. Is that what is happening here? Should I try to malloc the Message type, seems not right to me.
file_status = &response; will result in the outer response to be a dangling pointer when called in Fetch since you are taking the address of a function-local variable that does no exist outside the scope of the Stat function Instead you should modify the pointer that was passed into Stat StatusCode DFSClientNodeP1::Stat(const std::string &filename, void *file_status) { StatusCode return_status; grpc::ClientContext context; dfs_service::File request; auto response = static_cast<dfs_service::File_Metadata*>(file_status); request.set_filename(this->WrapPath(filename)); this->service_stub->get_status(&context, request, response); std::cout << "SHOULD BE " << response->filesize() << std::endl; return return_status; }
74,407,994
74,408,067
How to transform a unix timestamp in nanoseconds to seconds without losing precision [C++ 17]
I need the unix time in nanoseconds for calculation purposes in seconds, but dont want to lose "precision". So I tried to transform the integer variable to double and expected a 128 divided by 10 to be a 12.8. But in this example I lost precision and only got 12. What am I doing wrong, or where is my understanding problem? This is what I tried: #include <iostream> #include <chrono> using namespace std; int main() { int64_t a = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); double b = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / (1000 * 1000 * 1000); cout<<(a) << " ns \n"; cout.precision(9); cout << fixed << b << " s" << endl; return 0; } Output 1668199112421581468 ns 1668199112.000000000 s Wanted: 1668199112.421581468 s
count returns an integral type, because std::chrono::nanoseconds::rep (the representation type) is an integral type with at least 64 bits. You can use std::chrono::duration<double>, which supports fractional seconds. No need to do the math yourself, duration_cast knows about std::chrono::duration::period.
74,408,105
74,408,286
error: cannot convert ‘int (*)[4]’ to ‘int**’ | SWAPPING ARRAYS
I am trying to write a function that swap two arrays in O(1) time complexity. However, when i try to write the function parameters, I get the error: error: cannot convert ‘int (*)[4]’ to ‘int**’ Here is my code: #include <iostream> using namespace std; void swap_array_by_ptr(int* a[], int* b[]) { int* temp = *a; *a = *b; *b = temp; } int main() { int fr[] = {1,2,3,4}; int rv[] = {4,3,2,1}; swap_array_by_ptr(&fr, &rv); for (int i = 0; i < 4 ; i++) { cout << fr[i] << " "; } cout << endl; for (int i = 0; i < 4 ; i++) { cout << rv[i] << " "; } } However, when i tried to define the arrays with 'new' command, this works as expected as below: #include <iostream> using namespace std; void swap_array_by_ptr(int** a, int** b) { int* temp = *a; *a = *b; *b = temp; } int main() { int fr = new int[4]{1,2,3,4}; int rv = new int[4]{4,3,2,1}; swap_array_by_ptr(&fr, &rv); for (int i = 0; i < 4 ; i++) { cout << fr[i] << " "; } cout << endl; for (int i = 0; i < 4 ; i++) { cout << rv[i] << " "; } } Is there any way that i can define the arrays with [] method and swap the arrays by sending these arrays with '&array' method ? As I believe, there must be a way to do that, I only achieve this when I'm trying to do with 'new' method. However, is there any way to swap two arrays in O(1) complexity with sending parameters as swap_array_by_ptr(&fr, &rv); ? Thanks for help.
You can not swap two arrays with O( 1 ). You need to swap each pairs of corresponding elements of two arrays. In the first program int fr[] = {1,2,3,4}; int rv[] = {4,3,2,1}; swap_array_by_ptr(&fr, &rv); the expressions &fr and &rv have type int( * )[4] while the corresponding function parameters in fact has the type int ** void swap_array_by_ptr(int* a[], int* b[]) { after adjusting the parameters having array types to pointers to the array element types by the compiler. So the compiler issues an error. You could use standard function std::swap declared in the header <utility> the following way std::swap( fr, rv ); But in any case its complexity is O( n ). In the second program there are at least typos. Instead of int fr = new int[4]{1,2,3,4}; int rv = new int[4]{4,3,2,1}; you have to write int *fr = new int[4]{1,2,3,4}; int *rv = new int[4]{4,3,2,1}; In this case you are not swapping arrays themselves. That is the arrays will still store their initial values. You are swapping pointers that point to the dynamically allocated arrays. To be sure that arrays are not swapped consider the following demonstration program. #include <iostream> using namespace std; void swap_array_by_ptr(int** a, int** b) { int* temp = *a; *a = *b; *b = temp; } int main() { int fr[] = { 1,2,3,4}; int rv[] = {4,3,2,1}; int *p1 = fr; int *p2 = rv; swap_array_by_ptr( &p1, &p2 ); for (int i = 0; i < 4 ; i++) { cout << p1[i] << " "; } cout << endl; for (int i = 0; i < 4 ; i++) { cout << p2[i] << " "; } cout << endl; for (int i = 0; i < 4 ; i++) { cout << fr[i] << " "; } cout << endl; for (int i = 0; i < 4 ; i++) { cout << rv[i] << " "; } cout << endl; }
74,408,727
74,409,005
Is there a way to store functions in a vector?
I'm attempting to create a menu system within my C++ program and I'm having trouble implementing past the initial main menu. I want to have multiple Menu objects that I pass to my function called showMenu() that calls the function that pairs with the respective menu item. Should I be storing function pointers in the vector? Any advice is helpful - the cleaner the solution, the better. Here's my code: struct Menu { vector<string> items; vector<function> functions; // incorrect }; Menu mainMenu = { { "Quit", "Income Menu", "Expenses Menu" }, { return, showMenu(incomeOptions), showMenu(expenseOptions) } // incorrect }; Menu incomeOptions = { {"Back" , "Add Income", "Edit Income"}, { return, addIncome(), editIncome()} // incorrect }; Menu expenseOptions = { {"Back" , "Add Expense", "Edit Expense"}, { return, addExpense(), editExpense()} // incorrect }; void showMenu(Menu menu, string title = "") { system("cls"); if (title != "") { cout << "================ [" << title << "] ================" << endl; cout << endl; } for (int i = 0; i < menu.items.size(); i++) { cout << " (" << i << ") " << menu.items[i] << endl; } int selection; cout << "\t> "; cin >> selection; if (selection >= 0 && selection < menu.items.size()) { // call function that's paired with selected item menu.functions[selection]; } else { // invalid selection made, display menu again showMenu(menu, title); } } int main() { showMenu(mainMenu, "Main Menu"); } I've attempted to research the c++ library . I'm pretty sure that's what I need, but like I said, am having trouble implementing it. I'd love to get some suggestions.
You have to provide template parameters for std::function: struct Menu { vector<string> items; vector<function<void(void)>> functions; }; And than you can pass lamdas to it: Menu incomeOptions = { {"Add Income", "Edit Income"}, {[]{ addIncome(); }, []{ editIncome(); }} }; Menu expenseOptions = { {"Add Expense", "Edit Expense"}, {[]{ addIncome(); }, []{ editIncome(); }} }; Menu mainMenu = { {"Income Menu", "Expenses Menu"}, {[]{ showMenu(incomeOptions); }, []{ showMenu(expenseOptions); }} }; You will have to handle the return differently. And anyway, it it not a good idea to store your menus as global variables. You should change this! But pay attention to the fact that for the mainMenu you must add the other menus to the capture of its lambdas. int main() { Menu incomeOptions = { {"Add Income", "Edit Income"}, {[]{ addIncome(); }, []{ editIncome(); }} }; Menu expenseOptions = { {"Add Expense", "Edit Expense"}, {[]{ addIncome(); }, []{ editIncome(); }} }; Menu mainMenu = { {"Income Menu", "Expenses Menu"}, {[&incomeOptions]{ showMenu(incomeOptions); }, [&expenseOptions]{ showMenu(expenseOptions); }} }; showMenu(mainMenu, "Main Menu"); } Passing the menus by value to the showMenu function is a waste of resources. Feel free to modify it for reference. void showMenu(Menu &menu, string title = "") { // ... } And in you showMenu function. Calling the function also requires the use of the parentheses. menu.functions[selection](); Calling showMenu on invalid input is not the best idea because these recursive calls will eat up your stack after a while. I recommend changing this to a loop. And also, adding using namespace std; to your code is a bad practice in the long run.
74,408,773
74,408,863
Can't call function from .dll created in C++
I'm able to call function from DLL created in C (.c file), but i can't do it from DLL created in C++ (.cpp file). I want to find out why it doesn't work in .cpp file. I'm trying to call function printword() from a simple DLL, created with Visual Studio 2022: // FILE: dllmain.cpp BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } __declspec(dllexport) void printword() { std::cout << "word" << std::endl; //with printf() doesn't work too } And when i call function the way like this: int main() { HMODULE dll; if ((dll = LoadLibrary(L"D:\\Visual Studio projects\\Dll1\\x64\\Debug\\Dll1.dll")) == NULL) { return GetLastError(); } FARPROC func; if ((func = GetProcAddress(dll, "printword")) == NULL) { return GetLastError(); } func(); return 0; } GetProcAddress throws error ERROR_PROC_NOT_FOUND But if i create DLL in file with .c suffix printword() function calls correctly (with same code above): // FILE: dllmain.c BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } __declspec(dllexport) void printword() { printf("word\n"); }
The exported function's name will get mangled when the DLL is compiled. You must use the mangled name in GetProcAddress() in order for it to work. For example, the mangled name in MSVC is: GetProcAddress(dll, "?printword@@YAXXZ"); Or, you could add this to the function's body to tell the compiler not to mangle it: __declspec(dllexport) void printword() { #pragma comment(linker, "/EXPORT:" __FUNCTION__"=" __FUNCDNAME__) printf("word\n"); } Alternatively, adding extern "C" will also solve the problem.
74,409,226
74,409,261
How to restrict a class template parameter to a certain subclass?
This is what I am trying: C is a template parameter that is either SomeClass or SomeDerivedClass: class SomeClass { protected: int ProtectedBaseClassMember; virtual void SomeFunctionFromBaseClass(); }; class SomeDerivedClass : public SomeClass { }; How to restrict C to subclasses of SomeClass? template<class C> class SmuggleInBetween : public C { public: SmuggleInBetween() { // does not compile: unknown symbol "ProtectedBaseClassMember" ProtectedBaseClassMember = 5; // does compile, but ... SomeClass* Me = static_cast<SomeClass>(this); // ... member not accessible: Me->ProtectedBaseClassMember = 5; } protected: // doesn't compile: "method with override specifier did not override any base class method" virtual void SomeFunctionFromBaseClass() override; double DoubleProperty; }; I found the very related question: Restrict C++ Template parameter to subclass, but over there the author seems fine just restricting the template parameter w/o ever accessing any symbols from the base class. The use case for the templated SmuggleInBetween class is this: I can create class SomeImprovedClass : public SmuggleInBetween<SomeClass> { }; and class SomeImprovedDerivedClass : public SmuggleInBetween<SomeDerivedClass> { }; without having to duplicate the code that I smuggled in via this pattern (if possible). Btw, this happens in the context of Unreal Engine. It might be that a solution that is possible in C++ still causes additional headache with the Unreal Header Tool that sometimes doesn't tolerate things that wander too far off the known paths.
This is one way to do it: template<class C> class SmuggleInBetween : public C { static_assert(std::is_base_of_v<SomeClass, C>, "C must be a descendant of SomeClass"); /* ... */ }; Of course, in general you could also use std::enable_if_v<std::is_base_of_v<SomeClass, C>, ...> if you need SFINAE; here I think static_assert() does the trick.
74,409,230
74,409,233
How can i output "\" in console. C
I want to write some symbols in the console, but I have troubles with the output of the \ character. I know it is reserved by C for formatting inside printf(), but I really want to output it. printf(" __ __ __ __ ____ \n"); printf(" ||\ /|| || // ||/\\ \n"); printf(" ||\\//|| ||// ||\// \n"); printf(" || \/ || ||\\ ||‾‾ \n"); printf(" || || || \\ || \n"); printf(" ‾‾ I expect that \\ in this will just output like any other char, but it can't just output.
Backspace is a special escape character in C/C++, so that you can type, e.g., '\n'. You can use \\ to have a \ in your string.
74,409,572
74,409,808
How do I address the screen on a linux terminal?
I am teaching myself C++ and currently run the latest Fedora. On a Windows command prompt you can address the screen location. I am led to the believe that a Linux command terminal works, effectively, like characters printed to a piece of paper. i.e. You can't go "up" from where you are. However, when you install in Linux, there is a progress bar (in text) which doesn't appear to print a new line each time with the increase of progress. Also, take for example raspbi-config in which you can tab/arrow up and down a "menu" and select "OK" and "Cancel" etc. How does one achieve this? Can this then be used to do simple text graphics applications in Linux like one can do under Windows? Any help would be appreciated. Uberlinc. Coding in C++. General non-gui apps which simply "cout" to the stdout. Only found one or two examples which show a progress bar that prints out to the same line, but are not clear to me.
On a basic level, there are two things that enable these kinds of things on a Linux (or other POSIX) terminal: ASCII control characters and ANSI escape codes. For a simple progress bar, it's enough to know how wide the screen is and to have a way to get back to the beginning of the current terminal line. This can be one by reading the environment variable $COLUMNS with getenv and by printing the ASCII control character \r. A very bare-bones and unbeautified example is #include <iostream> #include <sstream> #include <string> #include <unistd.h> int main() { // Default screen width int width = 80; // Get screenwidth from environment char const *envwidth = getenv("COLUMNS"); if(envwidth != nullptr) { std::istringstream(envwidth) >> width; } // save some space for numeric display width -= 10; for(int i = 1; i < width; ++i) { std::cout << '\r' // go back to start of line << std::string(i, '.') // progress bar << std::string(width - i, ' ') // padding << "| " << i << '/' << width // numeric display << std::flush; // make the progress bar instantly visible // pretend to work usleep(100000); } } For more involved terminal "graphics,", there are ANSI escape codes. These allow you to set foreground and background color, move around on the screen at will, and a few other things, by printing special character sequences to stdout. For example, std::cout << "\x1b[10;20HHello, world." << std::flush; will print Hello, world. at position 10, 20 on the screen. There is also the ncurses library that provides more high-level terminal UI functionality (windows, dialogs, that sort of thing). They use ANSI escape codes under the hood, but it's normally nicer to use that than to roll your own UI framework.
74,409,988
74,410,044
Send A Message Across The Internet Using UDP And C++
I created a simple client/server program in which the client is able to send messages to the server. This works on my local computer, and even works when running it on different computers on the same network when I modify the IP_ADDRESS in my client program to be that for the server's IP address. However, this does not work when testing it with devices that are not a part of the same network, even if I change it to be my public IP address. I am pretty sure it would have to somehow use both my public IP address as well as my server's IP address in order to work as I intend, if I am understanding things properly. However, I am unsure of how I would go about implementing that. Ultimately, all I want to know is, how can I send a single message from one known device to another known device across the Internet using UDP with C++? I don't really care about the specific implementation beyond that, so that I can use it for a video game I am trying to make. Server: #include <iostream> #include <WS2tcpip.h> #pragma comment (lib, "ws2_32.lib") int main() { WSADATA wsadata; WORD version = MAKEWORD(2, 2); int wsOk = WSAStartup(version, &wsadata); if (wsOk != 0) { std::cout << "Cannot Start Winsock\n"; return -1; } SOCKET in = socket(AF_INET, SOCK_DGRAM, 0); sockaddr_in serverHint; serverHint.sin_addr.S_un.S_addr = ADDR_ANY; serverHint.sin_family = AF_INET; serverHint.sin_port = htons(54000); if (bind(in, (sockaddr*) &serverHint, sizeof(serverHint)) == SOCKET_ERROR) { std::cout << "Can't Bind Socket " << WSAGetLastError() << std::endl; return -1; } sockaddr_in client; int clientLength = sizeof(client); ZeroMemory(&client, clientLength); char buffer[1024]; while (true) { ZeroMemory(&buffer, sizeof(buffer)); int numOfBytes = recvfrom(in, buffer, sizeof(buffer), 0, (sockaddr*) &client, &clientLength); if (numOfBytes == SOCKET_ERROR) { std::cout << "Error Recieving Client Message " << WSAGetLastError() << std::endl; continue; } char clientIP[256]; ZeroMemory(clientIP, sizeof(clientIP)); inet_ntop(AF_INET, &client.sin_addr, clientIP, sizeof(clientIP)); std::cout << "Message Received From [" << clientIP << "] = " << buffer << std::endl; } closesocket(in); WSACleanup(); } Client: #include <iostream> #include <thread> #include <WS2tcpip.h> #pragma comment (lib, "ws2_32.lib") const char* IP_ADDRESS = "127.0.0.1"; int main() { WSADATA wsadata; WORD version = MAKEWORD(2, 2); int wsOk = WSAStartup(version, &wsadata); if (wsOk != 0) { std::cout << "Cannot Start Winsock\n"; return -1; } sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(54000); inet_pton(AF_INET, IP_ADDRESS, &server.sin_addr); SOCKET out = socket(AF_INET, SOCK_DGRAM, 0); std::string message = "Hello!\n"; for (size_t index = 0; index < 100; index++) { int sendOk = sendto(out, message.c_str(), message.size() + 1, 0, (sockaddr*) &server, sizeof(server)); if (sendOk == SOCKET_ERROR) std::cout << "Failed To Send" << WSAGetLastError() << std::endl; } closesocket(out); WSACleanup(); return 0; } I tried running my client on the same computer as my server, which worked, and also tried running my client on different devices in the same network, which worked when I updated my IP_ADDRESS. However, it did not work when my client was a part of an outside network, despite being connected to the internet and the IP_ADDRESS being modified to be the public IP address of the server.
Nowadays, with common usage of WiFi and multiple devices per location needing Internet access, most devices get their Internet access via a local network router. It is increasingly rare for a computer to be connected directly to an Internet modem anymore. As such, using a router would prevent outside clients from being able to directly access your server's UDP port from over the Internet. In this case, the LAN router would need to have port forwarding configured on it (either manually by an admin, or in code via uPNP) to forward incoming UDP packets from the router's public WAN IP to the server's LAN IP. Then outside clients can send packets to the router's WAN IP and have them reach your server's UDP port for recvfrom() to read.
74,410,149
74,454,452
How to procedurally generate LODs of a triangle mesh
I am looking for an algorithm that can generate level of details of a given mesh. Meshes have a vertex and index buffers. Each LOD number of vertices may be computed as following: LOD0 -> 1 / 2^0 -> 1 * <mesh_number_of_vertices> LOD1 -> 1 / 2^1 -> 1/2 * <mesh_number_of_vertices> ... LOD8 -> 1 / 2^8 -> 1 / 256 * <mesh_number_of_vertices> In term of code, I am looking how to implement the GenerateLOD function: struct Vertex { Math::Vec3 Position; Math::Vec2 Texcoord; }; void GenerateLOD(const std::vector<Vertex>& InVertices, const std::vector<uint32_t>& InIndices, std::vector<Vertex>& outVertices, std::vector<uint32_t>& outIndices, int LODLevel) { const float LODFactor = 1.0f / pow(2, LODLevel); // Generation here... } int main() { const std::vector<Vertex> MeshVertices{ { Math::Vec3(-1.0f, -1.0f, 0.0f), Math::Vec2(0.0f, 1.0f)}, { Math::Vec3(1.0f, -1.0f, 0.0f), Math::Vec2(1.0f, 1.0f)}, { Math::Vec3(-1.0f, 1.0f, 0.0f), Math::Vec2(0.0f, 0.0f)}, { Math::Vec3(1.0f, 1.0f, 0.0f), Math::Vec2(1.0f, 0.0f)} //etc..... }; const std::vector<uint32_t> MeshIndices{ 0, 1, 2, 1, 2, 3/* etc...*/ }; std::vector<Vertex> OutVertices; std::vector<uint32_t> OutIndices; const int LODLevel = 2; GenerateLOD(MeshVertices, MeshIndices, OutVertices, OutIndices, LODLevel); return EXIT_SUCCESS; }
I found that the problem is known as Mesh simplification. Here great papers about it: https://www.cs.cmu.edu/~garland/Papers/quadric2.pdf https://cragl.cs.gmu.edu/seamless/ Open source implementations can be found here: https://github.com/cnr-isti-vclab/meshlab https://github.com/cnr-isti-vclab/vcglib/
74,410,531
74,410,705
There is a list whose contents are type of vector<T>
What should I do to get any vector of the list? I use following code to do it currently: list<vector<T>> alist; list<vector<T>>::iterator iter = alist.begin(); vector<T> vec(*iter); is there any other way by which I don't need to copy the data?
If you need to access all vector of list and modify individual values, you can write as descried below. for (auto& v : alist) { for (auto& i : v) { i = 13; } }
74,410,626
74,410,650
Getting Segmentation violation signal error on copying vector elements?
I have the following code for doing a http post request. I am getting the response in const std::vector<json> value ...The below code works correctly Ttran<std::vector<Lar>> get() const { const std::vector<json> value = res["value"]; std::vector<Lar> account; for (const json &account : value) { account.push_back(account); } return {res["context"], accounts}; } To improve the appending of elements into accounts vector..I am trying to use std::copy() But getting this error: FATAL ERROR: test case CRASHED: SIGSEGV - Segmentation violation signal I am trying this way: Ttran<std::vector<Lar>> get() const { const std::vector<json> value = res["value"]; std::vector<Lar> accounts; std::copy(value.begin(), value.end(), accounts.begin()); return {res["context"], accounts}; } What I am doing wrong ?
reserve does not resize the vector, it just pre-allocates the space so push_backs are cheap and never invalidate any iterators but they are still required. std::copy assumes (like most <algorithm>s) the output iterators are valid, i.e. point to existing location. In this case they do not. What you need is std::back_inserter which will call push_back for you: accounts_list.reserve(value.size()); // Optional optimization std::copy(value.begin(), value.end(), std::back_inserter(accounts_list)); I am not actually sure whether this is the cause since you did not provide a minimal reproducible example, I would expect some iterator assertion, not segfault since the memory should have been allocated. Maybe some empty std::vector optimization is at play.
74,410,850
74,410,880
What are reasons for infinite inputs?
A lot of the times when I code lets say I have only one cin>> I run my code it compiles but I can do infinite inputs even though in my code I have one input. What is the reason for this? I checked for infinity loops found none for the specific test case I was working with. Here's the code if you want to see. #include <iostream> using namespace std; int main() { long long a,b,c; cin >> a >> b >> c; long long mx,mn; if(b >= a) { b = mx; a = mn; } if(a > b) { a = mx; b = mn; } int x; int r = c; for(int i = mn; i <= mx; i++) { x = i; if(x - mn == mx - x) { for(int j = 0; j < x; j++) { c += r * r; } cout << c + (mx - mn); return 0; } } }
The problem lies down here, you are re-assigning values of a and b with some unassigned variables. if(b >= a){ b = mx; a = mn; } if(a > b){ a = mx; b = mn; } Rather you may want to initialize max and mn with newly assigned values a, b if(b >= a){ mx = b; mn = a; } if(a > b){ mx = a; mn = b; }
74,411,266
74,411,303
How to directly specify some values as an argument in C++ instead of specifying an array name or a pointer to an array
Can I write a function in C++ to accept an array of values like this: void someFunction(/*the parameter for array*/){ //do something } someFunction({ 1, 2, 3 });
There are various ways of doing this. Method 1 Using initializer_list as parameter type. void someFunction(std::initializer_list<int> init){ } int main() { someFunction({ 1, 2, 3 }); } Method 2 Using std::vector<int> as parameter type. void someFunction(const std::vector<int> &init){ } int main() { someFunction({ 1, 2, 3 }); }
74,411,342
74,411,471
Will moving from released pointers leak memory?
I have the following code: std::unique_ptr<T> first = Get(); … T* ptr_to_class_member = GetPtr(obj); *ptr_to_class_member = std::move(*first.release()); Will this behave as expected with no copies, 1 move and without memory leak?
*ptr_to_class_member = std::move(*first.release()); just calls the move assignment operator of T with the object pointed to by first as argument. This may properly transfer some data, but delete is not called or the object so neither T::~T is executed nor does the memory of the object get freed. In the example of T = std::string this would result in the backing storage of the string object properly being transfered from the rhs to the lhs of the move assignment, but dynamically allocated memory of size sizeof(std::string) would still be leaked. For some classes the lack of a destructor invocation for the object could result in additional trouble, since move assignment simply needs to leave the rhs in an unspecified, but valid state which could still require freeing of additional resources. You need to do *ptr_to_class_member = std::move(*first); first.reset(); in order to prevent memory leaks. To show what's going wrong here, the following code implements prints for memory (de)allocation and special member functions: #include <iostream> #include <memory> #include <new> #include <utility> struct TestObject { TestObject() { std::cout << "TestObject::TestObject() : " << this << '\n'; } TestObject(TestObject&& other) { std::cout << "TestObject::TestObject(TestObject&&) : " << this << ", " << &other << '\n'; } TestObject& operator=(TestObject&& other) { std::cout << "TestObject::operator=(TestObject&&) : " << this << ", " << &other << '\n'; return *this; } ~TestObject() { std::cout << "TestObject::~TestObject() : " << this << '\n'; } void* operator new(size_t size) { void* const result = ::operator new(size); std::cout << "memory allocated for TestObject: " << result << '\n'; return result; } void operator delete(void* mem) { std::cout << "memory of TestObject deallocated: " << mem << '\n'; ::operator delete(mem); } }; template<class Free> void Test(Free free, char const* testName) { std::cout << testName << " begin -------------------------------------------\n"; { auto ptr = std::make_unique<TestObject>(); std::cout << "object creation done\n"; free(ptr); } std::cout << testName << " end ---------------------------------------------\n"; } int main() { TestObject lhs; Test([&lhs](std::unique_ptr<TestObject>& ptr) { lhs = std::move(*ptr); ptr.reset(); }, "good"); Test([&lhs](std::unique_ptr<TestObject>& ptr) { lhs = std::move(*ptr.release()); }, "bad"); } Possible output: TestObject::TestObject() : 0000009857AFF994 good begin ------------------------------------------- memory allocated for TestObject: 000001C1D5715EF0 TestObject::TestObject() : 000001C1D5715EF0 object creation done TestObject::operator=(TestObject&&) : 0000009857AFF994, 000001C1D5715EF0 TestObject::~TestObject() : 000001C1D5715EF0 memory of TestObject deallocated: 000001C1D5715EF0 good end --------------------------------------------- bad begin ------------------------------------------- memory allocated for TestObject: 000001C1D5715EF0 TestObject::TestObject() : 000001C1D5715EF0 object creation done TestObject::operator=(TestObject&&) : 0000009857AFF994, 000001C1D5715EF0 bad end --------------------------------------------- TestObject::~TestObject() : 0000009857AFF994 You can clearly see the destructor call and deallocation missing in the second case, which is the one matching the code you're asking about.
74,411,495
74,411,608
My st.show on stack cannot be display for some reason
My problem on my code is when i run it, it says the error no matching function call to stack::show() which i have. i dont know whats causing the error, did some research that it should be on the public class which already there. I used switch case 1 is to input 2nd is to show or to display the user inputs which I cant call out using st.show(); private: int MAX; int top; string *arr_q; public: Stack (int size) { MAX=size; top=-1; arr_q=new string[MAX]; } void push(string subs) { if ((top+1)==MAX) cout << "Stack Overflow..." << endl; top=top+1; arr_q[top]=subs; } void show(int lim) { int i = lim; cout<<"Stack contains --"<<endl; for (int ctr=i; ctr>=0; ctr--) { if (ctr==i) cout<<"\t\t"<<arr_q[ctr]<<"<--Top of Stack"<<endl; else cout<<"\t\t"<<arr_q[ctr]<<endl; } } }; case 2: { st.show(); break;
The error is that your show function has a parameter but when you call it there is no parameter. Seems reasonably likely that show should be written without a parameter. Like this void show() { cout<<"Stack contains --"<<endl; for (int ctr=top; ctr>=0; ctr--) { if (ctr==top) cout<<"\t\t"<<arr_q[ctr]<<"<--Top of Stack"<<endl; else cout<<"\t\t"<<arr_q[ctr]<<endl; } }
74,411,695
74,411,735
uint8_t and int8_t conversion
Consider the following program: using namespace std; int main() { uint8_t b = 150; int8_t a = -10; if (a>b){ cout << "greater" << endl; } else{ cout << "less" << endl; } return 0; } In Online C++14 Compiler it prints less. The same result I get in Compiler Explorer with x86-64 gcc 12.2 According to the documentation Otherwise, the operand has integer type (because bool, char, char8_t, (since C++20) char16_t, char32_t, (since C++11) wchar_t, and unscoped enumeration were promoted at this point) and integral conversions are applied to produce the common type, as follows: If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank. Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type. Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type. Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type. In the Compiler Explorer with x86-64 gcc 12.2 I've compiled it and got the following result: .LC0: .string "greater" .LC1: .string "less" main: push rbp mov rbp, rsp sub rsp, 16 mov BYTE PTR [rbp-1], -106 mov BYTE PTR [rbp-2], -10 movsx edx, BYTE PTR [rbp-2] movzx eax, BYTE PTR [rbp-1] cmp edx, eax jle .L2 mov esi, OFFSET FLAT:.LC0 mov edi, OFFSET FLAT:_ZSt4cout call std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) mov esi, OFFSET FLAT:_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ mov rdi, rax call std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&)) jmp .L3 ... So, accoring to mov BYTE PTR [rbp-1], -106 mov BYTE PTR [rbp-2], -10 uint8_t b is converted to int8_t and is assigned a value of -106, which seems to be true, because it falls under the point 3. of the documentation: Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type. If I understood the documentation and the assembly code right, the comparison (a>b) //-10 > -106 Should return true. But apparently, it returns false since I get the output of the else branch. So my questions is: why is (a>b) returns false in this example?
You forgot about integral promotion. From https://en.cppreference.com/w/cpp/language/operator_arithmetic : If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion. From https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion : prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int) Both a and b are first promoted to int, and then they are compared. As an int.
74,411,804
74,411,876
How to change values of private variables for all objects from under the same class?
How to make the variable m_i have its own value for each object, and when a certain function is called, the value of m_i for all objects should be set to zero, no matter how many objects of the class CMyClass were created? #include <iostream> using namespace std; class CMyClass { public: static int m_i; }; int CMyClass::m_i = 0; CMyClass myObject1; CMyClass myObject2; int main() { cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; myObject1.m_i = 1; // set m_i to 1 for first object cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; myObject2.m_i = 2; // set m_i to 2 for second object cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; CMyClass::m_i = 0; // set m_i to zero for all objects cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; } Output 0 0 1 1 2 2 0 0 Expected output should be: Output 0 0 1 0 1 2 0 0 UPD The solution for MCU usage was proposed by @Lasersköld and works without any additionally libraries: #include <iostream> using namespace std; class CMyClass { public: // The member variable should not be static because // it is unique for each class instance. int m_i; }; CMyClass instances[2]; void resetInstances() { for (auto &instance: instances) { instance.m_i = 0; } } int main() { cout << instances[0].m_i << endl; cout << instances[1].m_i << endl; instances[0].m_i = 1; cout << instances[0].m_i << endl; cout << instances[1].m_i << endl; instances[1].m_i = 2; cout << instances[0].m_i << endl; cout << instances[1].m_i << endl; resetInstances(); cout << instances[0].m_i << endl; cout << instances[1].m_i << endl; } Output: 0 1 0 1 2 0 0
Save each instance in a static list like so: #include <iostream> #include <vector> using namespace std; class CMyClass { public: CMyClass(int i): m_i{i} { instances.push_back(this); } // ~CMyClass() { // ... handle removal if nessesary. check out std::remove(...) // } int m_i = 0; static std::vector<CMyClass*> instances; static void reset() { for (auto &instance: instances) { instance->m_i = 0; } } }; std::vector<CMyClass*> CMyClass::instances; int main() { CMyClass myObject1{0}; CMyClass myObject2{0}; cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; myObject1.m_i = 1; cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; myObject2.m_i = 2; cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; CMyClass::reset(); cout << myObject1.m_i << endl; cout << myObject2.m_i << endl; } Possible microcontroller (heapless) implementation. #include <iostream> #include <array> using namespace std; class CMyClass { public: // The member variable should not be static because // it is unique for each class instance. int m_i = 0; }; // If you use microcontrollers that does not implement the standar library // replace this with // CMyClass instances[2]; std::array<CMyClass, 2> instances; void resetInstances() { for (auto &instance: instances) { instance.m_i = 0; } } int main() { cout << instances.at(0).m_i << endl; cout << instances.at(1).m_i << endl; instances.at(0).m_i = 1; cout << instances.at(0).m_i << endl; cout << instances.at(1).m_i << endl; instances.at(1).m_i = 2; cout << instances.at(0).m_i << endl; cout << instances.at(1).m_i << endl; resetInstances(); cout << instances.at(0).m_i << endl; cout << instances.at(1).m_i << endl; } Note: I do not recommend using the name convention with m_ for public class members. In this case i would call the member variable m_i for simply i and then use m_... for private variables that is only used in private functions of the class.
74,412,226
74,413,484
How throw a GCC error, if a global variable with the same name gets declared twice in a C/C++ file, but not static, extern, nor volatile?
I did run into the situation, that I declared two (separate) global variables with the same name in two separate files, but without using static, volatile nor extern on them. One file was a .c and the other a .cpp file. The compiler and build environment (GCC) was the ESP IDF and even the data types were different on these declarations. mqtt_ssl.c: esp_mqtt_client_handle_t client; mb_master.cpp: PL::ModbusClient client(port, PL::ModbusProtocol::rtu, 1); During the runtime i experienced a lot of problems with reboots of the ESP32 until I found out, that the same name, of two actually separate variables, is causing the issue. My guess is, that the compiler used the same memory-region for both of them. I expected, that it gets handled as two separate objects with its own region in the memory, which is obviously not true. After reading some questions here and there is my understanding now is that the behavior is undefined, if a variable with the same name gets declared without static, extern or volatile in two separate C/C++ files. It took me quite a while to figure that out. If it is not allowed to declare it like this, why didn't the compiler/linker throw an error? Is there an option for GCC to treat such a situation as error to prevent that situation in the future? Edit 1: This is a reproducible example with xtensa-esp32-elf-gcc.exe (crosstool-NG esp-2021r2-patch3) 8.4.0. app_main.c #include <stdio.h> void test_sub(void); uint16_t test1; void app_main(void) { test1 = 1; printf("app_main:test1=%d\n", test1); test_sub(); printf("app_main:test1=%d\n", test1); } test_sub.c #include <stdio.h> int16_t test1; void test_sub(void) { test1 = 2; printf("test_sub:test1=%d\n", test1); } Result: app_main:test1=1 test_sub:test1=2 app_main:test1=2 test1 in app_main() got overwritten by test_sub(), because it had the same name in both files.
esp_mqtt_client_handle_t client; is a tentative definition. In spite of its name, it is not a definition, just a declaration, but it will cause a definition to be created at the end of the translation unit if there is no regular definition in the translation unit. The C standard allows C implementations to choose how they resolve multiple definitions (because it says it does not define the behavior, so compilers and linkers may define it). Prior to GCC version 10, the default in GCC was to mark definitions from tentative definitions as “common,” meaning they could be coalesced with other definitions. This results in the linker not complaining about such multiple definitions. Giving the -fno-common switch to GCC instructs it not to do this; definitions will not be marked as “common,” and the linker will complain if it sees multiple definitions.
74,412,625
74,413,685
How to write iterator wrapper that transforms several values from base container
I have algorithm that uses iterators, but there is a problem with transforming values, when we need more than single source value. All transform iterators just get some one arg and transforms it. (see similar question from the past) Code example: template<typename ForwardIt> double some_algorithm(ForwardIt begin, ForwardIt end) { double result = 0; for (auto it = begin; it != end; ++it) { double t = *it; /* do some calculations.. */ result += t; } return result; } int main() { { std::vector<double> distances{ 1, 2, 3, 4 }; double t = some_algorithm(distances.begin(), distances.end()); std::cout << t << std::endl; /* works great */ } { /* lets now work with vector of points.. */ std::vector<double> points{ 1, 2, 4, 7, 11 }; /* convert to distances.. */ std::vector<double> distances; distances.resize(points.size() - 1); for (size_t i = 0; i + 1 < points.size(); ++i) distances[i] = points[i + 1] - points[i]; /* invoke algorithm */ double t = some_algorithm(distances.begin(), distances.end()); std::cout << t << std::endl; } } Is there a way (especialy using std) to create such an iterator wrapper to avoid explicitly generating distances value? It could be fine to perform something like this: template<typename BaseIterator, typename TransformOperator> struct GenericTransformIterator { GenericTransformIterator(BaseIterator it, TransformOperator op) : it(it), op(op) {} auto operator*() { return op(it); } GenericTransformIterator& operator++() { ++it; return *this; } BaseIterator it; TransformOperator op; friend bool operator!=(GenericTransformIterator a, GenericTransformIterator b) { return a.it != b.it; } }; and use like: { /* lets now work with vector of points.. */ std::vector<double> points{ 1, 2, 4, 7, 11 }; /* use generic transform iterator.. */ /* invoke algorithm */ auto distance_op = [](auto it) { auto next_it = it; ++next_it; return *next_it - *it; }; double t = some_algorithm( generic_transform_iterator(points.begin(), distance_op), generic_transform_iterator(points.end() -1 , distance_op)); std::cout << t << std::endl; } So general idea is that transform function is not invoked on underlying object, but on iterator (or at least has some index value, then lambda can capture whole container and access via index). I used to use boost which has lot of various iterator wrapping class. But since cpp20 and ranges I'm curious if there is a way to use something existing from std:: rather than writing own wrappers.
With C++23, use std::views::pairwise. In the meantime, you can use iota_view. Here's a solution which will work with any bidirectional iterators (e.g. points could be a std::list): auto distances = std::views::iota(points.cbegin(), std::prev(points.cend())) | std::views::transform([](auto const &it) { return *std::next(it) - *it; }); This can also be made to work with any forward iterators. Example: std::forward_list<double> points{1, 2, 4, 7, 11}; auto distances = std::views::iota(points.cbegin()) | std::views::take_while([end = points.cend()](auto const &it) { return std::next(it) != end; }) | std::views::transform([](auto const &it) { return *std::next(it) - *it; }) | std::views::common; Note that both of these snippets have undefined behaviour if points is empty.
74,412,851
74,413,169
C++ No instance of overloaded function matches the argument list when calling std::replace()
I am doing my custom image file format to display images in CLI but i need to convert size_t to std::string: namespace csfo { class Res { public: char* BLANK_DATA = "..."; }; ... inline char* generate(int COLOR, size_t x, size_t y, bool verbose) { csfo::Res RES; ... std::string dimenssions[2] = { std::to_string(x), std::to_string(y) }; std::string DATA = RES.BLANK_DATA; DATA = DATA.replace(DATA.begin(), DATA.end(), "[X_SIZE]", dimenssions[0]); ... }; ... } But i get this error when i try to call std::to_string() No instance of overloaded function matches the argument list c/c++(304) Can someone please help me? Thanks. I except my code to work
Your error means that your compiler didn't find any matching "variant" (overloading) of std::string::replace method. To replace given text in std::string, you should: Find the text position and determine the text length. Check if found. Replace if found. E.g: #include <iostream> #include <string> //! Replaces the first occurence of @param text in @param textTemplate with @param toInsert. // Since C++17 use std::string_view for @param text. void replace_text(std::string& textTemplate, const std::string& text, const std::string& toInsert) { const std::size_t pos = textTemplate.find(text); if (pos == std::string::npos) { /// Given @param text not found. return; } textTemplate.replace(pos, text.length(), toInsert); } int main() { static const std::string X_SIZE = "[X_SIZE]"; std::string DATA = "My data template with [X_SIZE] occurence."; replace_text(DATA, X_SIZE, std::to_string(4)); std::cout << DATA << std::endl; return 0; } The membercsfo::Res::BLANK_DATA should be const char* or std::string_view or std::string but not just char* - because you cannot modify it when pointing to string literal.
74,412,962
74,414,303
SDL2 Window Only Shows Black Background
I'm starting a new project in SDL2 and as I'm still trying out different architectural approaches I usually start out by bringing up a white window to confirm that the new approach I'm trying out satisfies at least the bare minimum to get started with SDL2. This time, I wanted to try wrapping my application into a separate Application class so as to unclutter main, like so: #include <SDL2/SDL.h> #include <stdio.h> #include <string> #include "HApplication/HApplication.h" //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; int main(int argc, char *argv[]) { HApplication application = HApplication( SCREEN_WIDTH, SCREEN_HEIGHT ); bool hasStarted = application.checkRunning(); if ( hasStarted ){ application.run(); } else{ std::string msg = "Application failed to initialize."; SDL_LogError( SDL_LOG_CATEGORY_ERROR, msg.c_str() ); } // add error codes return 0; } Now, the run method in HApplication is meant to reflect the main loop until the user exits. For test purposes, I'd just like to get two lines crossing in the middle on a white background. After initializing SDL, the window, and the renderer, which all work out fine, I'm presented with a window filled completely back, although I've used very similar code successfully before: void HApplication::run() { // while user doesn't quit, keep going bool userQuit = false; SDL_Event e while( !userQuit ) { // handle queued events while ( SDL_PollEvent( &e ) != 0 ) { if ( e.type == SDL_QUIT ) { userQuit = true; } } // clear screen SDL_SetRenderDrawColor( appRenderer, 255, 255, 255, 255); SDL_RenderClear( appRenderer ); // draw cross SDL_SetRenderDrawColor( appRenderer, 0, 0, 0, 255 ); SDL_RenderDrawLine( appRenderer, 0, screenHeight/2, screenWidth, screenHeight/2); SDL_SetRenderDrawColor( appRenderer, 0, 0, 0, 255 ); SDL_RenderDrawLine( appRenderer, screenWidth/2 , 0, screenWidth/2, screenHeight); // update screen with new scene SDL_RenderPresent( appRenderer ); SDL_UpdateWindowSurface( appWindow ); } close(); } I'm not quite sure why this happens, especially since I can see what I want stepping through the loop step-by-step using the debugger. I am quite honestly pretty much at a loss at where to even start. I tried looking on Google and Stackoverflow for similar questions. However, these were mostly addressing problems with loading textures, which I haven't even gotten to yet. If possible, I would like to keep a separate class handling game logic and resources. EDIT: It seems like I needed to get rid of SDL_UpdateWindow. However, I'm not quite sure why. If anyone has an explanation, I'd be happy to hear!
SDL has both a CPU rendering API and a GPU one. Everything that works with a SDL_Renderer belongs to the GPU API. For example, you can make a SDL_Texture and use SDL_RenderCopy to render it. The final step is to call SDL_RenderPresent so that everything that was rendered gets displayed. SDL_UpdateWindowSurface is part of the CPU API. To use this API, you can for example draw to a SDL_Surface and then use SDL_BlitSurface with SDL_GetWindowSurface to render to the window's surface. The final step is to call SDL_UpdateWindowSurface to display the changes, which is the equivalent to SDL_Flip in SDL 1.2. In short: after the SDL_RenderPresent call, you get what you wanted, but after the SDL_UpdateWindowSurface call, you overwrite that with the CPU window surface which is probably initialized to black. Just remove that SDL_UpdateWindowSurface call and use the GPU API only.
74,413,041
74,413,104
C++ raw pointers using this for operator overload results in segmentation fault when freeing memory
I am trying to build a Tree of operations for a Tensor application in c++. When I write c = a + b I would like c to have as children two pointers a and b. I pass the "this" of a to the constructor of c and then I free the memory in the destructor. template<typename T> struct ObjectPointers { const ObjectPointers<T> *left; const ObjectPointers<T> *right; vector<T> data; // initialize left and right in constructor ObjectPointers(std::initializer_list<T> list) : data(list) { left = nullptr; right = nullptr; } ~ObjectPointers(){ // somewhere around here the error happens if(left != nullptr) delete left; if(right != nullptr) delete right; } ObjectPointers(const ObjectPointers<T> *left, const ObjectPointers<T> *right) : left(left), right(right) {} //overload + ObjectPointers operator+(const ObjectPointers &other) const { // I create a new object with the left and right of the current object return ObjectPointers<T>(this, &other); } }; int main() { ObjectPointers<int> a = {1, 2, 3}; ObjectPointers<int> b = {4, 5, 6}; ObjectPointers<int> c = a + b; return 0; } The way I understand the code that I wrote is as follows: Object c is created and points to a and b. c goes out of scope => It calls the destructor => delete a => destructor of a is called => Nothing happens => delete b => Destructor of b is called => Nothing happens => Destructor of c is done Where I wrote "Nothing happens" in reality a segmentation fault happens and I do not understand why. I also tried using smart_pointers but that did not really help. I used std::unique_ptr<>.
What's the problem? This is not a sound design, because it does not respect the usual properties of +, for example that (x+y)+z is the same than x+(y+z). If you nevertheless want to make it work, you'd need to extract the operator+ of the class, and use an overload of the binary operator+. In addition, you have to work properly with destruction, and avoid destroying an object which is still used in some of the ObjectPointers. For this you should use shared_ptr and not unique_ptr. (The advantage is that when an object gets destroyed, the shared pointer is kept alive as long as another object still uses the pointer. Your current design with raw pointers might lead multiple ObjectPointers use the same pointer, and the first ObjectPointers that gets deleted, deletes the pointer, and the others then refer to dangling pointers. This is undefined behavior and very bad) How to solve it? The code would look somewhat like this (caution, I didn't analyse if it further for other issues): template<typename T> struct ObjectPointers { const std::shared_ptr<ObjectPointers<T>> left; const std::shared_ptr<ObjectPointers<T>> right; std::vector<T> data; // initialize left and right in constructor ObjectPointers(std::initializer_list<T> list) : data(list) { } ObjectPointers(const ObjectPointers &c) = default; ~ObjectPointers(){ // no need, shared ptr take care } ObjectPointers(std::shared_ptr<ObjectPointers<T>> left, std::shared_ptr<ObjectPointers<T>> right) : left(left), right(right) {} }; And: //overload + template <class T> ObjectPointers<T> operator+ (ObjectPointers<T> a, ObjectPointers<T> b) { // I create a new object with the left and right of the current object return ObjectPointers<T>(std::make_shared<ObjectPointers<T>>(a), std::make_shared<ObjectPointers<T>>(b)); } Here an online demo, including printing of the resulting structure.
74,413,099
74,413,190
std::ostream operator implementation for a type
Why is the reason of almost always, declare the ostream operator as a friend function, and not as a member function or as a free function? What benefits have to choose to implement it as a friend compared with the alternatives?
A member function doesn't work here, because it requires the lhs to be of the enclosing class type, while you need it to be ostream. A free function would work, but it opens you up to some confusing overload resolution. A friend function behaves the same way regardless of whether caller is in the same namespace as the class (or has using namespace for it), because either way it can only be found via ADL. (I'm assuming the operator is in the same namespace as the class.) But a free function can be found without ADL, but only if you're in the same namespace. When found without ADL, it can tolerate some implicit conversions of the rhs, which wouldn't work with ADL. Example: #include <iostream> struct AA {}; struct BB {}; namespace N { struct A { A(AA) {} template <typename T, typename U> friend std::basic_ostream<T,U> &operator<<(std::basic_ostream<T,U> &o, A) {return o;} }; struct B { B(BB) {} }; template <typename T, typename U> std::basic_ostream<T,U> &operator<<(std::basic_ostream<T,U> &o, B) {return o;} } int main() { { std::cout << AA{}; // error std::cout << BB{}; // error } { using namespace N; std::cout << AA{}; // error std::cout << BB{}; // ok } }
74,413,185
74,413,253
How to correctly pass a function with parameters to another function?
I have the following code to demonstrate a function been called inside another function. The below code works correctly: #include <iostream> int thirds() { return 6 + 1; } template <typename T, typename B> int hello(T x, B y , int (*ptr)() ){ int first = x + 1; int second = y + 1; int third = (*ptr) (); ; return first + second + third; } int add(){ int (*ptr)() = &thirds; return hello(1,1, thirds); } int main() { std::cout<<add(); return 0; } Now I want to pass one number as a parameter from add function ie into thirds function (thirds(6)). I am trying this way: #include <iostream> int thirds(int a){ return a + 1; } template <typename T, typename B> int hello(T x, B y , int (*ptr)(int a)() ){ int first = x + 1; int second = y + 1; int third = (*ptr)(a) (); ; return first + second + third; } int add(){ int (*ptr)() = &thirds; return hello(1,1, thirds(6)); //from here pass a number } int main() { std::cout<<add(); return 0; } My expected output is: 11 But It is not working. Please can someone show me what I am doing wrong?
If you want add to pass a value to hello, to be passed to the function given by the pointer ptr, you have to add a separate parameter. In c++ it is usually advised to use std::function instead of old c style funtion pointers. A complete example: #include <iostream> #include <functional> int thirds(int a) { return a + 1; } template <typename T, typename B> //------------------------------------------------VVVVV- int hello(T x, B y, std::function<int(int)> func, int a) { int first = x + 1; int second = y + 1; int third = func(a); return first + second + third; } int add() { std::function<int(int)> myfunc = thirds; return hello(1, 1, myfunc, 6); } int main() { std::cout << add(); return 0; } Output: 11 Note: another solution could be to use std::bind to create a callable from thirds and the argument 6. But I think the solution above is more simple and straightforward.
74,413,819
74,448,569
In C++, how do you read a file that is embedded in an executable?
I had a photo named photo.jpg. I used xxd -i to generate a C++ file for my image file. And the output is something like this: unsigned char photo_jpg[] = {     0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01,     0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x84,...}; unsigned int photo_jpg_len = 24821; I embedded that file into my main.cpp file and built it to generate my executable. How could I possibly read that part of the hex dump which is my image file from the executable? What have I tried...? I used xxd myfile.exe > file.txt. When I examine the hex dump of my executable generated with xxd, I see that the bytes of my photo_jpg character array are somewhere in the executable. You can see that in the image below: It is a screenshot of my executable hex dump. How could I read that and store it inside of a character array like it was before being embedded into my executable?
At first, I converted my zip file to a string which was with this command: xxd -p archive.zip > myfile.txt Then I used this code to generate a multiline string in C++ of the hex dump of my zip file: #include <fstream> #include <string> int main() { std::ifstream input("file.txt"); std::ofstream output("string.txt"); std::string double_coute = "\""; std::string line; while (getline(input, line)) { std::string to_be_used = double_coute + line + double_coute + "\n" ; output << to_be_used; } output.close(); input.close(); return 0; } After that, I put the contents of string.txt inside a global variable. Using the below function I was able to write a program that generates a zip file. void WriteHexDatatoFile(std::string &hex) { std::basic_string<uint8_t> bytes; // Iterate over every pair of hex values in the input string (e.g. "18", "0f", ...) for (size_t i = 0; i < hex.length(); i += 2) { uint16_t byte; // Get current pair and store in nextbyte std::string nextbyte = hex.substr(i, 2); // Put the pair into an istringstream and stream it through std::hex for // conversion into an integer value. // This will calculate the byte value of your string-represented hex value. std::istringstream(nextbyte) >> std::hex >> byte; // As the stream above does not work with uint8 directly, // we have to cast it now. // As every pair can have a maximum value of "ff", // which is "11111111" (8 bits), we will not lose any information during this cast. // This line adds the current byte value to our final byte "array". bytes.push_back(static_cast<uint8_t>(byte)); } // we are now generating a string obj from our bytes-"array" // this string object contains the non-human-readable binary byte values // therefore, simply reading it would yield a String like ".0n..:j..}p...?*8...3..x" // however, this is very useful to output it directly into a binary file like shown below std::string result(begin(bytes), end(bytes)); std::ofstream output_file("khafan.zip", std::ios::binary | std::ios::out); if (output_file.is_open()) { output_file << result; output_file.close(); } else { std::cout << "Error could not create file." << std::endl; } } But what is the point? The point is you could have any kind of resource inside your zip file. In this way, you could generate needed resources with your program and do some stuff with them. I think that's pretty cool.
74,414,215
74,414,531
How to template creating a map for custom types
In my code I have a number of places where I need to take an std::vector of things and put it into a std::map indexed by something. For example here are two code snippets: //sample A std::map<Mode::Type, std::vector<Mode>> modesByType; for( const auto& mode : _modes ) { Mode::Type type = mode.getType(); auto it = modesByType.find( type ); if( it == modesByType.end() ) { std::vector<Mode> v = { mode }; modesByType.insert( std::pair( type, v ) ); } else { it->second.push_back( mode ); } } //sample B std::map<unsigned, std::vector<Category>> categoriesByTab; for( const auto& category : _categories ) { unsigned tabIndex = category.getTab(); auto it = categoriesByTab.find( tabIndex ); if( it == categoriesByTab.end() ) { std::vector<Category> v = { category }; categoriesByTab.insert( std::pair( tabIndex, v ) ); } else { it->second.push_back( category ); } } I'd like to generalize this and create a template function like: template<typename T, typename V> std::map<T,std::vector<V>> getMapByType( const std::vector<V>& items, ?? ) { std::map<T,std::vector<V>> itemsByType; for( const auto& item : items ) { unsigned index = ??; auto it = itemsByType.find( index ); if( it == itemsByType.end() ) { std::vector<V> v = { item }; itemsByType.insert( std::pair( index, v ) ); } else { it->second.push_back( item ); } } return itemsByType; } My question is, how do I define the ?? argument to this function so that I can call the correct V.foo() function to get the index value for the map? Note, I do not want to make all the classes that this template (V) accepts, inherit from a base class. Can I somehow specify a lambda argument?
have a pointer to a member fn as an extra parameter template<typename T, typename V> std::map<T,std::vector<V>> getMapByType( const std::vector<V>& items, T (V::*fn)()const) { std::map<T,std::vector<V>> itemsByType; for( const auto& item : items ) { T index = (item.*fn)(); auto it = itemsByType.find( index ); if( it == itemsByType.end() ) { std::vector<V> v = { item }; itemsByType.emplace( index, v ); } else { it->second.push_back( item ); } } return itemsByType; } auto res = getMapByType(items, &Category::getTab);
74,414,406
74,415,072
I cannot access a C++ class attribute using ctypes
I am using ctypes to develop a kind of Python API for a C++ library. So far, everything has been working fine. However, I upgraded my OS from Ubuntu 20.4 LTS to 22.04 (now with Python3.10.6 and g++ 11.3.0, but even with g++ 9.x.x, the following problem occurs). The problem I have now is that I get a core dumped error whenever I want to access an attribute of a C++ object. The strange thing (to me) is that it works perfectly well when I use valgrind to debug. Here is a test case that illustrates what I am saying. First, my .h (moncc.h) and my .cc (moncc.cc) files : class test { public: test() : value(0) { ; } void set_value(int lval); void print(); protected: int value; }; #include <iostream> #include "moncc.h" void test::set_value(int val) { printf("Here1\n"); value = val; printf("Here2\n"); } void test::print() { printf("valeur : %d\n",value); } extern "C" { test* CreateTest() { return new test(); } void set_value(test* obj, int val) { obj->set_value(val); } void print(test* obj) { obj->print(); } } Next, my compilation to create the test.so library: g++ -c -Wall -lstdc++ -fPIC moncc.cc -o moncc.o gcc moncc.o -shared -o test.so The wrapper.py file which defines the interface with previous extern "C" functions: #!/usr/bin/env python # coding: utf-8 import ctypes lib = ctypes.CDLL("test.so") class test(object): def __init__(self): self.obj = lib.CreateTest() def set_value(self,val): lib.set_value(self.obj,val) def print(self): lib.print(self.obj) And finally my main.py file : #!/usr/bin/env python # coding: utf-8 from wrapper import * mon_obj = test() mon_obj.set_value(5) mon_obj.print() I add the directory where test.so is in LD_LIBRARY_PATH, and here are the results : python3 main.py Here1 Erreur de segmentation (core dumped) (sorry, it's in French) But, valgrind python3 cas.py ==245604== Memcheck, a memory error detector ==245604== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==245604== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info ==245604== Command: python3 main.py ==245604== Here1 Here2 valeur : 5 ==245604== ==245604== HEAP SUMMARY: ==245604== in use at exit: 656,376 bytes in 179 blocks ==245604== total heap usage: 2,348 allocs, 2,169 frees, 3,568,710 bytes allocated ==245604== ==245604== LEAK SUMMARY: ==245604== definitely lost: 0 bytes in 0 blocks ==245604== indirectly lost: 0 bytes in 0 blocks ==245604== possibly lost: 568 bytes in 1 blocks ==245604== still reachable: 655,808 bytes in 178 blocks ==245604== suppressed: 0 bytes in 0 blocks ==245604== Rerun with --leak-check=full to see details of leaked memory ==245604== ==245604== For lists of detected and suppressed errors, rerun with: -s ==245604== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) Any idea? I really don't understand...
Set .argtypes and .restype for the functions called by ctypes. The 64-bit pointer returned by CreateTest is being truncated due to the return value defaulting to a c_int (a 32-bit integer). Working code: test.cpp #include <stdio.h> #ifdef _WIN32 # define API __declspec(dllexport) #else # define API #endif class test { int value; public: test() : value(0) { printf("Created test\n"); } ~test() { printf("Destroyed test\n"); } void set_value(int val) { value = val; } void print() { printf("value: %d\n",value); } }; extern "C" { API test* CreateTest() { return new test(); } API void DestroyTest(test* obj) { delete obj; } API void set_value(test* obj, int val) { obj->set_value(val); } API void print(test* obj) { obj->print(); } } test.py import ctypes as ct class Test: def __init__(self): self.obj = lib.CreateTest() def __del__(self): lib.DestroyTest(self.obj) def set_value(self,val): lib.set_value(self.obj, val) def print(self): lib.print(self.obj) lib = ct.CDLL('./test') class PTEST(ct.c_void_p): pass # opaque pointer aids type-checking lib.CreateTest.argtypes = () lib.CreateTest.restype = PTEST lib.DestroyTest.argtypes = PTEST, lib.DestroyTest.restype = None lib.set_value.argtypes = PTEST, ct.c_int lib.set_value.restype = None lib.print.argtypes = PTEST, lib.print.restype = None mon_obj = Test() mon_obj.set_value(5) mon_obj.print() Output: Created test value: 5 Destroyed test
74,414,472
74,414,505
Prevent templated class from using itself as instance
Suppose I have a class template template<class T> class Foo{}; Is it possible to prevent T from being an instantiation of Foo. That is, this should not compile: struct Bar{}; Foo<Foo<Bar>> x;
Another option: #include <type_traits> template <typename T> struct ValidFooArg; template <typename T> requires ValidFooArg<T>::value class Foo { }; template <typename T> struct ValidFooArg : std::true_type {}; template <typename T> struct ValidFooArg<Foo<T>> : std::false_type {}; int main() { Foo<int> x; // ok Foo<Foo<int>> y; // error }
74,414,632
74,414,798
How do I build a Visual Studio project from inside a C++ program, using system() to access command line?
I'm trying to make a Visual Studio project build/compilation from the command line, but from inside a C++ program. I can get this working if I use the command line directly and running the following: cd C:\Program Files (x86)\My Project Folder "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\\IDE\devenv.exe" MyProject.sln /Build Release The trouble is that these commands are not working from inside a C++ program using system() like so: system("cd C:\\Program Files (x86)\\My Project Folder"); system("\"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe\" MyProject.sln /Build Release"); Can anyone help me to get these commands working from inside the C++program?
You need to make a couple of changes: Each system() call is new, so you will need to use && to do multiple commands You need to escape quotation marks with \" otherwise the quotations will be used to denote a string instead of being passed to cmd You need to use 2 backslashes in the path \\ Eg. system("cd \"C:\\Program Files (x86)\\My Project Folder\" && \"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe\" MyProject.sln /Build Release"); I suggest using raw string literals for better readability. system(R"(cd "C:\Program Files (x86)\My Project Folder" && "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe" MyProject.sln /Build Release)");
74,414,827
74,415,174
Print the largest corner element in a 2-D matrix
I am trying to write a program which prints the number of the largest corner element in 2d array.So far I have written a code, it works with many different imputs, but I'm really stuck with this one and I'm not sure how to fix it. The code: #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { int n; int m; int a[10][10]; int max=0; cin>>n>>m; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin>>a[i][j];} } int topLeft=a[0][0]; int topRight=a[0][m - 1]; int lowRight=a[n - 1][m - 1]; int lowLeft=a[n - 1][0]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(topLeft > topRight && topLeft > lowRight && topLeft > lowLeft){ max=topLeft; } else if(topRight > topLeft && topRight > lowRight && topRight > lowLeft){ max=topRight; } else if(lowRight > topLeft && lowRight > topRight && lowRight > lowLeft){ max=lowRight; } else if(lowLeft > topLeft && lowLeft > topRight && lowLeft > lowRight){ max=lowLeft; } else if(m<=1){ max=topLeft; } else if(n<=1){ max=topRight; } } } cout<<""<<max<<endl; return 0; } when I input: 3 1 6 8 9 it prints: "6" instead of "9" I've tried many different inputs, but I'm stick with this one..
I believe you don't need the whole second part of your code. I mean, assume that being a 2D array, the angles are always 4. You just load them into a vector and find the maximum element. I hope I have not misunderstood the problem. Below, find the code. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n, m; int a[10][10]; cin >> n >> m; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin >> a[i][j]; } } vector<int> corner = {a[0][0], a[0][m - 1], a[n - 1][m - 1], a[n - 1][0]}; int maxEl = corner[0]; for(unsigned i = 1; i < corner.size(); i++) maxEl = max(maxEl, corner[i]); cout << "Max: " << maxEl << endl; return 0; }
74,414,850
74,414,907
Only first UDP packet sent, then connection refused
I managed to make a reproducible example (All includes from my large original source code remain). The thing is that only the first letter a is sent. Then, I get send() failed: Connection refused. I don't know what to do, this is literally the smallest code that should work. I should say that the code does not work only if I open the socket once at the beginning of the program and close it at the end of the program. If I open a socket for each individual send() and then close it right afterwards, no error comes up. #include <pcap.h> #include <cstdio> #include <getopt.h> #include <cstring> #include <cstdlib> #include <string> #include <iostream> #include <map> #include <vector> #define BUFSIZE 256 #define __FAVOR_BSD #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include<netdb.h> #include<err.h> #include <arpa/inet.h> #include <netinet/ether.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <netinet/ip_icmp.h> #include <netinet/icmp6.h> using namespace std; #define BUFFER 1024 // buffer length int sock; // socket descriptor void start_connection(){ struct sockaddr_in server, from; // address structures of the server and the client struct hostent *servent; // network host entry required by gethostbyname() memset(&server,0,sizeof(server)); // erase the server structure server.sin_family = AF_INET; // make DNS resolution of the first parameter using gethostbyname() if ((servent = gethostbyname("127.0.0.1")) == NULL) // check the first parameter errx(1,"gethostbyname() failed\n"); // copy the first parameter to the server.sin_addr structure memcpy(&server.sin_addr,servent->h_addr,servent->h_length); server.sin_port = htons(2055); if ((sock = socket(AF_INET , SOCK_DGRAM , 0)) == -1) //create a client socket err(1,"socket() failed\n"); // create a connected UDP socket if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1) err(1, "connect() failed"); } void send_data(char * string){ char buffer[BUFFER]; int msg_size,i; //send data to the server memcpy(buffer,string,2); msg_size=2; i = send(sock,buffer,msg_size,0); // send data to the server if (i == -1) // check if data was sent correctly err(1,"send() failed"); else if (i != msg_size) err(1,"send(): buffer written partially"); printf("%s",string); } int main(int argc, char *argv[]) { //Start UDP connection start_connection(); send_data("a"); send_data("b"); send_data("c"); //Close the UDP connection close(sock); return 0; }
UDP does not provide a real reliable connection. connect just sets the destination address. A send will only put the data into the send buffer and will only fail if there was a previous error on the socket. The first send will not fail, since no previous activity was done on the socket and thus not error could have happend. But ... the datagram is then send to the target system. If the target system or some firewall in between rejects the packet with ICMP unreachable, then an error will be set on the socket. This error will then be delivered to the application on the next system call on the socket - in this case the second send. Thus, what you observe will for example happen if there is no UDP server expecting packets on the specific IP and port or if some firewall is explicitly blocking the packets. As explained, you get the error only on the second send.
74,415,131
74,415,276
Undo -Werror for a particular warning
I use -Werror ... -Wno-unknown-pragmas compiler flags (cause I don't need unknown pragmas to cause an error). However, this silences all unknown pragma warnings. Is there a way to produce -Wunknown-pragmas warnings while not turning them into errors, and to apply -Werror to all other warnings.
-Werror -Wno-error=unknown-pragmas should do the trick.
74,415,260
74,415,304
I cannot understand the compiler C++ switch, invalid operand error
#include <iostream> #include <cmath> using namespace std; int main() { float Litr; int opcja; cout << "Konwerter" << endl; switch(opcja){ case 1: cout << "Litr na barylke amerykanska i galon amerykanski" << endl; cin >> Litr; cout << Litr << " litrow to " << Litr * 159 << " barylek i " << Litr * 3,78 << "galonow."; break; } return 0; } Error in line 16 (e.g cout << Litr << " litrow to " << Litr * 159 << " barylek i " << Litr * 3,78 << "galonow."; ) ||=== Build: Debug in aeiou (compiler: GNU GCC Compiler) ===| C:\Users*file loaction*\main.cpp|16|error: invalid operands of types 'int' and 'const char [9]' to binary 'operator<<'| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===| Don't understand what's wrong and what compiler tries to tell me.
In this case, they are simple syntactic errors. When you have to express a decimal number in C ++ you have to use the "." and not the ",". There was also the problem that the command to execute was not asked in input and a simple cin was inserted. #include <iostream> using namespace std; int main() { int opcja; cout << "Konwerter: "; cin >> opcja; switch(opcja) { case 1: { float Litr; cout << "Litr na barylke amerykanska i galon amerykanski" << endl; cin >> Litr; cout << Litr << " litrow to " << Litr * 159 << " barylek i " << Litr * 3.78 << "galonow."; break; } } return 0; }
74,416,100
74,416,123
find the biggest number in 2D array, except one element
I have a task to find the biggest number in 2D array, except the a[2][1] element. The input is: 4 4 2 3 4 8 5 9 6 3 9 8 4 6 4 2 3 The output should be: 9 Im getting the output 8 Since there are two 9's in the array, I dont know how to fix it. #include <iostream> #include <iomanip> using namespace std; int main() { int n; int a[10][10]; cin>>n; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>a[i][j]; } } int max=1; for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ if(a[i][j]==a[2][1]){ continue; } if(a[i][j]>max){ max=a[i][j]; } } } cout<<max<<endl; return 0; } Since there are two 9's in the array, I dont know how to skip over the a[2][1] element.
You are ignoring the value of a[2][1] you should ignore the index pair (2,1) instead: #include <iostream> #include <iomanip> using namespace std; int main() { int n; int a[10][10]; cin>>n; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>a[i][j]; } } int max=1; for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ if(i == 2 && j == 1){ continue; } if(a[i][j]>max){ max=a[i][j]; } } } cout<<max<<endl; return 0; }
74,416,249
74,416,989
Is flat_map an STL container?
In the current draft of C++23s flat_map design, the type flat_map::reference is defined as pair<const key_type&, mapped_type&>, i.e. it is not a reference to flat_map::value_type = pair<key_type, mapped_type>. (This seems to be mandatory, since the keys and values are stored not as pairs, but in two separate containers.) Thus, the iterators must be some proxy-class. This makes me think: Is a flat_map actually even an STL container, similar to std::vector<bool> isn't one?
The standard defines what a "container" is in [container.reqmts]. Among these requirements is: typename X::reference Result: T& So yes, std::flat_map is not a container. But it never claims to be; it is a "container adapter": A flat_­map is a container adaptor... Note that like std::stack/queue/priority_queue, std::flat_set/map take container types as template parameters. It should also be noted that, while they are not containers, they are ranges as defined by the C++20 range library's concepts. The C++20 ranges concepts allow for proxy ranges where the reference type need not be a value_type&.
74,416,337
74,416,452
CPP file compile in visual studio
I have a single CPP file which contains my code, however when I try to compile it specifically with build feature I can't find how and were to do it. I tried building through solution explorer but there was no option for build
Go to the Visual Studio's File Menu and choose: File Menu -> New -> Project -> Select C++ from the filter dropdown list -> Select Empty Project from the list below -> Click the Next button -> Enter the Project Name - > click the Create button. In the Solution Explorer project tree: Right-click on the Source Files leaf item -> Select Add -> Select Existing Item -> Browse to your .cpp source file -> Click the Add button. Right-click on the project's icon ( next to the name you had given it ) in the Solution Explorer Tree -> select Build. Most likely you will also have to Right-click on the project's icon in the Solution Explorer Tree and select Properties ...and set bunch of options there. Which ones and how is outside the scope of your question. Don't forget to upvote and accept this answer with the green checkmark.
74,416,345
74,416,568
Writing a sequence of numbers like: 1 22 333 4444 55555 via recursion c++
I have to write a code in c++ without loops, which would display a monotonic sequence of numbers like 1 22 333 to the number I input, so number k is repeating k times. It's like i input 6, the code would display 1 22 333 4444 55555 666666. It has to be via recursion. For now, if i cin >> 15 output is a row of numbers from 1 to 15. I have a feeling this is extremely easy but nothing crosses my mind right now. This is my attemp: #include <iostream> using namespace std; int x; void func(int n) { if(n>=1){ func(n-1); std::cout<< n << " "; } } int main() { cout << "Enter a natural number: "; cin >> x; func(x); }
There you go: #include <iostream> int x{0}; void another_func(int n, int counter) { if (counter-- > 0) { std::cout << n; another_func(n, counter); } } void func(int n) { if(n>=1){ func(n-1); another_func(n, n); //for (int i = 0; i != n; ++i) // std::cout << n; std::cout << " "; } } int main() { std::cout << "Enter a natural number: "; std::cin >> x; func(x); }
74,417,085
74,417,292
How to sort a char vector that is inside a struct
I'm looking for some guidance here. I have a project and I'm looking to sort a char vector inside a struct. I have the next struct and the main: struct employee { long Id; char name[20] }; int main () { employee data[5] for(int i=0; i<5; i++) { for(int x=i+1; x<5; x++) { if(data[i].name[0]> data[x].name[0]) { data[i].Id = data[x].Id; data[i].name = data[x].name; } } } } I'm stuck in this part. What I am trying to do is to basically sort the vector alphabetically by the name. For example: brayan should be first and carlos next. It should look like this: Employee #1 Id: 123 Name: brayan Employee #2 Id: 121 Name: Carlos I would appreciate any kind of help. The only requirement for this program is not to use std::string.
You can use std::sort with a custom comparison function, as commented. The comparison function: receives two employees, and returns true if the first name is alphabetically "smaller" than the second (i.e. strcmp returned < 0). [Demo] #include <algorithm> // sort #include <cstring> // strcmp #include <fmt/core.h> struct employee { long Id; char name[20]; }; int main() { employee data[5] { { 200, "Bryan"}, { 100, "Charles"}, { 300, "Anne"}, { 500, "Will"}, { 400, "John"} }; std::sort(data, data + std::size(data), [](const auto& e1, const auto& e2) { return strcmp(e1.name, e2.name) < 0; } ); for (auto i{0}; i < std::ssize(data); ++i) { fmt::print("Employee #{}\nId: {}\nName: {}\n\n", i+1, data[i].Id, data[i].name); } } // Outputs: // // Employee #1 // Id: 300 // Name: Anne // // Employee #2 // Id: 200 // Name: Bryan // // Employee #3 // Id: 100 // Name: Charles // // Employee #4 // Id: 400 // Name: John // // Employee #5 // Id: 500 // Name: Will
74,417,728
74,422,719
How to define a custom mock allocator?
I'm trying to define a custom std::basic_string specialization with a mock allocator to log all memory operations that basic_string performs. struct MockAllocator : std::allocator<char> { char* allocate(size_t n); void deallocate(char *p, size_t n); }; using CustomString = std::basic_string<char, std::char_traits<char>, MockAllocator>; CustomString str("Hello World........ (more symbols to avoid SSO)"); This simple code doesn't call methods of my allocator. I can even skip definitions, and linker doesn't produce any errors. What am I doing wrong?
The following assumes C++11 (and later) allocator semantics, which older compilers (even if they did otherwise implement C++11) may not have implemented fully yet. Your type doesn't satisfy the allocator requirements because it doesn't rebind properly and so there is no guarantee how the code will behave. A minimal stateless allocator looks like this: template<typename T> struct MockAllocator { using value_type = T; MockAllocator() = default; template<typename U> MockAllocator(const MockAllocator<U>&) noexcept {} T* allocate(std::size_t) { /*...*/ }; void deallocate(T*, std::size_t) { /*...*/ }; }; template<typename T, typename U> inline bool operator==(const MockAllocator<T>&, const MockAllocator<U>&) noexcept { return true; }; template<typename T, typename U> inline bool operator!=(const MockAllocator<T>&, const MockAllocator<U>&) noexcept { return false; }; and is passed as MockAllocator<char> to the std::basic_string. The template parameter is a requirement. An allocator must always be rebindable to other object types, which works automatically for templates of this form. Otherwise a rebind member must be provided. The == and != operators are a requirement. They determine whether the two allocators can deallocate memory allocated by the other. They can just return true and false respectively for a simple stateless allocator like this. Since C++20 the != overload is optional. For more complex allocators, escpecially stateful ones, other members which are currently defaulted via std::allocator_traits may be required to make it work correctly. It is not necessary to inherit from std::allocator. In fact, before C++20, inheriting from std::allocator will cause its rebind to be inherited as well, which will incorrectly rebind to std::allocator</*...*/> instead of your MockAllocator, which violates the allocator requirements. Since C++20 std::allocator doesn't have a rebind, so then your non-template MockAllocator will not be rebindable at all, again violating the requirements. The last part is probably why you see the behavior you do. Libstc++ is rebinding the allocator for char internally, which should be completely fine for a proper allocator, but your allocator rebinds to std::allocator<char> instead of MockAllocator, so that it will effectively just use std::allocator<char>.
74,418,043
74,418,109
Using the built-in C++ function to make parameter variable "seat" upper case
Am trying to make the parameter variable "seat" upper case but I keep getting errors I don't want to include bits/stdc++.h header file but am stuck trying to figure it out. I need guidance on how to make it work Error states 'transform': identifier not found these are the includes i have in the code #include <iostream> #include <fstream> #include <string> #include <ctime> #include <iomanip> #include <cctype> bool releaseSeat(string seat) { bool releaseSeatOK = false; transform(seat.begin(), seat.end(), seat.begin(), ::toupper); string passengerName = showOccupant(seat); if (passengerName.compare("seat_01A") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_01B") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_01C") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_01D") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_02A") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_02B") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_02C") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_02D") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_03A") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_03B") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_03C") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_03D") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_04A") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (seat.compare("04B") == 0) { passengerName = "seat_04B"; } else if (passengerName.compare("seat_04B") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_04C") == 0) { passengerName = "empty"; releaseSeatOK = true; } else if (passengerName.compare("seat_04D") == 0) { passengerName = "empty"; releaseSeatOK = true; } return releaseSeatOK; } I've tried what I know based on my knowledge so far since am just starting c++ This is part of 1000 lines of code I can't include every line, am just getting errors on this line
Did you include <algorithm>? std::transform is found in <algorithm> so if you didn't include it C++ doesn't know what std::transform is, hence the error. Edit: I see you don't have <algorithm> included, so just add #include <algorithm> to the top of your code and the error should disappear. Edit 2: Just iterate over each character in seat and capitalize them, like so: for (size_t i = 0; i < seat.length(); i++) { seat[i] = toupper(seat[i]); } std::transform is not necessary in this case.
74,418,172
74,418,313
Is there a way to remove reference, cv qualifiers, and pointerness of a type to make it plain?
Take the following code: struct Foo {} template<typename T> void passFoo(T t) {} I would want the domain of passFoo to be restricted to Foo objects, but I don't mind if they are references, pointers, or cv qualified. Is it possible to somehow remove all those aspects of a type to get down to the "plain" type, when using a concept? For instance: template<typename T> concept Foo_C = std::is_same_v<Foo, plainify<T>>; template<Foo_C Foo_c> void passFoo(Foo_c foo) {} In that hypothetical code, passFoo could accept only Foo, Foo&, Foo*, const Foo, etc. Is there any actual way to do this?
Combination of std::remove_cvref_t and std::remove_pointer_t would work: template<typename T> concept Foo_C = std::is_same_v<Foo, std::remove_cvref_t<std::remove_pointer_t<T>>>;
74,418,448
74,418,587
Why is a rvalue string stream working in this context but not an lvalue?
I noticed that I could do some quick and dirty translation of a narrow to a wide string by doing the following: #include <iostream> #include <sstream> int main() { using namespace std; wcout << (wstringstream{} << "This works.\n").str(); wstringstream ss{}; wcout << (std::move(ss) << "This works too.\n").str(); return 0; } But if I replaced the rvalue wstringstream with an lvalue, it doesn't work: #include <iostream> #include <sstream> int main() { using namespace std; wstringstream ss{}; wcout << (ss << "This doesn't work. :(\n").str(); return 0; } What exactly is going on here?
In the working examples the type is std::basic_stringstream which has a str() method and comes form an rvalue template of the << operator: std::__cxx11::basic_stringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >&& std::operator<< <std::__cxx11::basic_stringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, char [13]>(std::__cxx11::basic_stringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >&&, char const (&) [13]) Whereas in the non-working it is std::basic_ostream which does not have a str() method and is from the inherited class operator overload. std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& std::operator<< <wchar_t, std::char_traits<wchar_t> >(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >&, char const*)
74,418,884
74,420,237
Creating a 3D vector. C++
Help me please. I have a 3d vector. I need to make a new vector from this using existing internal indices. I hope the input and output information will be clear. Input: a = { { {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,5,5,5}, {6,6,6,6} }, { {10,10,10,10}, {20,20,20,20}, {30,30,30,30}, {40,40,40,40}, {50,50,50,50}, {60,60,60,60} }, { {100,100,100,100}, {200,200,200,200}, {300,300,300,300}, {400,400,400,400}, {500,500,500,500}, {600,600,600,600} }, }; Output: b = { {{ 1,1,1,1}, {10,10,10,10}, {100,100,100,100}}, {{ 2,2,2,2}, {20,20,20,20}, {200,200,200,200}}, {{ 3,3,3,3}, {30,30,30,30}, {300,300,300,300}}, {{ 4,4,4,4}, {40,40,40,40}, {400,400,400,400}}, {{ 5,5,5,5}, {50,50,50,50}, {500,500,500,500}}, {{ 6,6,6,6}, {60,60,60,60}, {600,600,600,600}}, } I don't know how to iterate over indices in a 3D array to create a new 3D array (Output). I want to create a 3D vector from the columns (n-indices) of an existing 3D vector. I have a 3D vector ('Input'). I need to make a 3D vector out of this ('Output'). #include <iostream> #include <vector> using namespace std; void show3D_vector(std::vector<std::vector<std::vector<double>>>& a); void show2D_vector(std::vector<std::vector<double>>& a); template<typename T> std::vector<std::vector<T>> SplitVector(const std::vector<T>& vec, size_t n); int main() { a = { { {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,5,5,5}, {6,6,6,6} }, { {10,10,10,10}, {20,20,20,20}, {30,30,30,30}, {40,40,40,40}, {50,50,50,50}, {60,60,60,60} }, { {100,100,100,100}, {200,200,200,200}, {300,300,300,300}, {400,400,400,400}, {500,500,500,500}, {600,600,600,600} }, }; } void show3D_vector(std::vector<std::vector<std::vector<double>>>& a) { for (double i = 0; i < a.size(); ++i) { for (double j = 0; j < a[i].size(); ++j) { for (double k = 0; k < a[i][j].size(); ++k) std::cout << a[i][j][k] << " "; std::cout << endl; } std::cout << endl; } } void show2D_vector(std::vector<std::vector<double>>& a) { for (int i = 0; i < a.size(); i++) { for (auto it = a[i].begin(); it != a[i].end(); it++) { std::cout << *it << " "; } std::cout << endl << endl; } } template<typename T> std::vector<std::vector<T>> SplitVector(const std::vector<T>& vec, size_t n) { std::vector<std::vector<T>> outVec; size_t length = vec.size() / n; size_t remain = vec.size() % n; size_t begin = 0; size_t end = 0; for (size_t i = 0; i < std::min(n, vec.size()); ++i) { end += (remain > 0) ? (length + !!(remain--)) : length; outVec.push_back(std::vector<T>(vec.begin() + begin, vec.begin() + end)); begin = end; } return outVec; } Thank you.
You can solve this matrix transpose more succinctly. for(const auto& a1 : a){ b.resize(a1.size()); auto b1 = b.begin(); for(const auto& a2 : a1){ b1->push_back(a2); b1++; } } output is {{1,1,1,1,},{10,10,10,10,},{100,100,100,100,},}, {{2,2,2,2,},{20,20,20,20,},{200,200,200,200,},}, {{3,3,3,3,},{30,30,30,30,},{300,300,300,300,},}, {{4,4,4,4,},{40,40,40,40,},{400,400,400,400,},}, {{5,5,5,5,},{50,50,50,50,},{500,500,500,500,},}, {{6,6,6,6,},{60,60,60,60,},{600,600,600,600,},},
74,418,999
74,419,709
Templated template function as input parameter to function in C++
I have several classes which all receive raw data on the form of an uint8 buffer, and the underlying datatype of the data in the buffer is decided at runtime. The buffer needs to go through a converter function that's templated, and decided in a big switch statement at runtime, depending on the received data type which templated version of the converter function that's going to be executed. So I have one 'inner' converter function, and one 'outer' switch function that calls different templated versions of the 'inner' function, depending on the data type that the underlying data had. Since the 'inner' converter functions all look a bit different, I have until now had a separate 'outer' function for every 'inner' function. Now I want to do a more general 'outer' function that can take the the 'inner' function as an input argument. But I'm a bit stuck on how to do the templating. This is my current approach: struct InputParams { size_t num_elements; size_t num_bytes_per_vec; }; struct OutputData { float *q0; float *q1; }; template <typename T> OutputData testFunction(const uint8_t* const input_data, const InputParams& input_params) { OutputData output; // Allocate 'output' in some way... const T* const t_ptr = reinterpret_cast<const T* const>(input_data); for(size_t k = 0; k < input_params.num_elements; k++) { output.q0[k] = input_data[k]; output.q1[k] = ... // ... } return output; } template <typename O, template <typename> typename F, typename T, typename I> O applyFunctionForDataType(const uint8_t* const input_data, const DataType data_type, const F<T>& converter_function, const I& input_params) { O output_data; if (data_type == DataType::FLOAT) { output_data = converter_function<float>(input_data, input_params); } else if (data_type == DataType::DOUBLE) { output_data = converter_function<double>(input_data, input_params); } else if (data_type == DataType::INT8) { output_data = converter_function<int8_t>(input_data, input_params); } else if ... return output_data; } The template arguments typename O and typename I are for the output data structure, and input parameters, as these differ depending on which function that will call all of this. In one use case, OutputData might have two float pointers, in another a float pointer and an int pointer. InputParams will probably always be pretty similar, but I figured I might as well have that as a template arguments, since OutputData already is one. Calling applyFunctionForDataType: InputParams input_params; OutputData oo = applyFunctionForDataType<OutputData>(data_ptr_, data_type_, testFunction, input_params); I get the following error message from the compiler: <source>:68:23: error: 'converter_function' does not name a template but is followed by template arguments output_data = converter_function<float>(input_data, input_params); ^ ~~~~~~~ <source>:61:40: note: non-template declaration found by name lookup const F<T>& converter_function, Compiler test Alternative solutions are of course welcome.
You cannot pass function templates to your template. You could however pass an object providing a template function: template <typename O, typename Converter, typename I> O applyFunctionForDataType(const uint8_t* const input_data, const DataType data_type, Converter&& converter, const I& input_params) { O output_data; if (data_type == DataType::FLOAT) { output_data = std::forward<Converter>(converter).template Convert<float>(input_data, input_params); } else if (data_type == DataType::DOUBLE) { output_data = std::forward<Converter>(converter).template Convert<double>(input_data, input_params); } else if (data_type == DataType::INT8) { output_data = std::forward<Converter>(converter).template Convert<int8_t>(input_data, input_params); } return output_data; } struct TestFunctionConverter { template<class T> OutputData Convert(const uint8_t* const inputData, const InputParams& inputParams) const { return testFunction<T>(inputData, inputParams); } }; int main() { ... OutputData oo = applyFunctionForDataType<OutputData>(input_data, dt, TestFunctionConverter{}, input_params); } Alternatively you could pass a type as template template parameter, that provides a function for conversion: template <typename O, template <typename> class Converter, typename I> O applyFunctionForDataType(const uint8_t* const input_data, const DataType data_type, const I& input_params) { O output_data; if (data_type == DataType::FLOAT) { output_data = Converter<float>{}(input_data, input_params); } else if (data_type == DataType::DOUBLE) { output_data = Converter<double>{}(input_data, input_params); } else if (data_type == DataType::INT8) { output_data = Converter<int8_t>{}(input_data, input_params); } return output_data; } template<class T> struct TestFunctionConverter { OutputData operator()(const uint8_t* const inputData, const InputParams& inputParams) const { return testFunction<T>(inputData, inputParams); } }; int main() { ... OutputData oo = applyFunctionForDataType<OutputData, TestFunctionConverter>(input_data, dt, input_params); ... }
74,419,992
74,420,151
Can't print cyrillics cahracters in terminal
I have an labaratoly work from my university - I have to print ASCII table with ukrainian symbols, then make transliteration from ukrainian to english but I have met problems that I expalined here. I think than I have tried everething I could and it wont work. Please help me.
This is a rtf for Ukrainian Character Set KOI8-U : https://www.rfc-editor.org/rfc/rfc2319.html .... You can map your std ascii table to the required cyrillic characters. Another option is to look at something like yandex. https://yandex.com/dev/translate/ it is an api for translating but I think its a service that charges but there is usage limits or just a temporary key if not paid for. It's pretty useful for translating and an easy api.
74,420,848
74,420,882
How does Name lookup work when using multiple inheritance in C++?
Why does the following work(I know it would not work when d.f(5)): #include <string> #include <iostream> struct A { int f(int a) { return a*a; } }; struct B : A { std::string f(std::string string) { return "Hello " + string; } }; struct Derived : B {}; int main() { Derived d; std::cout << d.f("5") << std::endl; return 0; } and the following doesnt: #include <string> #include <iostream> struct A { int f(int a) { return a*a; } }; struct B { std::string f(std::string string) { return "Hello " + string; } }; struct Derived : B, A {}; int main() { Derived d; std::cout << d.f("5") << std::endl; return 0; } You could make the last example work by adding: using A::f; using B::f; in Derived, but shouldnt the compiler just check either A or B which would be the same case as in the first example? Edit: Here is the error message: main.cpp: In function ‘int main()’: main.cpp:11:19: error: request for member ‘f’ is ambiguous 11 | std::cout << d.f("5") << std::endl; | ^ main.cpp:4:16: note: candidates are: ‘int A::f(int)’ 4 | struct A { int f(int a) { return a*a; } }; | ^ main.cpp:5:24: note: ‘std::string B::f(std::string)’ 5 | struct B { std::string f(std::string string) { return "Hello " + string; } }; | ^ Edit 2: I think I phrased my question wrong, the question was more about the how exactly the compiler differentiates between multiple inheritance and single inharitance when perfoming name lookup. Edit 3: I got it now, thanks.
In the former case the class does not have a method whose name matches the method name getting called. Next, the class is derived from a class, and the derived-from class has a method with the matching name, which satisfies the name getting looked up. In the latter case the class is derived from two other classes, and both of them have a method with the matching name. The name lookup is now ambiguous. but shouldnt the compiler just check either A or B It is not up to the compiler to decide this. This rules for name lookups are specified in the C++ standard, and the compiler must follow the name lookup rules.
74,420,853
74,420,913
Vector of object pointers recursive function using next object pointer in vector
I have a vector (vector<Spell *> spells;) and I want to be able to call the cast() function on the first element of the vector and have the spells cast the Spell* in the vector but the program will reach me->cast(me, pos, 0.0f, capacity-1, draw); and run into a segmentation fault, crashing the program. My code: #include <iostream> #include <vector> using namespace std; typedef struct Vector2 { float x; float y; } Vector2; class Spell { protected: Vector2 pos; string name; public: Spell() { pos = {1, 2}; name = "Empty Slot"; } virtual void cast(Spell *me, Vector2 from, float angle, int capacity, int draw) { cout << name << " cast (virtual)" << endl; if (draw > 0 && capacity > 0) { me++; me->cast(me, pos, 0.0f, capacity-1, draw); } } }; class SparkBolt : public Spell { public: SparkBolt () { pos = {0, 0}; name = "Spark Bolt"; } void cast(Spell *me, Vector2 from, float angle, int capacity, int draw) { cout << name << " cast" << endl; if (draw > 0 && capacity > 1) { me++; me->cast(me, pos, 0.0f, capacity-1, draw-1); } } }; class SpellStorage { private: int capacity; vector<Spell *> spells; public: explicit SpellStorage(int capacity) { SpellStorage::capacity = capacity; for (int i = 0; i < capacity; i++) { spells.emplace_back(new Spell()); } } void insertSpell(Spell *spell, int slot) { spells.at(slot-1) = spell; } void cast() { spells.at(0)->cast(spells.at(0), {3.0f, 4.0f}, 0.0f, capacity, 1); } }; //------------------------------------------------------------------------------------ // Program main entry point //------------------------------------------------------------------------------------ int main() { SpellStorage test = SpellStorage(5); test.insertSpell(new SparkBolt(), 4); test.cast(); return 0; } Before I realised that the vector had to be a vector of Spell pointers for the Cast() polymorphism to work, the code worked fine but would return a sigsev fault after casting the last Spell in the vector. I am expecting the program to print: Empty Slot cast (virtual) Empty Slot cast (virtual) Empty Slot cast (virtual) Spark Bolt cast or Empty Slot cast (virtual) Empty Slot cast (virtual) Empty Slot cast (virtual) Spark Bolt cast Empty Slot cast (virtual) if draw = 2 (so the entire vector is cast)
me++ increments the pointer but me isn't a pointer to an array so your code has undefined behaviour. Each pointer in your vector is unreleated to the rest and you can't use pointer arithmetic to traverse between them. You'd be better of using iterators instead: #include <iostream> #include <vector> using namespace std; typedef struct Vector2 { float x; float y; } Vector2; class Spell { protected: Vector2 pos; string name; public: Spell() { pos = { 1, 2 }; name = "Empty Slot"; } virtual void cast(std::vector<Spell*>::iterator me, Vector2 from, float angle, int capacity, int draw) { if (draw > 0 && capacity > 0) { cout << name << " cast (virtual)" << endl; me++; (*me)->cast(me, pos, 0.0f, capacity - 1, draw); } } }; class SparkBolt : public Spell { public: SparkBolt() { pos = { 0, 0 }; name = "Spark Bolt"; } void cast(std::vector<Spell*>::iterator me, Vector2 from, float angle, int capacity, int draw) { if (draw > 0 && capacity > 1) { cout << name << " cast" << endl; me++; (*me)->cast(me, pos, 0.0f, capacity - 1, draw - 1); } } }; class SpellStorage { private: int capacity; vector<Spell*> spells; public: explicit SpellStorage(int capacity) { SpellStorage::capacity = capacity; for (int i = 0; i < capacity; i++) { spells.emplace_back(new Spell()); } } void insertSpell(Spell* spell, int slot) { spells.at(slot - 1) = spell; } void cast() { spells.at(0)->cast(spells.begin(), { 3.0f, 4.0f }, 0.0f, capacity, 1); } }; //------------------------------------------------------------------------------------ // Program main entry point //------------------------------------------------------------------------------------ int main() { SpellStorage test = SpellStorage(5); test.insertSpell(new SparkBolt(), 4); test.cast(); return 0; } You'll also need to check the capacity before recursing to ensure you don't dereference the past the end iterator: if (capacity > 1) { (*me)->cast(me, pos, 0.0f, capacity - 1, draw); }
74,421,150
74,424,685
Why does std::basic_string have two separate template parameters _Elem (char type) and _Traits (char traits)?
The problem is I don't understand why those should be separate. Why not use one class, like CharType, that would contain both the logic of char traits and char type. I mean replace that: template <class _Elem, class _Traits = char_traits<_Elem>, class _Alloc = allocator<_Elem>> class basic_string { /*...*/ }; with that: template <class ExtendedTraits, class _Alloc = allocator<_Elem>> class basic_string { /*...*/ }; where ExtendedTraits is the presaid combination of _Elem and _Traits, that might look like that: template<_CharType> //all the necessary template parameters class extended_traits { public: using value_type = _CharType; private: _CharType _elem; public: //... all methods, that used to be in char_traits but now non-static and accepting one parameter }; I tried to implement both approaches, both of them do work, but there may be some problems I still do not notice.
I think it makes more sense to separate the character type from the Traits object. Traits is an additional class for character comparisons and such, which is inherently different from the character type. Your method would work, but the equivalent would be like combining two completely different functions into the same function. It's also more immediately obvious what character type the string is using. For example: typedef string basic_string<char>; is much more obvious than typedef string basic_char<extended_traits<char>, ...>; as there is an additional level of nesting and more characters and such. At the end of the day, we don't care about what Traits is, we care about what character type the string is. Traits is for internal operations, and is meant to be abstracted away; as such, it's kept away from the character type, which is meant to be more obvious as it indicates what types of values the string can contain. At least, that's my view on things. Besides, it's not necessarily a bad thing to have more template arguments for std::basic_string, especially since there's only ever one template argument you really need to define a parameter for - the other template are given default types. It's not often that I would need to define my own Traits class. But if I wanted to define my own separate string class with a custom character or something like that, I would have to define a Traits class for it, even if I have written my assignment operator and comparison operators and everything else. That would be especially irritating.
74,421,315
74,421,459
How to i get my Array to output its random generated values from 0 - 99
I wanted to make a function called fillArray to set up random values to the Array. Then i wanted the function to output all the values but i kept getting values way above 99. This is what i have written so far: #include <ctime> #include <iostream> using namespace std; void fillArray(){ srand(time(NULL)); const unsigned int sizeOfArray = 10; // this sets the array to the constant size of 10 int numberArray[sizeOfArray]; //this sets the array to the size of 'sizeOfArray' which is 10 for(int i = 0; i < sizeOfArray; i++) { numberArray[i] = rand() % 100; cout << numberArray[i] << endl; } } int main (){ void fillArray(int a[10], int randNum); cout << numberArray[0] << " , " << numberArray[1] << " , " << numberArray[2] << " , " << numberArray[3] << " , " << numberArray[4] << " , " << numberArray[5] << " , " << numberArray[6] << " , " << numberArray[7] << " , " << numberArray[8] << " , " << numberArray[9] << '\n'; } I understand the name numberArray hasnt been declared in the main function but just wondered what to do.
So, your error is simple: You have declared a function in the main function like this: int main() { void fillArray(int a[10], int random); } But it should have been int main() { fillArray(int a[10], int random); } Which is calling the fillArray function Also there are a few other things that i would like to add, instead of fillArray taking nothing it should take an array like this template<auto Size> void fillArray(int (&arr)[Size]) { // Implemenatation } and also, it should not take a random number the function can do that in the function body. When you are printing your array, you should use a loop or a specialized function to do it like this: template<auto Size> auto PrintArray(int (&arr)[Size]) { for(int i = 0; i < Size; i++) { std::cout << arr[i] << ", "; } std::cout << "\n"; } So, your final code would be something like the following: #include <ctime> #include <iostream> using namespace std; template<auto Size> void fillArray(int (&numberArray)[Size]){ srand(time(NULL)); for(int i = 0; i < Size; i++) { numberArray[i] = rand() % 100; } } template<auto Size> auto PrintArray(int (&arr)[Size]) { for(int i = 0; i < Size; i++) { std::cout << arr[i] << ", "; } std::cout << "\n"; } int main (){ int numberArray[10]; void fillArray<10>(numberArray); PrintArray<10>(numberArray); }
74,421,337
74,421,658
The program's structure is different from the output
I decided to write the code in such a manner where both inputs are from the user and the system adds the value to give the sum of the 2 values provided by the user. but the out is different from what I expected it to do. please refer to the respective attached block of the result *I really hope that someone could help me understand what exactly is going on with the block of code I have written, Please also help me with typing the code more efficiently -` Please refer to my code and attachments Here is my actual code ` #include <iostream> #include <string> using namespace std; int main() { int nm1, nm2; cout<<"Your numbers please"; cin >> nm1, nm2 ; cout << nm1 + nm2; return 0 ; } ` I was expecting a sum and it gave me some sort of a big surprise PS E:\programmes\C programming> cd "e:\programmes\C programming" ; if ($?Your numbers please1 2 4201052 PS E:\programmes\C programming> cd "e:\programmes\C programming" ; if ($?) { g++ c++intros2.cpp -o c++intros2 } ; if ($?) { .\c++intros2 } Your numbers please1 4201052 I also hope that someone could give me some intel and also provide me with a good and more efficient code instead of referring me to this one - ` #include <iostream> #include <string> using namespace std; int main() { int nm1, nm2; cout<<"Your numbers please"; cout << "Your 1st number please"; cin >> nm1 ; cout << "Your 2nd number please"; cin >> nm2 ; cout << nm1 + nm2; return 0 ; } ` Thanking you
If you take a good look of both your codes, you can see where the main problem is; The difference (beside cout comments) are into these lines: cin >> nm1, nm2; and cin >> nm1; cin >> nm2; And the reason you got a big surprise is that you misread(incorrect syntax) multiple integers from the input stream; You can use commas like that int nm1, nm2, nm3, nm4; and declare multiple integers, but you need different syntax while reading or writing - which would be: cin >> nm1 >> nm2; and does same as cin >> nm1; cin >> nm2; Same goes for cout for better understanding - cout << "Your Sum is "; cout << nm1+nm2; and cout << "Your sum is " << nm1+nm2; will do the same. And probably you should try the suggested links in the comments too, like: How Comma Operator works What exactly are cout/cin What is the << operator for in C++
74,422,217
74,422,260
Vector of an array of structs resets strings to be blank. C++
So I'm having a very confusing issue where I'm attempting to print a string from a vector of arrays of structs to the console. Integers print just fine however strings stored within these structs get set to "". I have no idea what's going on here but after setting up a test as shown bellow this issue is still persisting. Any help figuring this out would be greatly apricated. Should also mention I'm still new to c++ so I apologise if the issue here is something simple. #include <iostream> #include <string> #include <vector> #include "Header.h" //Test struct struct testStruct { string testString; int testInt; }; testStruct testArray[1] = { testArray[0] = {"String works", 69} }; int main() { srand(time(NULL)); vector < testStruct > test; test.push_back({ testArray[0] }); cout << test[0].testString << "\n"; // prints "", should print "String works" cout << test[0].testInt << "\n"; // prints 69 characterCreation(); checkPlayerStats(); introduction(); return 0; }
This surprised me. The following code is legal (syntactically at least) testStruct testArray[1] = { testArray[0] = {"String works", 69} }; but if you replace it with the sensible version testStruct testArray[1] = { {"String works", 69} }; then your program works as expected. I expect your version has undefined behaviour because you are assigning (here testArray[0] = ...) to an array element that has not yet been created.
74,422,385
74,422,579
Delete Even Numbers From A Linked List C++
I can't seem to understand what am I missing, I've spent hours and hours looking at this and everything I tried doesn't work. My thought process to check if the second node of the list is even, if it is then to link the first and third node and delete the second but it doesn't work... I've been stuck at this for a week. void delete_even() { nod *aux; if (head == NULL) { cout << "List doesn't exist!"; } else { nod *curent; current = head; while (curent) { if (curent->next->info % 2 == 0) { curent = curent->next->next; curent->next = aux; delete aux; break; } else { curent = curent->next; } } } } I don't know what else to do.
There are several things wrong with this code. Your use of curent->next invokes undefined behavior when curent is pointing at the last node in the list, since next will be NULL in that case. It is are causing you to skip the 1st node in the list. You never assign aux to point at anything, so calling delete on aux is also undefined behavior. Even if aux were pointing at a valid node, you are assigning aux to curent->next right before deleting the node that aux is pointing at, thus leaving curent->next pointing at invalid memory, which is also undefined behavior. If you did manage to remove a node from the list, you are breaking the loop immediately afterwards, so you would be removing only one even number from the list, not removing all even numbers, as your title suggests you want to do. Try something more like this instead: void delete_even() { if (!head) cout << "List is empty!"; else { nod *curent = head, *prev = NULL; while (curent) { nod *next = curent->next; if (curent->info % 2 == 0) { if (prev) prev->next = next; else head = next; delete curent; } else { prev = curent; } curent = next; } } } Alternatively: void delete_even() { if (!head) cout << "List is empty!"; else { nod *curent = head; nod **prev = &head; while (curent) { if (curent->info % 2 == 0) { *prev = curent->next; delete curent; } else { prev = &(curent->next); } curent = *prev; } } }
74,423,083
74,423,142
Determining the return type of a class method without warning on gcc
I would like to alias a return type for a templated class method, on clang I use template <class R, unsigned int BlockSize> struct block { using KeyType = decltype(((R*)nullptr)->getKey()); } This works fine on clang, but on gcc 11.3.0 I get a warning: warning: ‘this’ pointer is null [-Wnonnull] My question is what is the proper way to get the KeyType without warning?
To be able to use member functions in unevaluated contexts such as decltype expressions one should use std::declval: template <class R, unsigned int BlockSize> struct block { using KeyType = decltype(std::declval<R>().getKey()); }
74,423,293
74,423,305
Creating a public variable from another class (C++)
If you have two classes, class a and class b, could you create a variable in class a from class b? main.cpp class A { public: A() {} }; class B { public: B() { test = A(); test.<variable name> = <variable value>; } }; The code above is just an example. It will probably cause an error. "variable name" doesn't exist in class A. Is there a way to create this variable for class A in the constructor for class B?
No, C++ is not Javascript. Types are strict and, after you define a type, there's no way to modify it. You can, however, create a local type in a function: class B { public: B() { struct A_extended : A { int i; }; auto test = A_extended(); test.i = 1; } };
74,423,550
74,423,575
How to remove the last \n from a file?
I write a table to a file, using simple: ofstream myfile; myfile.open("file.txt"); myfile << "rho P \n"; for (j = 0; j < blocksize; j++) { myfile << rho[j] << " " << P[j] << "\n"; } myfile.close(); The problem is the last "\n" that creates a new line I don't like. how to remove it?
ofstream myfile; myfile.open("tabulated/QEOS.txt"); myfile << "rho (g/cm^-3) P (GPa); T="<<T<<"\n"; for (j = 0; j < blocksize; j++) { myfile << rhoiterp[j] << " " << Piterp[j]; if(j < blocksize - 1) myfile << "\n"; } myfile.close(); We are printing "\n" exactly before the last element, we are skipping the last element using a conditinal statement.
74,423,660
74,423,921
While loop will only terminate if I use CTRL + C on the terminal
The prompt of the question is: Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (for example, a space, carriage return, newline) or borders the beginning or end of the file. I have successfully gotten the program to count how many words are in a file; no issues there. #include <fstream> #include <iostream> #include <cstdlib> #include <string> int main() { char file_name[16]; std::ifstream in_stream; int count = 0; char ch; bool lastWasWhite = true; std::string next; // Ask the user for the file name std::cout << "What is the name of the file? "; std::cin >> file_name; in_stream.open(file_name); // See if we can open the file if (!in_stream.is_open()) { std::cout << "Something went wrong when opening your file."; exit(1); } // Read the file, one character at a time while (in_stream >> next) { do { std::cin.get(ch); } while (ch != ' ' && ch != '\n' && ch != '\t'); ++count; } in_stream.close(); std::cout << "The file " << file_name << " contains " << count << " words." << std::endl; return 0; } The only problem is that the only way for the program, or I think the "while loop" to finish, is for me to hit CTRL + C on the terminal so it force stops. Then I get the result I want. This is my first post, so please let me know if there is any other information you would like to see.
Your outer loop is reading words from the file and counting them just fine (operator>> handles the whitespace for you). However, your outer loop is also running an inner loop that is reading user input from stdin (ie, the terminal). That is where your real problem is. You are waiting on user input where you should not be doing so. So, simply get rid of the inner loop altogether: while (in_stream >> next) { ++count; } That is all you need.
74,423,675
74,424,787
terminate called after throwing an instance of 'std::length_error' what(): basic_string::_M_create
The problem is to reverse words in a string ... Eg. - This is Nice Output -Nice is This so here's the error terminate called after throwing an instance of 'std::length_error' what(): basic_string::_M_create Here's my actual code, don't know where it went wrong I just started c++, but I'm sure I'm trying to access an index that isn't defined. Pls correct me if I'm wrong string reverseWords(string s) { vector<string> v; string x=""; for(int i=0;i<s.size();i++) { if(isspace(s[i])) { v.push_back(x); x=""; v.push_back(" "); } else { x=x+s[i]; } } v.push_back(x); x=""; for(int j=v.size();j>=0;j--) x=x+v[j]; return x; }
Your approach is inefficient. Also you are not reversing the source string but building a new string in the reversed order. The compound statement of the if statement if(isspace(s[i])) { v.push_back(x); x=""; v.push_back(" "); } does not make great sense when the source string contains adjacent spaces because it appends empty strings to the vector. Also if the last character of the string is space then this statement after the for loop v.push_back(x); again appends a redundant empty string to the vector. This for loop for(int j=v.size();j>=0;j--) x=x+v[j]; invokes undefined behavior when j is equal to v.size(). If you are dealing with an object of the type std::string then you should use methods of the class and standard algorithms as for example the algorithm std::reverse. Here is a demonstration program that shows how a string can be reversed. #include <iostream> #include <string> #include <iterator> #include <algorithm> std::string & reverseWords( std::string &s, const char *delim = " \t" ) { auto first = s.find_first_not_of( delim ); if (first != std::string::npos) { auto last = s.find_last_not_of( delim ) + 1; std::reverse( std::next( std::begin( s ), first ), std::next( std::begin( s ), last ) ); while ( first != last ) { auto pos = s.find_first_of( delim, first ); if (pos == std::string::npos) pos = last; std::reverse( std::next( std::begin( s ), first ), std::next( std::begin( s ), pos ) ); first = pos; if ( first != last ) first = s.find_first_not_of( delim, first ); } } return s; } int main() { std::string s( "The quick brown fox jumps over the lazy dog" ); std::cout << s << '\n'; std::cout << reverseWords( s ) << '\n'; } The program output is The quick brown fox jumps over the lazy dog dog lazy the over jumps fox brown quick The
74,424,110
74,424,220
My VS Code is showing wrong error messages
Have no idea what is wrong, any thoughts and answers will be helpful. The compiler is showing errors when there aren't any.
left and right are variables of the class called Node: Node * left; Node * Right; You used a variable as a function, which causes the error. To solve the error use: Line 30 a.setLeft(b); Line 31 a.setRight(c); Also, on line 18, you’re trying to setRight() but you change the variable of left. It must be right = &n.
74,424,386
74,424,516
How to play gif in qt cpp?
I want to show a gif on the screen until an action is finished. As far as I understand from the examples, I tried something like this, but the gif does not appear on the screen. How can I do that? QMovie *movie=new QMovie(":/images/loading.gif"); if (!movie->isValid()) { qDebug()<<"Movie is not valid"; } // Play GIF QLabel *label = new QLabel(this); label->setMovie(movie); movie->start();
You need an event loop. Bracket your code with a QApplication creation and exec... QApplication app(argc, argv); QMovie movie(":/images/loading.gif"); if (!movie.isValid()) { qDebug() << "Movie is not valid"; } // Play GIF QLabel label; label.setMovie(&movie); movie.start(); app.exec();
74,424,854
74,425,317
Pass private variable to non-member function on separate thread
I am passing a private variable from a class function to a thread executing a function not part of the class. The function call works without problems when executed normally, but when I try to execute it using a separate thread, I get the error message "static assertion failed". Does anyone know what I'm doing wrong here? I've added an example program below, which calls a function (do_something()) from a class (A) that launches a thread (th1) with a non-member function (outside()). #include <iostream> #include <vector> #include <thread> void outside(std::vector<int>& array) { for (int i = 0; i < array.size(); i++) { printf("array[%d] = %d\n", i, array[i]); } } class A { public: void do_something(); private: std::vector<int> array = { 3, 4, 5 }; }; void A::do_something() { outside(this->array); // This works. std::thread th1(outside, this->array); // This doesn't work. th1.join(); } int main() { A example; example.do_something(); return 0; } The compilation of this program results in the following error message: In file included from main.cpp:3: /usr/include/c++/9/thread: In instantiation of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<int>&); _Args = {A*, std::vector<int, std::allocator<int> >&}; <template-parameter-1-3> = void]’: <span class="error_line" onclick="ide.gotoLine('main.cpp',20)">main.cpp:20:47</span>: required from here /usr/include/c++/9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues 120 | typename decay<_Args>::type...>::value, | ^~~~~ /usr/include/c++/9/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (*)(std::vector<int, std::allocator<int> >&), A*, std::vector<int, std::allocator<int> > > >’: /usr/include/c++/9/thread:131:22: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<int>&); _Args = {A*, std::vector<int, std::allocator<int> >&}; <template-parameter-1-3> = void]’ <span class="error_line" onclick="ide.gotoLine('main.cpp',20)">main.cpp:20:47</span>: required from here /usr/include/c++/9/thread:243:4: error: no type named ‘type’ in ‘struct std::thread::_Invoker >&), A*, std::vector > > >::__result >&), A*, std::vector > > >’ 243 | _M_invoke(_Index_tuple<_Ind...>) | ^~~~~~~~~ /usr/include/c++/9/thread:247:2: error: no type named ‘type’ in ‘struct std::thread::_Invoker >&), A*, std::vector > > >::__result >&), A*, std::vector > > >’ 247 | operator()() | ^~~~~~~~
All values passed to the constructor of std::thread are moved or copied. You can find this in the documentation. The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with std::ref or std::cref). If you think about the call of the constructor here std::thread th1(outside, this->array); there is no way to be explicit about if you want the array to be passed by value or by reference here. You could argue that it should look at the function signature and default to whatever the signature does, but that could potentially be confusing as well. Seems like the decision was made to always assume copy/move, if you want to pass by ref you need to be explicit about it with std::ref/std::cref.
74,425,128
74,425,476
Trying to understand: clang's side-effect warnings for typeid on a polymorphic object
This question is not about how to avoid the described warning. (Store in a reference beforehand; Or use dynamic_cast instead of typeid) I'm trying to understand why the warning exists in the first place. What is it trying to protect from? Consider the following code example: #include <memory> #include <iostream> struct A { virtual ~A() = default; }; struct B : A { }; A *get_pa() { static A static_a{}; return &static_a; } int main() { std::shared_ptr<A> pa1 = std::make_shared<B>(); A *pa2 = new B{}; //1) warning: will be evaluated std::cout << typeid(*pa1).name() << '\n'; //2) okay std::cout << typeid(pa1.get()).name() << '\n'; //3) okay std::cout << typeid(*pa2).name() << '\n'; //4) warning: will be evaluated std::cout << typeid(*new A{}).name() << '\n'; //5) warning: will not be evaluated std::cout << typeid(new A{}).name() << '\n'; //6) warning: will be evaluated std::cout << typeid(*get_pa()).name() << '\n'; //EDIT 1: //7) okay std::cout << typeid(get_pa()).name() << '\n'; } Compile this code with clang and you'll get the following kind of warning: warning: expression with side effects will be evaluated despite being used as an operand to 'typeid' [-Wpotentially-evaluated-expression] std::cout << typeid(*pa1).name() << '\n'; ^ I think I understand the general premise of that warning: typeid will actually evaluate the expression these cases, and we might not be aware of that. The expression involves a polymorphic reference. Even if its class doesn't cause any side-effects, classes that inherit from it might have side-effects. The expression *pa1, is equivalent to *pa1.get() which calls a function returning a pointer. We might not notice/consider the fact that the dereferencing is overloaded (We might've thought it was a raw pointer, or maybe the code originally used a raw pointer and was later changed to use a smart pointer) All of the warned expressions take a pointer to A* and dereference it (except for example 5). How can dereferencing a pointer cause a side-effect? And why don't we get a warning for the expressions that don't dereference? EDIT 2: Could you give an example of a class inheriting from A that would cause a side effect where it gives a warning it might happen, but not cause a side effect where it doesn't give such a warning? EDIT: Considering the answers & comments, the question in EDIT 2 is very likely a red herring, and the answer most likely involves value category rules and typeid rules, rather than directly involving polymorphism and its potential for overrides. EDIT 3: Observations: As examples 6 & 7 show. The compiler doesn't really care about the expression returning a pointer to a polymorphic object having a potential side effect, but rather, it cares about the dereferencing of it having a side effect. Whether we dereference a pointer or a smart pointer doesn't seem to matter, so it doesn't seem to be about overriding the dereferencing operation. If we make A non-polymorphic (remove the virtual destructor definition) it would not show the warning for evaluating with a potential side effect (it still shows the opposite warning for example 4,5) further emphasizing that the problem is not with an expression returning a pointer but with the dereferencing them. and yet, example 3 seems to contradict the other observations, since if the problem was with dereferencing it, it shouldn't matter whether the pointer itself has a name or not. Thus far any explanation of what we are being warned for, as well as when the compiler looks ahead to consider a warning and when it doesn't seems to be inconsistent.
You already explain the purpose of the warning correctly, so I will just go through the list to explain why it does or does not apply in each case: //1) warning: will be evaluated std::cout << typeid(*pa1).name() << '\n'; pa1 is not a pointer, it is a class type, a std::shared_ptr<A>. It is true that the dereferencing still doesn't have any side effect, but to determine that for sure the compiler would need to figure out what the overloaded operator* exactly does. Compiler's don't usually do such deeper analysis for warnings. That it still warns although it can't prove whether side effects are possible either way is a choice made by the compiler developers. //2) okay std::cout << typeid(pa1.get()).name() << '\n'; This one is okay because pa1.get() is a pointer type. It is not a polymorphic glvalue and therefore the expression will not be evaluated at all. typeid only evaluates the operand if it is a polymorphic glvalue, which is part of why one can easily get confused whether the operand will cause side effects. typeid(pa1.get()) is always A*, determined at compile-time. //3) okay std::cout << typeid(*pa2).name() << '\n'; This one is okay because you are really only dereferencing a pointer which, without having to look through other functions, is guaranteed not to have side effects. //4) warning: will be evaluated std::cout << typeid(*new A{}).name() << '\n'; This has a side effect because it allocates memory. The warning here is really useful, because *new A{} is going to lead to a guaranteed memory leak, so the side effect is definitively unintended. //5) warning: will not be evaluated std::cout << typeid(new A{}).name() << '\n'; As above new A{} evaluates to a pointer prvalue, not a polymorphic glvalue, so the expression won't be evaluated. But new A{} has a guaranteed side effect, so why would you have written it if you don't intent the side effect? Just A* would be fine and less prone to mistake. //6) warning: will be evaluated std::cout << typeid(*get_pa()).name() << '\n'; Again, the compiler is not likely to look through the get_pa call to determine whether it has side effects. In this case get_pa does have a side effect. It initializes the static variable. So in any case the warning is warranted. In any case, the warnings can be avoided and the intention be made clearer by simply not passing anything but an id-expression to typeid. For example you can state clearly that evaluation will happen like this: auto& obj = *get_pa(); std::cout << typeid(obj).name() << '\n';
74,425,494
74,425,648
How make template member function specialization from inherited class?
Need some help about template member function specialization as following code; class Base { public: template <int> void MyFunc(); }; class Object : public Base { public: //template <int> void MyFunc(); // with this works !!! template <> void MyFunc<3>() { } }; Thanks !!!
You can't. The reason is that when the compiler sees the declaration of Object, it doesn't know anything about Base's template functions. So it can't generate a specialization of MyFunc for Object. The only way to make this work is to declare the specialization of MyFunc in the Base class. Member function templates are not inherited.
74,425,959
74,425,974
C++ Code outputs two characters when I only desire one output (Fix found!) <3
As simple as it sounds. I'm a newb when it comes to c++, but I have been following cpp reference and some online tutorials to write code. My code should output a string as "SuCh", but instead it outputs something as "SSuuCChh". Is there a practical error I'm missing? #include <cctype> #include <iostream> using namespace std; int main() { string mani; int L = 0; getline(cin, mani); for (int i = 0; i<mani.length();i++){ if(mani.at(i) == ' '){ cout << ' ' << flush; L = L - 2; } else if(L%2==0){ putchar(toupper(mani.at(i))); L++; } else if(L%1==0) { putchar(tolower(mani.at(i))); L++; } } return 0; }
You're calling putchar and using cout, so you're printing each character twice in two different ways. Eliminate either the call to putchar(), or the cout <<, and you will only get each character once.
74,426,092
74,431,294
How to have C++ call overridden method after a conversion to the base class
I have a class A with method Hello: class A { public: void Hello(){ std::cout << "Hi from class A!" << std::endl; } }; I then have a class B that inherits class A and has its own Hello method: class B : public A { public: void Hello(){ std::cout << "Hi from class B!" << std::endl; } }; I create a new object of class B, and later cast it to be of type class A. B myB; A myA = static_cast<A>(myB); How do I make it so myA.Hello(); prints "Hi from class B!"?
You should use reference and can call Hello() B myB; A& myA = static_cast<A&>(myB); myA.Hello(); oupput: Hi from class A! If you add "virtual" to Hello() of class A, virtual void Hello() { you can get output below. Hi from class B!
74,426,141
74,426,210
Using a custom value as a local variable
What I want to do is to use a custom value as a local variable (in code this looks something like this): #include <iostream> #include <iomanip> #include <cmath> #include <fstream> using namespace std; int main() { fstream someFileStream; someFileStream.open("RandomFileName.txt"); double a0; double a1; double a2; double a3; string SomethingString; int counter = 0; for (int counter = 0; counter <= 3; counter++) { getline(someFileStream, SomethingString, '\n'); double SomethingDouble = stod(SomethingString); 'a'+counter= SomethingDouble; //This line of code gets an error /* I want to make it so that the 'a'+counter is used as a local variable name and the SomethingDouble gets stored in the following doubles: a0, a1, a2, a3; */ } someFileStream.close(); return 0; } If this is not possible, then I might try another solution rather than using a custom value for the local variable name. Also please don't use arrays in the answer (I'm writing a program for an assignment, in which arrays are not allowed) I tried looking all across the internet, but it seems as if nothing has been done like this before, so I couldn't find how to make it work.
Since using a counter value in the name for an assignment seems to be impossible in c++, the next closest thing to solving this problem was hard-coding a switch into the while loop: for (int counter = 0; counter <= 3; counter++) { getline(someFileStream, SomethingString, '\n'); double SomethingDouble = stod(SomethingString); switch(counter){ case 0: a0 = SomethingDouble; break; case 1: a1 = SomethingDouble; break; case 2: a2 = SomethingDouble; break; case 3: a3 = SomethingDouble; break; default: cout<<"This isn't supposed to happen\n"; break; } }
74,426,229
74,427,152
Why does the == operator of std::unordered_multiset<T> returns wrong result when T is a pointer type?
Is this a bug, or am I doing something wrong? I already tried providing hashing and equality functors for the pointer type, but it doesn't seem to work. I even tried creating my own miniature template container just to test the functors. Hashing functor: class CharPtHash { private: using pChar = char*; public: size_t operator()(const pChar& c) const { std::hash<char> hasher; if (c == nullptr) { return 0; } return hasher(*c); } }; Equality: class CharPtEqual { private: using pChar = char*; public: bool operator()(const pChar& lhs, const pChar& rhs)const { if (lhs == rhs)//not sure of nullptr is equal to itself. { return true; } else if (lhs==nullptr || rhs==nullptr) { return false; } return *lhs == *rhs; } }; Main: int main() { cout << "Testing unordered_multiset with keys being simple types:\n"; unordered_multiset<char> sA1({ 'a','b','c' }); unordered_multiset<char> sA2({ 'a','c','b' }); cout << "Values: " << endl << sA1 << endl << sA2 << endl; cout << (sA1 == sA2 ? "Equal" : "Not Equal"); cout << endl; cout << "Testing unordered_multiset with keys being pointers to simple types:\n"; char** c1 = new char* [3]{ new char('a'), new char('b'), new char('c') }; char** c2 = new char* [3]{ new char('a'), new char('c'), new char('b') }; unordered_multiset<char*,CharPtHash,CharPtEqual> sB1; unordered_multiset<char*,CharPtHash,CharPtEqual> sB2; sB1.insert(c1[0]); sB1.insert(c1[1]); sB1.insert(c1[2]); sB2.insert(c2[0]); sB2.insert(c2[1]); sB2.insert(c2[2]); cout << "Values: " << endl << sB1 << endl << sB2 << endl; cout << (sB1 == sB2 ? "Equal" : "Not Equal"); cout << endl; cin.get(); } I tried compiling it to c++20 and c++14 using Visual Studio 2022. This is the output: Testing unordered_multiset with keys being simple types: Values: { a, b, c } { a, c, b } Equal Testing unordered_multiset with keys being pointers to simple types: Values: { a, b, c } { a, c, b } Not Equal
Supplying your own KeyEqual only change the behavior internally, i.e. inserting new items. However it has no effects on operator==. According to operator==(std::unordered_multiset), the behavior of it is as if each equivalent equal_ranges were compared with std::is_permutation. You can potentially specialize the behavior of std::is_permutation for your set pre-C++20(this is undefined behavior since C++20): template<> bool std::is_permutation( std::unordered_multiset<char*, CharPtHash, CharPtEqual>::const_iterator l_begin, std::unordered_multiset<char*, CharPtHash, CharPtEqual>::const_iterator l_end, std::unordered_multiset<char*, CharPtHash, CharPtEqual>::const_iterator r_begin) { return std::is_permutation(l_begin, l_end, r_begin, CharPtEqual{}); } Or just create your own char* wrapper with a custom operator==.
74,426,266
74,426,381
C++, getting gibberish from const unisgned char array
I am trying to write a program with a simple login interface for school in C++. I am new and still learning but I am getting a strange error with the following snippet of code. Inside the loop it outputs the username,password and name just as intended but if I try to access the array later it outputs gibberish. Any help with this is greatly appreciated: EDIT: Thanks everyone! You suggestions helped to fix the problem. I needed to use strdup, It is not a standard c function but is really easy to implement, just run a google search! sql = "SELECT username,password,real_name from Users"; const unsigned char* usernames[20]; // 20 max usernames const unsigned char* passwords[20]; const unsigned char* names[20]; rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); //sqlite3_exec(db, sql, callback, usernames, &zErrMsg); if( rc != SQLITE_OK ) { printf("error: %s ", sqlite3_errmsg(db)); return 1; } int i = 0; while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { usernames[i]= sqlite3_column_text (stmt, 0); passwords[i] = sqlite3_column_text(stmt, 1); names[i] = sqlite3_column_text(stmt, 2); //Prints fine cout << usernames[i] << ":" << passwords[i] << ":" << names[i] << "\n"; i = i + 1 ; } //Prints gibberish cout << usernames[0];
According to the documentation: The pointers returned are valid [...] until sqlite3_step() or sqlite3_reset() or sqlite3_finalize() is called. Since you are calling sqlite3_step on each iteration, the pointer you saved into the arrays became invalid right afterward. Solution Either manually invoke malloc and strcpy to actually store the result, or simply save them into std::strings.
74,426,674
74,436,138
Can switch default statement be optimised out for enum
If I have a switch statement that handles all enum cases explicitly, is the compiler allowed to optimise away the default case statement? enum MyEnum { ZERO = 0, ONE = 1, TWO = 2, THREE = 3, }; bool foo(MyEnum e) { switch(e) { case ZERO: case ONE: case TWO: case THREE: return true; default: // Could a compiler optimise this away? return false; } } Cpp Reference says regarding enums (emphasis mine): Values of integer, floating-point, and enumeration types can be converted by static_cast or explicit cast, to any enumeration type. If the underlying type is not fixed and the source value is out of range, the behavior is undefined. (The source value, as converted to the enumeration's underlying type if floating-point, is in range if it would fit in the smallest bit field large enough to hold all enumerators of the target enumeration.) Otherwise, the result is the same as the result of implicit conversion to the underlying type. Note that the value after such conversion may not necessarily equal any of the named enumerators defined for the enumeration. Which indicates it would be allowed to optimise out the default statement in the above example since the underlying type is not fixed and every 2-bit value is specified (though maybe you would need to include negative values to -4). However, it is not clear if this also applies to fixed type enums or enum classes. In practice, GCC, clang, and MSVC do not assume that the enum is one of the defined values. (Godbolt with full optimization enabled like -O3 -std=c++20.) Is that a missed optimization, or is the standard saying that if the implementation picks int as the underlying type (even though you didn't specify) then any int value is legal? CppReference shows an example under the paragraph quoted: enum access_t { read = 1, write = 2, exec = 4 }; // enumerators: 1, 2, 4 range: 0..7 access_t y = static_cast<access_t>(8); // undefined behavior since CWG1766 That makes it clear that "range" is tied to the named enumerator values, not the full width of any integer type. Assuming that cppreference example is an accurate reflection of the ISO standard, of course, that implies that explicit or implicit conversion can't legally produce an enum object with a value that isn't accounted for.
Yes, I guess in theory they could. There is no standard-sanctioned way to reach the default. As mentioned on the cppreference page, the standard essentially says in [dcl.enum]/8 that the possible values of an enumeration without fixed underlying type are zero to, exclusive, the smallest power of two able to fit all of the declared enumerator's values. Casting from the underlying type to values outside this range via static_cast is explicitly undefined behavior. There may be some room to argue about memcpy/std::bit_cast from the underlying type to the enumeration, but I don't think that works out either. The linked standard passage seems to define the values of the enumeration exclusively, so it is not possible for object representations to represent any additional values (assuming they are valid object representations of the enumeration to begin with). The standard currently doesn't even guarantee same representation as the underlying type for the values that the enumeration does have (although that may be a defect). However, it wouldn't be compatible with C where all values of the underlying type are allowed. Since the smallest possible underlying type is char which is at least 8 bits wide, it will always be possible to reach the default in C. So I don't expect any compiler to consider the default unreachable without additional knowledge of the argument's range. Enumerations with fixed underlying type (which includes all enum class) are specified differently and guaranteed to support all values of the underlying type, as is the case in C for all enumerations.
74,426,867
74,426,980
C++20 <chrono>: How to calculate difference between year_month_date?
Using C++20's <chrono>, how can I find the days difference of two year_month_day objects? int main() { using namespace std::chrono; const auto now = system_clock::now(); const year_month_day today = floor<days>(now); const year_month_day xmas = today.year() / month(12) / day(25); const days days_till_xmas = xmas - today; // I want something like this ---^ }
You can use std::chrono::sys_days to convert to std::chrono::time_point. For example, auto diff = std::chrono::sys_days(xmas) - std::chrono::sys_days(today); std::cout << "diff days: " << std::chrono::duration_cast<std::chrono::days>(diff).count() << "days\n";
74,427,054
74,428,668
Put .conan folder with cache to the current project folder
Is there any way to create .conan folder in the root of the current project on building stage?
You can define CONAN_USER_HOME environment variable to point to your current folder, that will put the Conan cache there. However this doesn't have many advantages, one of the reasons of having the cache separated is that it is way more efficient to have the packages installed in a common place, and they can be used in multiple projects. And given the structure of the cache, different versions or different configurations (shared/static, Debug/Release, etc) will not conflict, they can be installed simultaneously. Conan 2.0 implements a .conanrc file that you can put in your project root and that allows defining the CONAN_HOME variable automatically.
74,427,605
74,427,766
How can I fix C++ error C2672 in my code with threads?
When I'm trying to compile program with threads, C2672 error ('invoke': no matching overloaded function found) is occuring. My code: #include <iostream> #include <thread> // the procedure for array 2 filling void bar(int sum2) { for (int i = 100000; i < 200000; i++) { sum2 = sum2 + (i + 1); std::cout << sum2; } } int main() { // the second counter initialization int sum2 = 0; // the constructor for the thread std::cout << "staring thread2...\n"; std::thread thread(bar); // the thread detaching thread.detach(); // the first counter initialization int sum1 = 0; // filling of the first array for (int i = 0; i < 100000; i++) { sum1 = sum1 + (i + 1); // elements output std::cout << sum1; } } Tell me please, how to fix this bug?
You need to pass a value to the thread you're creating, std::thread thread(bar, N); where N is the integer value, as you've defined in your void bar(int) function. #include <iostream> #include <thread> // the procedure for array 2 filling void bar(int sum2) { for (int i = 100000; i < 200000; i++) { sum2 = sum2 + (i + 1); std::cout << sum2; } } int main() { // the second counter initialization int sum2 = 0; // the constructor for the thread std::cout << "staring thread2...\n"; std::thread thread(bar, 100); // the thread detaching thread.detach(); // the first counter initialization int sum1 = 0; // filling of the first array for (int i = 0; i < 100000; i++) { sum1 = sum1 + (i + 1); // elements output std::cout << sum1; } return 0; }
74,427,737
74,428,867
How to get angle between two vectors in 3D
I have two objects one sphere and a cone. I want cone to always face the sphere as shown in the images. we have constructed the cone in local coordinate system in such a way, that the tip of the cone points upward the y-axis and the center is at the origin (0,0,0). The angle between two 3D vectors would be float fAngle = std::acos(dot(sphereVector, coneVector) / magnitude(sphereVector * magnitude(coneVector))); For cone to be always facing the sphere it need to be rotated in all three axis based on the position of the sphere but i am getting only one angle from the maths formula. How do i calculate all the three angles for the cone that it is always perpendicular to the sphere.
First, you need the vector where the cone should point to: direction = center_cone - center_sphere; Then, we assume, that you've constructed your cone in the local coordinate system in such a way, that the tip of the cone points upward the y-axis and the center is at the origin (0,0,0). The axises to rotate are: x_axis(1, 0, 0); y_axis(0, 1, 0); z_axis(0, 0, 1); Now, you simply have to project the axises to the direction vector to get the 3 angles. Example: float angle(vec a, vec b) { return acos(dot(a, b) / (magnitude(a) * magnitude(b))); } vec direction = normalize(center_cone - center_sphere); float x_rot = angle(x_axis, direction); float y_rot = angle(y_axis, direction); float z_rot = angle(z_axis, direction);
74,429,257
74,429,594
Compare string array1 with string array2 and return entries that are not present in array2
I have two arrays in my C++ code. array1 has all elements but array2 has the same elements but with a few missing. I am trying to find out the elements that are missing in array2. Instead of showing the missing elements, it is showing elements which are also present in both the arrays and multiple times. string array1[] = { "aaa","bbb","ccc","ddd" }; string array2[] = { "aaa","bbb","ccc" }; for (i = 0; i <= 3; i++) { for (int j = 0; j <= 2; j++) { if (array1[i] == array2[j]) continue; else cout << array1[i] << endl; } } ''' I tried using nested for loops to try to compare every element from array1 with all the elements of array2. If a match is found, the loop is supposed to skip and move on to the next iteration and if a match has not been found, it should display the element that was not found in array2.
You implemented the logic of your code a little bit wrong. So, first iterate over all elements from array1. Then, check, if the current element is in the array2. For this you can use a flag. If it is not in, then print it. There are even standard functions in the C++ algorithm library availabe. But let's ge with the below solution: #include <iostream> #include <string> using namespace std; int main() { string array1[] = { "aaa","bbb","ccc","ddd" }; string array2[] = { "aaa","bbb","ccc" }; for (int i = 0; i <= 3; i++) { bool isPresent = false; for (int j = 0; j <= 2; j++) if (array1[i] == array2[j]) isPresent = true; if (not isPresent) std::cout << array1[i] << '\n'; } }
74,429,465
74,432,464
Synchronization problem with std::atomic<>
I have basically two questions that are closely related and they are both based on this SO question: Thread synchronization problem with c++ std::atomic variables As cppreference.com explains: For memory_order_acquire: A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread For memory_order_release: A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable Why people say that memory_order_seq_cst MUST be used in order for that example to work properly? What's the purpose of memory_order_acquire if it doesn't work as the official documentation says so? The documentation clearly says: All writes in other threads that release the same atomic variable are visible in the current thread. Why that example from SO question should never print "bad\n"? It just doesn't make any sense to me. I did my homework by reading all available documentation, SO queastions/anwers, googling, etc... But, I'm still not able to understand some things.
Your linked question has two atomic variables, your "cppreference" quote specifically mentions "same atomic variable". That's why the reference text doesn't cover the linked question. Quoting further from cppreference: memory_order_seq_cst : "...a single total order exists in which all threads observe all modifications in the same order". So that does cover modifications to two atomic variables. Essentially, the design problem with memory_order_release is that it's a data equivalent of GOTO, which we know is a problem since Dijkstra. And memory_order_acquire is the equivalent of a COMEFROM, which is usually reserved for April Fools. I'm not yet convinced that they're good additions to C++.
74,429,905
74,438,895
Large interval upper bound of a CGAL lazy number
I have an example of a sum of the form s = a_1/b_1 + a_2/b_2 + ... where the a_i and the b_i are CGAL lazy numbers, such that the interval returned by s.interval() is very large. Its lower bound is close to the expected value (and close to CGAL::as_double(s)) but its upper bound is huge (even infinite). But if I use mydivision(a_i, b_i) (defined below) instead of a_i/b_i, then the interval is thin as expected. Here is mydivision: typedef CGAL::Quotient<CGAL::MP_Float> Quotient; typedef CGAL::Lazy_exact_nt<Quotient> lazyScalar; lazyScalar mydivision(lazyScalar x1, lazyScalar x2) { Quotient q1 = x1.exact(); Quotient q2 = x2.exact(); lazyScalar q = lazyScalar(Quotient( q1.numerator() * q2.denominator(), q1.denominator() * q2.numerator()) ); return q; } This is the sum (it goes to pi/2 - 1): This is the full code: #include <vector> #include <CGAL/number_utils.h> #include <CGAL/Lazy_exact_nt.h> #include <CGAL/MP_Float.h> #include <CGAL/Quotient.h> #include <CGAL/Interval_nt.h> typedef CGAL::Quotient<CGAL::MP_Float> Quotient; typedef CGAL::Lazy_exact_nt<Quotient> lazyScalar; typedef std::vector<lazyScalar> lazyVector; // "my" division lazyScalar mydivision(lazyScalar x1, lazyScalar x2) { Quotient q1 = x1.exact(); Quotient q2 = x2.exact(); lazyScalar q = lazyScalar(Quotient( q1.numerator() * q2.denominator(), q1.denominator() * q2.numerator()) ); return q; } // sum the elements of a vector of lazy numbers lazyScalar lazySum(lazyVector lv) { const size_t n = lv.size(); lazyScalar sum(0); for(size_t i = 0; i < n; i++) { sum += lv[i]; } return sum; } // element-wise division of two vectors of lazy numbers lazyVector lv1_dividedby_lv2(lazyVector lv1, lazyVector lv2) { const size_t n = lv1.size(); lazyVector lv(n); for(size_t i = 0; i < n; i++) { lv[i] = lv1[i] / lv2[i]; } return lv; } // same as above using "my" division lazyVector lv1_mydividedby_lv2(lazyVector lv1, lazyVector lv2) { const size_t n = lv1.size(); lazyVector lv(n); for(size_t i = 0; i < n; i++) { lv[i] = mydivision(lv1[i], lv2[i]); } return lv; } // cumulative products of the elements of a vector of lazy numbers lazyVector lazyCumprod(lazyVector lvin) { const size_t n = lvin.size(); lazyVector lv(n); lazyScalar prod(1); for(size_t i = 0; i < n; i++) { prod *= lvin[i]; lv[i] = prod; } return lv; } // the series with the ordinary division lazyScalar Euler(int n) { lazyVector lv1(n); for(int i = 0; i < n; i++) { lv1[i] = lazyScalar(i + 1); } lazyVector lv2(n); for(int i = 0; i < n; i++) { lv2[i] = lazyScalar(2*i + 3); } return lazySum(lv1_dividedby_lv2(lazyCumprod(lv1), lazyCumprod(lv2))); } // the series with "my" division lazyScalar myEuler(int n) { lazyVector lv1(n); for(int i = 0; i < n; i++) { lv1[i] = lazyScalar(i + 1); } lazyVector lv2(n); for(int i = 0; i < n; i++) { lv2[i] = lazyScalar(2*i + 3); } return lazySum(lv1_mydividedby_lv2(lazyCumprod(lv1), lazyCumprod(lv2))); } // test - the difference starts to occur for n=170 int main() { lazyScalar euler = Euler(171); CGAL::Interval_nt<false> interval = euler.approx(); std::cout << "lower bound: " << interval.inf() << "\n"; // prints 0.57 std::cout << "upper bound: " << interval.sup() << "\n"; // prints inf lazyScalar myeuler = myEuler(171); CGAL::Interval_nt<false> myinterval = myeuler.approx(); std::cout << "lower bound: " << myinterval.inf() << "\n"; // prints 0.57 std::cout << "upper bound: " << myinterval.sup() << "\n"; // prints 0.57 return 0; } Why this large upper bound?
You are computing factorials and similar products. Once they exceed the maximum value for a double, there isn't much an interval represented as a pair of double can do. At least it gives you a safe answer, and you can still get the true answer using exact() at the end. Your division would be simpler as return exact(x1/x2);, but you don't even need to call exact that often, just exact(Euler(171)) Computing the value as (1/3)*(2/5)*(3/7) instead of (1*2*3)/(3*5*7) would avoid having an overflow so soon.
74,429,998
74,430,207
Declaration of a String of Dynamic Length Using Pointer
I wanted to declare an array with a pointer in character type, and the length of the array can be determined by my input string. I wrote it in this way: char *s; cout << "Enter a string: " << endl; cin >> s; I expected that I can initialize the string by the cin operation, but an error showed up when compiling. The error is about "invalid operands to binary expression". I'm not sure why the lines I wrote was wrong. I though not only the built in string class is used for declaring an array. Isn't the string data type in C++ the same as "a character array"? Isn't the line char *s means the pointer s points to an character array (or string)? Thank you!
You should use std::string. It is a class that represents a string of characters. It is different than an old c style array of characters (although internally might contain one). In your case: #include <string> #include <iostream> std::string s; std::cout << "Enter a string: " << endl; std::cin >> s; Using std::string means memory is managed automatically for you. Specifically with cin it will also be resized to fit the input. A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
74,430,850
74,430,921
I have Question about class overriding in C++
When I study about override keyword, I found some strange thing like below code. #include <iostream> template <class T> class A { public: virtual void some_function(const T a) { std::cout<<__PRETTY_FUNCTION__<<std::endl; std::cout<<"Base"<<std::endl; } }; class Derived : public A<int*> { public: virtual void some_function(const int* a) { std::cout<<__PRETTY_FUNCTION__<<std::endl; std::cout<<"Derived"<<std::endl; } }; int main() { A<int*>* p = new Derived; p->some_function(nullptr); delete p; } When I first saw that code, I expected "Derived" to be called. But above code print result like below. void A<T>::some_function(T) [with T = int*] Base But when I removed const keyword in the some_function that placed in Derived class, class Derived : public A<int*> { public: virtual void some_function(int* a) { std::cout<<__PRETTY_FUNCTION__<<std::endl; std::cout<<"Derived"<<std::endl; } }; It print "Derived". Can you tell me why this is happening?
The function prototypes are not the same. For T=int* const T a: a is a const pointer to an int, while const int *a is a pointer to an const int. For one the pointer is const, for the other the int is const. int * const a would be the same as const T a, or you can make T=const int*. https://godbolt.org/z/WEaEoGh58 Also important to note: When you derive from a class you must declare a virtual destructor. A hint: when you use the keyword override on the derived function, you will get an error that you are not overriding the function: https://godbolt.org/z/o87GMrhsd
74,431,090
74,444,578
Qt Folder organization
I am learning Qt6 in Qt Creator 8.0.2 (Community) with C++ on Windows. I have a project( Qt Widgets Application) with Qmake as the build system. When I open the project in Creator it is well organized, that is, the headers(.h files) are in a header folder, sources(.cpp files) are in sources folder, etc. Like so: LearningQt -LearningQt.pro -Headers\ -mainwindow.h -Sources\ -main.cpp -mainwindow.cpp -Forms\ -mainwindow.ui But when I open the project in File explorer all the files are in the root directory. Like so: LearningQt -LearningQt.pro -LearningQt.pro.user -mainwindow.h -main.cpp -mainwindow.cpp -mainwindow.ui My question is that is it possible to organize the project files in folders in File explorer?
Yes, you can reorganise file locations. It is still unclear from your question what problems you have with it. You just have to mimic whatever the changes you made on your storage directories in your *.pro file as well. QtCreator will usually understand what you did on the fly. If it does not then you erase or empty its temporary files in build directories. Here for example how to do it when you want absolute paths. The variable $$PWD is location of the .pro file itself: INCLUDEPATH += \ $$PWD/Headers HEADERS += \ $$PWD/Headers/mainwindow.h SOURCES += \ $$PWD/Sources/main.cpp \ $$PWD/Sources/mainwindow.cpp Or other such changes. The *.pro is relatively simple and intuitive project file compared to other build systems like CMake, makefiles, XCode or Visual Studio project files. Also it is quite well documented. If you have concrete questions about particular feature of it then ask it in some other question.
74,431,093
74,433,892
How to check a valid boost asio CompletionToken?
I'm writing Boost.Asio style async function that takes CompletionToken argument. The argument can be function, function object, lambda expression, future, awaitable, etc. CompletionToken is template parameter. If I don't restrict the argument, the function could match unexpected parameter such as int. So I want to write some restriction using std::enable_if. (My environment is C++17). If CompletionToken takes parameters, then I can use std::is_invocable for checking. See f1 in my example code. However, I got a problem. If CompletionToken takes no parameters, then boost::asio::use_future makes an error. See f2 in my example code. After some of try and error, I got my solution. That is concatenating std::is_invocable and use_future_t checking by OR (||). See f3 in my example code. But it is not so elegant. In addition, I'm not sure other features supported by Boost.Asio e.g.) use_awaitable_t requires similar direct matching check. I tried to find Boost.Asio provides type traits or predicate such as is_completion_token, but I couldn't find it. Is there any better way to checking CompletionToken? Godbolt link https://godbolt.org/z/sPeMo1GEK Complete Code: #include <type_traits> #include <boost/asio.hpp> // Callable T takes one argument template < typename T, std::enable_if_t<std::is_invocable_v<T, int>>* = nullptr > void f1(T) { } // Callable T takes no argument template < typename T, std::enable_if_t<std::is_invocable_v<T>>* = nullptr > void f2(T) { } template <template <typename...> typename, typename> struct is_instance_of : std::false_type {}; template <template <typename...> typename T, typename U> struct is_instance_of<T, T<U>> : std::true_type {}; // Callable T takes no argument template < typename T, std::enable_if_t< std::is_invocable_v<T> || is_instance_of<boost::asio::use_future_t, T>::value >* = nullptr > void f3(T) { } int main() { // no error f1([](int){}); f1(boost::asio::use_future); // same rule as f1 but use_future got compile error f2([](){}); f2(boost::asio::use_future); // error // a little complecated typechecking, then no error f3([](){}); f3(boost::asio::use_future); } Outputs: Output of x86-64 clang 13.0.1 (Compiler #1) <source>:45:5: error: no matching function for call to 'f2' f2(boost::asio::use_future); // error ^~ <source>:17:6: note: candidate template ignored: requirement 'std::is_invocable_v<boost::asio::use_future_t<std::allocator<void>>>' was not satisfied [with T = boost::asio::use_future_t<>] void f2(T) { ^ 1 error generated.
If you have c++20 concepts, look below. Otherwise, read on. When you want to correctly implement the async-result protocol using Asio, you would use the async_result trait, or the async_initiate as documented here. This should be a reliable key for SFINAE. The template arguments to async_result include the token and the completion signature(s): Live On Compiler Explorer #include <boost/asio.hpp> #include <iostream> using boost::asio::async_result; template <typename Token, typename R = typename async_result<std::decay_t<Token>, void(int)>::return_type> void f1(Token&&) { std::cout << __PRETTY_FUNCTION__ << "\n"; } template <typename Token, typename R = typename async_result<std::decay_t<Token>, void()>::return_type> void f2(Token&&) { std::cout << __PRETTY_FUNCTION__ << "\n"; } int main() { auto cb1 = [](int) {}; f1(cb1); f1(boost::asio::use_future); f1(boost::asio::use_awaitable); f1(boost::asio::detached); f1(boost::asio::as_tuple(boost::asio::use_awaitable)); auto cb2 = []() {}; f2(cb2); f2(boost::asio::use_future); f2(boost::asio::use_awaitable); f2(boost::asio::detached); f2(boost::asio::as_tuple(boost::asio::use_awaitable)); } Already prints void f1(Token&&) [with Token = main()::<lambda(int)>&; R = void] void f1(Token&&) [with Token = const boost::asio::use_future_t<>&; R = std::future<int>] void f1(Token&&) [with Token = const boost::asio::use_awaitable_t<>&; R = boost::asio::awaitable<int, boost::asio::any_io_executor>] void f1(Token&&) [with Token = const boost::asio::detached_t&; R = void] void f1(Token&&) [with Token = boost::asio::as_tuple_t<boost::asio::use_awaitable_t<> >; R = boost::asio::awaitable<std::tuple<int>, boost::asio::any_io_executor>] void f2(Token&&) [with Token = main()::<lambda()>&; R = void] void f2(Token&&) [with Token = const boost::asio::use_future_t<>&; R = std::future<void>] void f2(Token&&) [with Token = const boost::asio::use_awaitable_t<>&; R = boost::asio::awaitable<void, boost::asio::any_io_executor>] void f2(Token&&) [with Token = const boost::asio::detached_t&; R = void] void f2(Token&&) [with Token = boost::asio::as_tuple_t<boost::asio::use_awaitable_t<> >; R = boost::asio::awaitable<std::tuple<>, boost::asio::any_io_executor>] C++20 Concepts Now keep in mind the above is "too lax" due to partial template instantiation. Some parts of async_result aren't actually used. That means that f2(cb1); will actually compile. The linked docs even include the C++20 completion_token_for<Sig> concept that allows you to be precise at no effort: Live On Compiler Explorer template <boost::asio::completion_token_for<void(int)> Token> void f1(Token&&) { std::cout << __PRETTY_FUNCTION__ << "\n"; } template <boost::asio::completion_token_for<void()> Token> void f2(Token&&) { std::cout << __PRETTY_FUNCTION__ << "\n"; } Otherwise In practice you would always follow the Asio recipe, and that guarantees that all parts are used. Apart from the example in the documentation, you can search existing answers Example: template <typename Token> typename asio::async_result<std::decay_t<Token>, void(error_code, int)>::return_type async_f1(Token&& token) { auto init = [](auto completion) { auto timer = std::make_shared<asio::steady_timer>(boost::asio::system_executor{}, 1s); std::thread( [timer](auto completion) { error_code ec; timer->wait(ec); std::move(completion)(ec, 42); }, std::move(completion)) .detach(); }; return asio::async_result<std::decay_t<Token>, void(error_code, int)>::initiate( init, std::forward<Token>(token)); }