question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,849,359
69,850,769
Is it correct to resize a vector with moved-elements?
I am trying to understand the generic rules of move semantics. Specifically of containers and contained elements. The reason is that I am trying to understand move in the context of ownership and iterator invalidation. To do that I am going through some cases with increasing complexity involving a typical container, a general contained type T, general g and f functions. (Maybe an important extra detail is that f might or might not actually do a move operation, or it could be contingent at runtime.) The idea is to introduce Case 3 which is the core of this question. Case 0 First a fairly uncontroversial case, this is ok: std::vector<T> v(100, t); f(std::move(v)); v = make_a_vector(); Case 1 However, use-after-move is likely smelly code std::vector<T> v(100, t); f(std::move(v)); g(v); I think most people agree that this above is not ok. The rule being (as far I know) that the only operation after move should be assignment. I think this is particularly because it is undocumented (undefined but valid state) what is the state of a moved-from vector, (or even if it was moved at all.). So, at best v is empty and at worst v is an unspecified state and therefore g could do something unspecified in this scope. Case 2: std::vector<T> v(100, t); f(std::move(v)); v.resize(120); Is it correct? It is not an assignment, but resize has no preconditions. (found this Can I resize a vector that was moved from?) Case 3: Now the really tricky case. std::vector<T> v(100); h(std::make_move_iterator(v.begin()), std::make_move_iterator(v.end())); v.resize(120); (Here, h is a function that takes iterators, assume that implicitly it refers to the range [iterator1, iterator2).) Is this correct code? The reason is that .resize seems to be going to play, move, swap and copy moved-from object of type T. To summarize, is it correct to resize a vector whose elements have been (possibly) moved-from? EDIT: For the sake of argument, let's specify the signatures of the functions in case they are relevant to the answer(s): template<class T> void f(std::vector<T>&&); template<class T> void g(std::vector<T> const&); template<class It> void h(It first, It last);
std::vector<T> v(100, t); f(std::move(v)); v.resize(120); is similar to your case 1 std::vector<T> v(100, t); f(std::move(v)); g(v); vector::resize has no prerequires, but you don't know previous state. it might be empty, have some size (with unspecified value). So after v.resize(120), you just know that the new size is 120, but doesn't know its contents (new elements are default constructed, but which are they?).
69,849,438
69,849,599
Exception thrown: read access violation. **this** was 0xCCCCCCCC
I'm trying to build an understanding of objects, arrays, and pointers. When I compile my code I ended up with 0xCCCCCCCC. I understand that this error is probably due to an uninitialized pointer. The problem is I don't know where or how to. #include <iostream> #include <string> using namespace std; class Person { public: string name; }; void createPerson(Person* person[]); int main() { Person* person[5]; createPerson(person); for (int i = 0; i < 5; i++) { cout << person[i]->name << endl; } return 0; } void createPerson(Person* person[]) { string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" }; for (int i = 0; i < 5; i++) { person[i]->name = n[1]; } } I'm trying to get the list of names to display.
The Problem is you have an Array of Person Person* person[] pointers and not an array of persons. I fixed the code and removed the pointers: #include <iostream> #include <string> using namespace std; class Person { public: string name; }; void createPerson(Person person[]); int main() { Person person[5]; createPerson(person); for (int i = 0; i < 5; i++) { cout << person[i].name << endl; } return 0; } void createPerson(Person person[]) { string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" }; for (int i = 0; i < 5; i++) { person[i].name = n[i]; } } As you can see I removed the pointer from your array definitions. This way the Person object gets initialized on the stack. In your way the pointers get initialized, but they dont point to anything. Thats why you get your error, because the pointers are dangling. If you really want to use an array of pointer you have to initialize these pointers like this: #include <iostream> #include <string> using namespace std; class Person { public: string name; }; void createPerson(Person* person[]); int main() { Person* person[5]; createPerson(person); for (int i = 0; i < 5; i++) { cout << person[i]->name << endl; //delete person so that we dont leak mem delete person[i]; } return 0; } void createPerson(Person* person[]) { string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" }; for (int i = 0; i < 5; i++) { person[i] = new Person(); person[i]->name = n[i]; } } BTW: I would not use pointers this way. If you are new and try to understand stuff its fine to experiment. But you should almost always use smart_pointers like std::shared_ptr etc. The next thing to experiment with should be containers and proper data structures.
69,849,548
69,849,573
Are there any differences between accumulate(a.begin(), a.end(), 0) and accumulate(a.begin(), a.end(), 0ll) in C++?
When I write long long sum = accumulate(a.begin(), a.end(), 0); or long long sum = accumulate(a.begin(), a.end(), 0ll); both give me the same result (where a is std:: vector<int> a(n)). So why use 0ll instead of only 0 ? Here is my code: #include <bits/stdc++.h> using namespace std; const int MAX = 1e6; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); vector<int> cnt(MAX + 1); for (int i = 0; i < n; ++i) { cin >> a[i]; ++cnt[a[i]]; } long long sum = accumulate(a.begin(), a.end(), 0ll); vector<int> ans; for (int i = 0; i < n; ++i) { sum -= a[i]; --cnt[a[i]]; if (sum % 2 == 0 && sum / 2 <= MAX && cnt[sum / 2] > 0) { ans.push_back(i); } sum += a[i]; ++cnt[a[i]]; } cout << ans.size() << endl; for (auto it : ans) cout << it + 1 << " "; cout << endl; return 0; } And here is the same code on OnlineGDB
std::accumulate is a template, when being passed 0 (which is supposed to be the initial value of the sum), the 2nd template parameter will be deduced as int, then the sum is performed on int, the return type is int too. Then in long long sum = accumulate(a.begin(), a.end(), 0);, the returned int is converted to long long and assigned to sum. On the other hand, accumulate(a.begin(), a.end(), 0ll); performs sum on long long and returns a long long. If the sum won't cause overflow on int, you'll get the same result on both cases. Otherwise, the 2nd one should be perferred.
69,849,844
69,849,901
Can I insert a vector to itself with std::vector::insert?
Is it allowed by the C++03 standard to append a std::vector to itself? I wonder if the source iterators can become invalid if v needs to reallocate memory. In my STL implementation, the old memory is kept until the new memory has been created. But can I rely on this? If not, is v.reserve(2 * v.size()) before the insert a good solution to avoid the reallocation altogether? vector<int> v; v.reserve(3); v.push_back(1); v.push_back(2); v.push_back(3); // v may need to reallocate because its capacity may be less than 6. // Is this operation safe? v.insert(v.end(), v.cbegin(), v.cend()); or // Here v will _not_ need to reallocate because it has enough capacity. // Is this operation safe? v.reserve(2 * v.size()); v.insert(v.end(), v.cbegin(), v.cend());
Regardless of whether perform reserve in advance or not, the behavior is undefined. For std::vector::insert: inserts elements from range [first, last) before pos. The behavior is undefined if first and last are iterators into *this.
69,850,402
69,850,921
How to convert this directory "engine\\..\\..\\NewFolder" to absolute directory ( C++ Window )
How to convert this directory "c:\~~\engine\..\..\NewFolder" to absolute directory. I have some directory string containing "\..\". I don't know how to convert this to real path. I'm on C++, Windows.
There's a function for this called PathCanonicalize() in the Win32 API which you might find useful. Example usage: TCHAR outbuf [32767]; PathCanonicalize (outbuf, my_path); outbuf is as long as it is to handle long path names, which is a user-definable option in Windows 10 and later. You can, of course (and probably should) allocate this on the heap, and you should check the return code (the function returns TRUE if successful). Update (thank you Cody, for making me seek this out): Turns out there's a better way to do this. From Windows 8 onwards, you can use PathAllocCanonicalize instead. This has two advantages: you don't need to preallocate the output buffer it can handle path names longer than MAX_PATH Here's a snippet showing how to use it: TCHAR *path_out; HRESULT hr = PathAllocCanonicalize (my_path, PATHCCH_ALLOW_LONG_PATHS, &path_out); if (hr == S_OK) { // do stuff with path_out CoTaskMemFree (path_out); } Be sure to call CoInitializeEx somewhere in your code before calling this function, otherwise it will always fail.
69,851,029
69,851,065
how to specify constructor in header for child and parent class
I am new to C++ and define a parent class in a header file parent.h. It has a constructor Parent(int a, int b). Now I want to write the header file for the child class child.h, which inherits the exact same constructor as the parent class and only has additional member functions. Do I have to specify the constructor in the child's header file as well? (Child(int a, int b)) Or do I only specify the signatures for the additional member functions and specify the constructor in the corresponding child.cppfile?
Constructors aren’t inherited. Therefore, if you want your child class to have the specified constructor you will need to provide it explicitly inside your class definition: … Child(int a, int b) : Parent(a, b) {} … Or pull in the definition from the parent class: using Parent::Parent; Note that this will pull in all constructor overloads. This may not be what you intended.
69,851,551
69,851,675
Call templated class with multiple parameters with single parameter only
I have a class with multiple template parameters; let us say it looks something like this: template <class T, class B> struct Vector2 : B { Vector2() noexcept; constexpr explicit Vector2(T a) noexcept; } Template parameter B always depends on T. For example if T is float B will be XMFLOAT2, if T is int B will be XMINT2. For this I created a template specialization: template class Vector2<float, XMFLOAT2>; template class Vector2<int32_t, XMINT2>; template class Vector2<uint32_t, XMUINT2>; The problem is that since B always depends on T, I want to call Vector<float> for example, and the expression should expand to Vector<float, XMFLOAT2>. I thought of doing a typealias, however, I wouldn't be sure how to accomplish this, since it would need to be specialized again. template<class T> using Vector2 = Vector2<T, ??>; That doesn't really make sense... How can I call a class with multiple template parameters using just a single parameter with the others being deduced? Or is there a different approach?
You can create helper trait: template <typename T> struct vector_base_class; template <> struct vector_base_class<float> { using type = XMFLOAT2; }; template <> struct vector_base_class<int32_t> { using type = XMINT2; }; template <> struct vector_base_class<uint32_t> { using type = XMUINT2; }; template <class T> struct Vector2 : typename vector_base_class<T>::type { Vector2() noexcept; constexpr explicit Vector2(T a) noexcept; };
69,851,868
69,855,886
How does gdb find the address of a variable in anonymous namespace
I have a variable declared in a c++ file like this: namespace { VelocityLongitudinal vel_lgt; } The corresponding dwarf info is <1><5e08b>: Abbrev Number: 317 (DW_TAG_namespace) <5e08d> DW_AT_sibling : <0x5e09e> <2><5e091>: Abbrev Number: 193 (DW_TAG_variable) <5e093> DW_AT_name : (indirect string, offset: 0xa5582): vel_lgt <5e097> DW_AT_decl_file : 2 <5e098> DW_AT_decl_line : 19 <5e099> DW_AT_type : <0x5bed3> <5e09d> DW_AT_declaration : 1 <2><5e09d>: Abbrev Number: 0 We see that there is no DW_AT_linkage_name and no DW_AT_location In the symbol table (readelf -s) I find. The address, 21a0a0, matches the address gdb reports (print &'(anonymous namespace)::vel_lgt') 42: 0000000000000000 0 FILE LOCAL DEFAULT ABS vehiclemotionstate_server 43: 000000000021a0a0 24 OBJECT LOCAL DEFAULT 2 _ZN12_GLOBAL__N_17vel_lgt How does gdb find that? vehiclemotionstate_serve.cpp is the name of the file in which the variable is declared. It seems unlikely that gdb would search for entries with matching last characters in the symbol table entries for a certain cpp file. And if so, how would it distinguish between two different declarations of the same name in files with the same name?
How does gdb find that? By reading the symbol table (equivalent to what readelf -s does), in addition to reading the debug info. It seems unlikely that gdb would search for entries with matching last characters It doesn't. The name you found demangles to (anonymous namespace)::vel_lgt (except you appear to have made a cut/paste error: the actual name should be _ZN12_GLOBAL__N_17vel_lgtE). how would it distinguish between two different declarations of the same name in files with the same name? It would tell you that there is more than one instance if you ask, e.g. (gdb) info var vel_lgt All variables matching regular expression "vel_lgt": File t.cc: 2: static int (anonymous namespace)::vel_lgt; File t1.cc: 2: static int (anonymous namespace)::vel_lgt; Note that it's actually quite hard to tell GDB which of the two instances to print -- print vel_lgt just prints the first one, with no easy way to ask for the other one. I believe there is an open GDB bug about this, but I can't find it. Update: The name mangling algorithm - is it the same for every compiler? No. It's the same for ABI-compatible compilers, and (intentionally) different for incompatible ones (so you don't accidentally link code compiled with two different ABI-incompatible compilers together and than debug the resulting crashes). Is the mangling algorithm easily accessible in any way? The mangling algorithm is only really useful to the compiler. Presumably you want the demangling one (going from _ZN12_GLOBAL__N_17vel_lgtE to (anonymous namespace)::vel_lgt). That one is available via the c++filt or cxxfilt programs, and also via __cxa_demangle() routine provided by most C++ runtime libraries.
69,852,735
69,852,912
How does the auto keyword deduct the type in C++
I wonder how the auto keyword determines the type of a variable in c++. I thought that statically typed languages couldn't do that. For example, how does this work: #include <iostream> int main() { std::cout << "Hello World!\n"; auto a = 5433245244524; std::cout << a << std::endl; }
It works in same way as deduction of expression returning type for templates. It happens at compilation type, so it is a static type. Literal 5433245244524 comprises initializing expression. You can get the type of expression at compile time (static type) by using operator decltype(). E.g. decltype(5433245244524) a = 5433245244524; But autokeyword is more than that. It's a placeholder type. E.g. in statement const auto& a = 5433245244524; Here auto replaces identifier of type without qualifiers to form a compatible reference type. There is a number of other uses for keyword auto, e.g. function's trailing return type, etc. see https://en.cppreference.com/w/cpp/language/auto
69,852,815
69,867,365
Unable to print other levels via BOOST_LOG_SEV
I'm trying to use Boost.Log but when I use: BOOST_LOG_SEV(slg, level)//Doesn't matter the level here even if manually pass error I'm always getting: [2021-11-05 12:07:01.305178] [0x00007ffff21589c0] [info] I'm expecting [info] to reflect the severity level I'm passing. [Edit] This is the code (Entire code, from .hpp): #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/trivial.hpp> enum severity_level { trace, debug, info, warning, error, fatal }; inline boost::log::sources::severity_logger<severity_level> slg; template <class First> std::string extract_args(First first) { if constexpr (std::is_integral_v<First>) { return std::to_string(first); } else { return first; } } template <class First, class... Args> First extract_args(First first, Args... args) { first += extract_args(args...); return first; } template <class First, class... Args> std::string logging_helper(First msg, Args... args) { std::string s_msg = extract_args(msg); if constexpr (sizeof...(args)) { s_msg += extract_args(args...); } return s_msg; } template <class First, class... Args> inline void log(severity_level level, First msg, Args... args) { BOOST_LOG_SEV(slg, level) << logging_helper(msg, args...); } If I use as proposed by @Andrey Semashev: boost::log::trivial::severity_level I'm getting following error: cannot convert ‘const boost::log::v2_mt_posix::trivial::severity_level’ to ‘boost::log::v2_mt_posix::sources::aux::severity_level<severity_level>::value_type’ {aka ‘severity_level’}
I suspect, you're using a severity level type different from boost::log::trivial::severity_level while still relying on the default sink. If the default sink can't extract severity level from a log record, it will use boost::log::trivial::severity_level::info as a default. You should either use boost::log::trivial::severity_level everywhere, or explicitly configure a sink, with a filter and formatter as necessary. In the latter case you can use your own severity level enum: enum severity_level { trace, debug, info, warning, error, fatal }; // Formatting for severity levels template< typename Char, typename Traits > inline std::basic_ostream< Char, Traits >& operator<<( std::basic_ostream< Char, Traits >& strm, severity_level level) { const char* str; switch (level) { case trace: str = "trace"; break; case debug: str = "debug"; break; default: case info: str = "info"; break; case warning: str = "warning"; break; case error: str = "error"; break; case fatal: str = "fatal"; break; } strm << str; return strm; } inline boost::log::sources::severity_logger<severity_level> slg; BOOST_LOG_ATTRIBUTE_KEYWORD(a_timestamp, "TimeStamp", boost::log::attributes::utc_clock::value_type) BOOST_LOG_ATTRIBUTE_KEYWORD(a_thread_id, "ThreadID", boost::log::attributes::current_thread_id::value_type) BOOST_LOG_ATTRIBUTE_KEYWORD(a_severity, "Severity", severity_level) // Logging initialization. To be called early in main(). void init_logging() { auto core = boost::log::core::get(); // Add commonly used attributes, such as timestamp, thread id, etc. core->add_global_attribute("TimeStamp", boost::log::attributes::utc_clock()); core->add_global_attribute( "ThreadID", boost::log::attributes::current_thread_id()); // Construct the sink typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_ostream_backend > text_sink; boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >(); boost::shared_ptr< std::ostream > stream(&std::clog, boost::null_deleter()); sink->locked_backend()->add_stream(stream); // Set formatter sink->set_formatter( boost::log::expressions::stream << "[" << boost::log::expressions::format_date_time(a_timestamp, "%Y-%M-%d %H:%M:S.%f") << "] [" << a_thread_id << "] [" << a_severity << "] " << boost::log::expressions::smessage); // Add the sink to core core->add_sink(sink); } // ... template <class First, class... Args> inline void log(severity_level level, First msg, Args... args) { BOOST_LOG_SEV(slg, level) << logging_helper(msg, args...); }
69,854,268
69,854,507
GLSL - Calculate the surface normal given its vertex normal
I want to implement flat shading on OpenGL. I googled it and found this question: How to achieve flat shading with light calculated at centroids?. I understood the top answer idea and I'm trying to implement it. However, I couldn't figure out how to find the surface normal given the normals of each vertex of the triangle. Relevant code in vertex shader: #version 400 core ... layout(location = 0) in vec4 position; layout(location = 1) in vec3 normal; uniform mat4 Mm; uniform mat3 normalMatrix; out vec3 vertexN; out vec3 vertexP; ... int main() { ... vertexN = normalize(normalMatrix * normal); vertexP = vec3(Mm * position); ... } Relevant code in geometry shader: #version 400 core ... layout (triangles) in; layout (triangle_strip, max_vertices=3) out; in vec3 vertexP[3]; in vec3 vertexN[3]; ... void main(){ ... vec3 centroidPosition(0.0); for(int i = 0; i < 3; i++) centroidPosition += vertexP[i]; centroidPosition/=3.0; // calculate surface normal ... }
The surface normal can be computed with the Cross product of 2 vectors on the surface. The following code is for counter-clockwise triangles: vec3 v1 = vertexP[1] - vertexP[0]; vec3 v2 = vertexP[2] - vertexP[0]; vec3 surfNormal = normalize(cross(v1, v2)); If the winding order of the triangles is clockwise, you have to swap v1 and v2: vec3 surfNormal = normalize(cross(v2, v1)); Use the Dot product to ensure that the orientation of the surface normal correct when mixing the winding order of the triangles: surfNormal *= sign(dot(surfNormal, vertexN[0]+vertexN[1]+vertexN[2]));
69,855,772
69,917,577
Can a lock-free atomic write / consistent read operation be achieved on a 4 byte int using System V shared memory across language platforms?
I want to implement a lock free counter, a 4-byte int, in System V shared memory. The writer is a C++ program, the reader is a Python program. Working roughly like this: C++ code updates counter in an atomic operation Python code reads counter and has a consistent view of memory (eventual consistency is perfectly acceptable) No locks are implemented to achieve this Within the C++ language there are atomic get/update operations that allow for this and guarantee memory consistency, I believe the same is true in Python. However, as I understand it, the assumptions in C++ regarding atomic operations do not necessarily apply to code written and compiled in another language and compiler. Is there a way to achieve a consistent view of shared memory across languages that doesn't involve implementing low level locks?
Yes, using the atomics library, along with a suitable shared memory library (e.g. mmap or shared_memory). This example assumes your atomic int is in the first 4 bytes of the shared memory segment. from atomics import atomicview, MemoryOrder, INT from multiprocessing import shared_memory # connect to existing shared memory segment shmem = SharedMemory(name="test_shmem") # get buf corresponding to "atomic" region buf = shmem.buf[:4] # atomically read from buffer with atomicview(buffer=buf, atype=INT) as a: value = a.load(order=MemoryOrder.ACQUIRE) # print our value print(value) # del our buf object (or shmem.close() will complain) del buf # close our shared memory handle shmem.close() We can use ACQUIRE memory order here rather than the default SEQ_CST. The atomicview can only be created and used with a with statement, so you will need to manually keep your buf around (and manage its lifetime correctly). Note: I am the author of this library
69,855,859
69,855,935
Compile time errors while implement Virtual Functions and Run-time polymorphism in C++
I created the following program to implement Run-time Polymorphism in C++ /* Consider a book shop which sells both books and video-tapes. Create a class know as media that storea the title and price of a publication.*/ #include <iostream> #include <cstring> using namespace std; class media // defining base class { protected: char title[50]; float price; public: media(char *s, float a) { strcpy(title, s); price = a; } virtual void display() {} }; class book : public media // defining derived class 'book' which is derived from 'media' { int pages; public: book(char *s, float a, int p) : media(s, a) // constructor of derived class { pages = p; } void display() {} }; class tape : public media // defining derived class 'tape' which is derived from 'media' { float time; public: tape(char *s, float a, float t) : media(s, a) // constructor of derived class { time = t; } void display() {} }; void book ::display() // function to display book details { cout << "\n Title: " << title; cout << "\n Pages: " << pages; cout << "\n Price: " << price; } void tape::display() // function to display tape details { cout << "\n Title: " << title; cout << "\n Playtime: " << time; cout << "\n Price: " << price; } int main() { char *title = new char[30]; // creating a array of characters using 'new' for storing title float price, time; int pages; //Book Details cout << "\n Enter Book Details \n"; cout << "Title: "; cin >> title; cout << "Price: "; cin >> price; cout << "Pages: "; cin >> pages; book book1(title, price, pages); //Tape Details cout << "\n Enter Tape Details \n"; cout << "Title: "; cin >> title; cout << "Price: "; cin >> price; cout << "Play time (mins): "; cin >> time; tape tape1(title, price, time); media *list[2]; list[0] = &book1; list[1] = &tape1; cout << "\n Media Details"; cout << "\n.....Book...."; list[0]->display(); // display Book details cout << "\n.....Tape...."; list[1]->display(); // display Tape details return 0; } It uses Constructor, 'new' memory allocator operator and virtual functions for its purpose The question is: Consider a book shop which sells both books and videotapes. Create a class known as media that store the title and price of a publication. But it ends up with the following errors virtual_function.cpp:47:6: error: redefinition of ‘void book::display()’ 47 | void book ::display() // function to display book details | ^~~~ virtual_function.cpp:32:10: note: ‘virtual void book::display()’ previously defined here 32 | void display() {} | ^~~~~~~ virtual_function.cpp:54:6: error: redefinition of ‘void tape::display()’ 54 | void tape::display() // function to display tape details | ^~~~ virtual_function.cpp:44:10: note: ‘virtual void tape::display()’ previously defined here 44 | void display() {} | ^~~~~~~ I'm using GNU-GCC Compiler in VSCode on Ubuntu
The problem is instead of declaring the function display inside class book and tape you were defining them because you have curly braces {}. And then you again redefined them outside the class. To solve this, just replace: void display() {} with void display() ; in class book and tape. So your class book and tape would now look like: class book : public media { int pages; public: book(char *s, float a, int p) : media(s, a) { pages = p; } void display(); //a declaration. I removed the curly braces {} you had here }; class tape : public media { float time; public: tape(char *s, float a, float t) : media(s, a) { time = t; } void display() ; //a declaration.I removed the curly braces {} you had here }; Note in the above code i have removed the braces {} and replaced them with a semicolon for the function display(). The program now works(that is it no longer have the errors you mentioned) as can be seen here.
69,856,425
69,857,216
free(): double free detected in tcache 2 on calling assignment operator
I've just asked a very similar question, but I've been over the answers to that one and I just can't see what I'm doing wrong this time around. I'm working on a university project implementing the c++ list<int> using a linked list. I'm working on the assignment operator, and here's what I have so far. Linkedlist &Linkedlist::operator=(const Linkedlist &l) { clear(); if(l.empty()) { return *this; } Node *iterRight = l.head; head = new Node; Node *iterLeft = head; while(iterRight != NULL) { iterLeft -> data = iterRight -> data; iterLeft -> next = new Node; iterLeft -> next -> prev = iterLeft; iterLeft = iterLeft -> next; iterRight = iterRight -> next; } return *this; } When I run, the assingment operator DOES work to copy the data from one list to another, but I get this after the run - free(): double free detected in tcache 2 I don't understand how I used my pointers inappropriately. Can someone show me what I'm doing wrong? EDIT: The destructor might be useful too. ``` Linkedlist::~Linkedlist() { Node *del; while(head != NULL) { del = head; head = head -> next; delete del; } } EDIT: My apologies, I'm very new to Stack Overflow. If I understand a MRE correctly, here's the minimum amount of code to reproduce (Everything above with the addition of my main program and my constructor). int main() { Linkedlist a(20); Linkedlist b = a; return 0; } Linkedlist::Linkedlist(unsigned int n) { size = n; tail = NULL; head = new Node; Node *iter = head; for(int i = 0; i < n; i++) { iter -> data = i; iter -> next = new Node; iter -> next -> prev = iter; iter = iter -> next; } tail = iter -> prev; tail -> next = NULL; } Calling the constructor for the Linkedlist a does not crash, it only crashes once I call the assignment. I ran my program in valgrind, but since I'm rather new at memory management, I'm not quite sure what I'm looking at. It shows me and invalid free() in my destructor, but I can't find where it was already free'd prior.
The line: Linkedlist b = a; calls copy constructor, not assignment operator. If you didn't provide copy constructor, then the compiler-generated one will just copy head pointer. Then, during destruction the same head will be deleted both from list a and list b leading to "double free".
69,856,792
69,859,627
Winsock connect fails with WSAEFAULT | Error on Windows 11 only
My code perfectly works on any Windows from XP to 10. Now I've tested my code for the first time in Win11, and the connect() function fails with error 10014 WSAEFAULT: Bad address. The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr). However as I checked with my debugger, the sockaddr_in structure seems to be passed correctly: connect(hSocket, (sockaddr*)(&InSockAddr), sizeof(InSockAddr)) I am using Visual C++ 2015 compiler. Here is a snipped of the relevant code: #include <WinSock2.h> class CConnection { public: static bool bWinsockInitialized; SOCKET hSocket = INVALID_SOCKET; sockaddr_in sockAddr; bool Create(); bool InitializeWinsock(); bool Connect(sockaddr_in &InSockAddr); }; CConnection sckt_Main; sockaddr_in g_sockAddr; void main() { if (!sckt_Main.Create()) { // Error: Unable to create connection socket return; } g_sockAddr.sin_family = AF_INET; // Get IP address from string. // If address is a DNS, HostInfo->h_addr will contain resolved IP address. // Save host information into HostInfo struct: hostent* HostInfo = gethostbyname("127.0.0.1"); //Error checking: if (!HostInfo) { return; } assert((sizeof(g_sockAddr.sin_addr)) >= HostInfo->h_length); //Copy the resolved IP address into our sockAddr structure: memcpy(&g_sockAddr.sin_addr, HostInfo->h_addr, HostInfo->h_length); //Saves connection port g_sockAddr.sin_port = htons(atoi("2405")); sckt_Main.Connect(g_sockAddr); } bool CConnection::Create() { if (!InitializeWinsock()) { return false; } hSocket = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP); if (this->hSocket == INVALID_SOCKET) return false; return true; } bool CConnection::InitializeWinsock() { WSADATA wsaData; if (!WSAStartup(MAKEWORD(2, 2), &wsaData)) { bWinsockInitialized = true; } else bWinsockInitialized = false; return bWinsockInitialized; } bool CConnection::Connect(sockaddr_in &InSockAddr) { // If no error occurs, connect returns zero. // Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError. if (connect(hSocket, (sockaddr*)(&InSockAddr), sizeof(InSockAddr)) == 0) { // Connect SUCCESS return true; } else { // !!! connect error !!! int err = WSAGetLastError(); return false; } }
As noted in the comments, your code is not IPv6 aware. Windows 11 ships with IPv6 enabled by default. You should update your code to be IPv4 vs. IPv6 agnostic. See Microsoft Docs. Note Microsoft stop shipping checkv4.exe ages ago, but if I run it against your code I get: sockaddr_in : use sockaddr_storage instead, or use sockaddr_in6 in addition for IPv6 support AF_INET : use AF_INET6 in addition for IPv6 support gethostbyname : use getaddrinfo instead hostent : use addrinfo instead
69,856,891
69,856,983
C++ including Python.h compiling using makefile
I am trying to compile a C++ program which uses Python.h to execute some python scripts. Before adding the python, I had a makefile which works perfectly. I added the code to run the python script, which involves including the Python.h file. I edited the makefile to include this file, without success. My makefile: CC = g++ SHELL = /bin/sh EXECUTABLES = Software_V2 CFLAGS += -O2 -g0 -Wall -pedantic -Wstrict-prototypes -std=c99 $(shell python3-config --cflags) LIBS = -lm -lrt -laes_access -lstdc++ -pthread OBJS = $(EXECUTABLES).o .PHONEY: all all: $(EXECUTABLES) .PHONEY: clean clean: rm -f *.[bo] rm -f *.err rm -f $(EXECUTABLES) $(EXECUTABLES): $(OBJS) $(CC) $(OBJS) $(CFLAGS) $(LIBS) -o $@ I already installed following libraries: sudo apt-get install python-dev sudo apt-get install python3-dev sudo apt install libpython3.7-dev The error after running make I'm receiving the following error: g++ -c -o Software_V2.o Software_V2.cpp Software_V2.cpp:3:10: fatal error: Python.h: No such file or directory #include <Python.h> ^~~~~~~~~~ compilation terminated. make: *** [<builtin>: Software_V2.o] Error 1 I also tried changing the include from #include <Python.h> to #include <python3.7m/Python.h> None of my tries succeeded, I'm out of inspiration at this moment to try some new things, maybe you guys know how to solve my problem. Thank you!
You are mixing C and C++. These are completely different languages: you shouldn't confuse them. In makefiles, the default rules use CC to hold the C compiler and CXX to hold the C++ compiler. Similarly, they use CFLAGS to hold flags for the C compiler and CXXFLAGS to hold flags for the C++ compiler. In your makefile you've not set either the CXX or the CXXFLAGS variables, but you're trying to use the default rule to build your object file. The default value for CXX is g++ (on your system) and the default value for CXXFLAGS is empty. That's why when make shows you the compile command, none of your options appear there: g++ -c -o Software_V2.o Software_V2.cpp If you're trying to compile C++ code (implied by the fact that your filename extension is .cpp not .c) then you should set CXXFLAGS not CFLAGS. Also, it's wrong to set -std=c99 if you're trying to compile C++; that flag sets the C 1999 standard, not C++.
69,857,081
69,863,213
how could I use the power function in c/c++ without pow(), functions, or recursion
I'm using a C++ compiler but writing code in C (if that helps) There's a series of numbers (-1^(a-1)/2a-1)B^(2a-1) A and X are user defined... A must be positive, but X can be anything (+,-)... to decode this sequence... I need use exponents/powers, but was given some restrictions... I can't make another function, use recursion, or pow() (among other advanced math functions that come with cmath or math.h). There were plenty of similar questions, but many answers have used functions and recursion which aren't directly relevant to this question. This is the code that works perfectly with pow(), I spent a lot of time trying to modify it to replace pow() with my own code, but nothing seems to be working... mainly getting wrong results. X and J are user inputted variables for (int i = 1; i < j; i++) sum += (pow(-1, i - 1)) / (5 * i - 1) * (pow(x, 5 * i - 1)); }
It is a series. Replace pow() based on the previous iteration. @Bathsheba Code does not need to call pow(). It can form pow(x, 5 * i - 1) and pow(-1, i - 1), since both have an int exponent based on the iterator i, from the prior loop iteration. Example: Let f(x, i) = pow(x, 5 * i - 1) Then f(x, 1) = x*x*x*x and f(x, i > 1) = f(x, i-1) * x*x*x*x*x double power_n1 = 1.0; double power_x5 = x*x*x*x; for (int i = 1; i < j + 1; i++) // sum += (pow(-1, i - 1)) / (5 * i - 1) * (pow(x, 5 * i - 1)); sum += power_n1 / (5 * i - 1) * power_x5; power_n1 = -power_n1; power_x5 *= x*x*x*x*x; }
69,857,124
69,913,213
Can we use auto keyword instead of template?
Can we use auto keyword instead of template? Consider following example : #include <iostream> template <typename T> T max(T x, T y) // function template for max(T, T) { return (x > y) ? x : y; } int main() { std::cout << max<int>(1, 2) << '\n'; // instantiates and calls function max<int>(int, int) std::cout << max<int>(4, 3) << '\n'; // calls already instantiated function max<int>(int, int) std::cout << max<double>(1, 2) << '\n'; // instantiates and calls function max<double>(double, double) return 0; } So we can write it this way too : #include <iostream> auto max(auto x, auto y) { return (x > y) ? x : y; } int main() { std::cout << max(1, 2) << '\n'; std::cout << max(4, 3) << '\n'; std::cout << max(1, 2) << '\n'; return 0; } So, why should use auto keyword instead of template?
Finally I found the answer to my question: We can use abbreviated function templates if we're using the C++20 language standard. They are simpler to type and understand because they produce less syntactical clutter. Note that our two snippets are not the same. The top one enforces that x and y are the same type, whereas the bottom one does not.
69,857,519
69,863,090
Taking input from editbox as displaying the result
I am currently working on an MFC C++ program that takes a mathematical expression as input and displays the result. But I am having trouble reading from the editbox. The code for taking in input and displaying it is as below: { char input[50]; sprintf_s(input, "%d", IDC_EDIT1); len = strlen(input); ... ... CString s; s.Format(_T("%.2f"), mCurVal); SetDlgItemText(IDC_EDIT1, s); } IDC_EDIT1 is the input from the editbox. I want to change that to a char so I can be able to call each character and compute the mathematical operation. The middle part I committed works well so I tried everything to see where the problem is and seems like it is in the first 3 lines. Can anyone please help me?
You want this: { CString input; GetDlgItemText(IDC_EDIT1, input); len = input.GetLength(); ... CString s; s.Format(_T("%.2f"), mCurVal); SetDlgItemText(IDC_EDIT1, s); } Forget char arrays like char input[50]; if you're using MFC, you can use CString almost all the time instead.
69,857,528
69,857,689
C++20 Likely and UnLikely?
I was reading https://iq.opengenus.org/cpp-likely-and-unlikely-attributes/ and I don't understand/agree with few things. In the following code: void doModulus( vector<int> &vec , int mod ){ // here the value of mod we are passing is 224, vec is of size 1024 holding values in [1,255] for( int i = 0 ; i<vec.size() ; i++ ) { if( vec[i] >= mod ) [[unlikely]]{ // so we are prioritizing else statement here vec[i] = vec[i] % mod ; }else { vec[i] = vec[i] ; } } } does it matter or make any difference if we make the else code [[likely]] or this happens automatically in background as if one side is likely then the other side isn't? (Although I would like it to be that if the one side is unlikely then the other side (if it was likely) to be strongly likely. The following claim was made: % operation is a computationally heavy operation for cpu , so let's try to optimize our code. While the "optimize" refers to adding the if else conditions, but I tested the code using chrono and it seems execution time was 2-3 times faster without if-else... Plus I don't see why % is heavy, it's just about reading bottom bits of number.
does it matter or make any difference if we make the else code [[likely]] or this happens automatically in background as if one side is likely then the other side isn't? The C++ Standard say about likely just recommended practice and example. See [dcl.attr.likelihood]. So it is up to the implementation how they are actually used. Though recommended practice and example imply that only one mark is needed, and compilers where the difference is observed seem to imply this as well. Plus I don't see why % is heavy, it's just about reading bottom bits of number. Only for a power of two. But it should be known that is is power of two in compile time. There's also a way to make this operation cheaper for a known not a power of two constant (Why does GCC use multiplication by a strange number in implementing integer division?). For a runtime value it is heavy, it is division. It might happen that a value is known to the optimizer due to constant propagation though. Then optimizations apply.
69,857,618
69,865,933
fmt::dynamic_format_arg_store replacement/implementation for std::format
It looks like that c++20 std::format is not a direct replacement for the fmt library. Looking at the API (https://en.cppreference.com/w/cpp/utility/format) it looks like that fmt::dynamic_format_arg_store is not part of the standard. Currently in fmt you can have the following code: #include <fmt/format.h> #include <fmt/args.h> int main() { auto store = fmt::dynamic_format_arg_store<fmt::format_context>(); store.push_back(42); store.push_back( std::string { "abc1"} ); store.push_back(1.5f); fmt::vprint("{} this is my {}. This is a number: {}.", store); } I would like to replace fmt with the standard std::format. I had a very quick look at fmt::dynamic_format_arg_store and it looks like it is using a few internal things from fmt so it didn't look that straight forward. Anyone can provide some guidance on how to implement the above functionality outside of fmt for C++20 using std::format ? edit: Looking a bit deeper in fmt:dynamic_format_arg_store it looks like it is using detail:make_arg to create an argument. I don't know how I can get something equivalent from std::format as I only see std::make_format_args which returns a different type. Is fmt:dynamic_format_arg_store possible to be implemented for std:format without getting into implementation specific details for each compiler ?
You cannot portably implement an equivalent of fmt::dynamic_format_arg_store for std::format yourself because the representation of std::basic_format_args is an implementation detail of the standard library. It might be provided in one of the future versions of the C++ standard.
69,858,031
69,858,197
Create std::list unique_ptr from variadic template
I try to create std::list from args, but when pass more than 0 params get an error "no matching function for call to 'make_unique'". I think that the mistake is that I pass all the arguments to make_unque at once, but I do not understand how to open the bundle 2 times. template<class ...Args> void do(Args&&... args) { std::list<std::unique_ptr<Base>> obj(std::make_unique<Child>(std::forward<Args>(args)...)); }
Syntax would be: template<class ...Args> void do(Args&&... args) { std::list<std::unique_ptr<Base>> obj{std::make_unique<Child>(std::forward<Args>(args))...}; } but you cannot move elements from std::initializer_list (their element are const). A possible workaround is to emplace: template<class ...Args> void do(Args&&... args) { std::list<std::unique_ptr<Base>> obj; #if 0 // C++17 (obj.emplace(std::make_unique<Child>(std::forward<Args>(args)), ...); #else // C++11 and C++14 int dummy[] = {0, (obj.emplace(std::make_unique<Child>(std::forward<Args>(args)), 0)...}; static_cast<void>(dummy); // avoid warning for unused variable. #endif }
69,858,137
69,858,537
What type of filter is this?
output = (((previous * rate) + current) / (rate + 1.0)) I believe it's a low pass, but correct me if I'm wrong. Is there a more accurate way to describe a function like this?
This is a low pass filter, with an Infinite Impulse Response design. The rate is used to determine how much a single new value can change the output. A large rate puts more value on the previous state, and less on the current value. Consider when rate is 1: output is 1/2 of the previous value plus 1/2 of the current value. In other words, it's the average of the two. When rate is larger, output is more heavily weighted to the previous value, so high-frequency variations in subsequent values of current are filtered out, and only slow changes to current affect the output.
69,858,189
69,858,955
CMake can't find file or directory
I'm working on a CMake project with multiple subdirectories and I can't get it to work. My working directory is the following: ├───main.cpp ├───CMakeLists.txt ├───build ├───States └───CMakeLists.txt └───Elevator ├───CMakeLists.txt Once I build the project, I get Elevator/Elevator.h: No such file or directory as an error. The way my project is set up, Elevator is included in States and apparently CMake isn't linking them properly. My root CMakeLists.txt: cmake_minimum_required(VERSION 3.21.4) project(Test) set(CMAKE_CPP_STANDARD 11) set(CMAKE_CPP_STANDARD_REQUIRED True) add_subdirectory(Elevator) add_subdirectory(States) add_executable(${PROJECT_NAME} main.cpp) target_link_libraries(${PROJECT_NAME} PUBLIC Elevator States) The one in Elevator: set(elevator_source_files Elevator.cpp Elevator.h Set.cpp Set.h ) add_library(Elevator ${elevator_source_files}) The CMakeLists.txt in States: set(state_source_files State.h State.cpp InitialState.h InitialState.cpp EmergencyState.cpp EmergencyState.h IdleState.h IdleState.cpp MaintenanceState.h MaintenanceState.cpp MovingState.h MovingState.cpp AllStates.h FSM.h FSM.cpp ) add_library(States ${state_source_files}) target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR}/..) target_link_libraries(States PUBLIC Elevator) I'm still a novice so any help would be appreciated! It's worth noting that States.h includes Elevator with #include "Elevator/Elevator.h" UPDATE: The project now builds and runs. I updated the CMake files in the description.
For #include "Elevator/Elevator.h" to work in the States library you need to include the folder containing the Elevator folder. One way to fix this is to change target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR}) to target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_CURRENT_LIST_DIR}/..) to have CMake add the State folder and its parent to the include directories.
69,858,292
69,858,452
I am working on airline management system. Here User enters the selected destination from shown destinations,so it's showing INVALID DESTINATION
string dest; string local_des[4]={"HYDERABAD","KOLKATA","GWALIOR","DELHI"}; string inter_des[5]={"USA","PARIS","DUBAI","LAS VEGAS","LONDON"}; char option; cout<<"\nPlease select your destination type:\n"; cout<<"1.Local Destinations\n"; cout<<"2.International Destinations\n"; cout<<"\nENTER YOUR CHOICE(1 or 2)\n"; cin>>option; stat=0; switch(option){ case '1': for(a=0;a<4;a++){ cout<<"\n"<<local_des[a]; } cout<<"Now Enter Your Destination(IN BLOCK LETTERS):"; cin.ignore(); getline(cin,dest); for(int i=0;i<4;i++){ if(dest==local_des[i]){ stat=1; } else{ stat=0; } } if(stat==1){ cout<<"DESTINATION CONFIRMED!\n"; } else{ cout<<"INVALID DESTINATION\n"; } break; case '2': for(b=0;b<5;b++){ cout<<inter_des[b]; } cout<<"Now Enter Your Destination(IN BLOCK LETTERS):"; cin.ignore(); getline(cin,dest); for(int j=0;j<5;j++){ if(dest==inter_des[j]){ stat=1; } else{ stat=0; } } if(stat==1){ cout<<"DESTINATION CONFIRMED!\n"; } else{ cout<<"INVALID DESTINATION\n"; } break; default: cout<<"INVALID OPTION"; } I am working on airline management system where i need to show destinations for users. In above code, You can see switch statements,so whatever user inputs as destination ,it's throwing INVALID DESTINATION as output.It will be very helpfull if anyone can help with this bug.Thanks in advance:)
You will want to fix this loop: for (int j = 0; j < 5; j++) { if (dest == inter_des[j]) { stat = 1; } else { stat = 0; // Resets stat to 0 } } Currently stat will be 0 unless the last item in the inter_des was the same as dest. That is because every time that dest is not matched to the current item it sets stat to 0 even if it had already found a match earlier in the loop. Instead you want this which will set stat to 1 if dest is found in any position and end the loop when it is found: stat=0; for (int j = 0; j < 5 && stat == 0; j++) { if (dest == inter_des[j]) { stat = 1; // The loop will end on the next iteration because stat is no longer 0 } } You have the same bug in the loop for local_des[].
69,858,324
69,858,529
Are there any pitfalls to using std::move() in value-oriented property setter?
I came across this answer to how to write C++ getters/setters and the author implies that when it comes to value-oriented properties, the setters in the standard library use the std::move() like this... class Foo { X x_; public: X x() const { return x_; } void x(X x) { x_ = std::move(x); } } (code taken directly from the aforementioned answer) ... to leverage the move operator, if it is specified, potentially improving performance. That itself makes sense to me - the values are copied once when passed by value to the method, so there's no need to copy them a second time to the property if they can be moved instead. However, my knowledge of C++ isn't good enough to be certain that doing this is safe in all cases. Does passing an argument by value always make a deep copy? Or does it depend on the object? Considering the std::move() supposedly "signals the compiler I don't care what happens to the moved object", this could have unexpected side effects if I intended the original object to stay. Apologies if this is a well-known problem, I'm in the process of learning C++ and am really trying to get to the bottom of the language.
Yes there is. Receiving a parameter by value and move is okay if you always send an rvalue to that parameter. It is also okay to send an lvalue, but will be slower than receiving by const ref, especially in a loop. Why? It seem that instead of making a copy you simply make a copy and then move, in which the move in insignificant in term of perfomance. False. You assume that a copy assignment is as slow as a copy constructor, which is false. Consider this: std::string str_target; std::string long1 = "long_string_no_sso hello1234"; std::string long2 = "long_string_no_sso goobye123"; str_target = long1; // allocation to copy the buffer str_target = long2; // no allocation, reuse space, simply copy bytes This is why for setter function, by default, you should receive by const ref by default, and add a rvalue ref to optimize for rvalues: class Foo { X x_; public: X x() const { return x_; } // default setter, okay in most cases void x(X const& x) { x_ = x; } // optionally, define an overload that optimise for rvalues void x(X&& x) noexcept { x_ = std::move(x); } }; The only place where this does not apply is on constructor parameter and other sink functions, since they always construct and there is no buffer to reuse: struct my_type { // No buffer to reuse, this->_str is a totally new object explicit my_type(std::string str) noexcept : _str{std::move(str)} private: std::string _str; };
69,858,579
69,858,810
Why does >> operator gives error on const file in C++?
I have this piece of code: void NeighborsList::insertVertexes(const ifstream & inputFile) { int tempS, tempT; for (int i = 0; i < numOfVertexes; i++) { inputFile >> tempS; inputFile >> tempT; addEdge(tempS, tempT); } } where I'm trying to get the input for a file. Once I remove the const in the function parameter - (ifstream & inputFile) it works.
Given a const object or reference, only const operations may be performed. std::istream::operator>> is not a const operation, therefore it may not be used here. It makes sense that std::istream::operator>> is not a const operation, because it alters the observable state of the stream. The read position on the file is changed, for example, as well as status indicators like fail and eof.
69,859,146
69,859,554
What does `class function<_Res(_ArgTypes...)>` mean?
The code of std::function in gcc has these two lines: template<typename _Res, typename... _ArgTypes> class function<_Res(_ArgTypes...)> // <-- unclear to me The first part template... _ArgTypes denotes a "parameter pack", i.e., a variadic number of template parameters; that is clear. But the second line is magic. OK, writing class function<SmthHere> means template specialization, so we specialize class function with _Res(_ArgTypes...). The latter looks like a function call with a variable number of arguments. However if _Res is void and _ArgTypes is int, we get void(int): this doesn't make sense to me as we can't have a function named void and pass an argument int to it (??). Is this a specially supported syntax? Could you clarify?
I think you are confused about the declaration syntax (which is inherited from C language): here, the syntax void(int) does not mean that a function named void and taking an argument named int is being called. Instead, it denotes a type, which is a function, taking a parameter of type int and returning void. You can read more about function declaration syntax at C++ Reference, there are some examples as well.
69,859,683
69,859,810
Assigning a reference to a struct
I have a variable ntot_sols who's final value isn't known when my object is constructed. Consequentially I want to store a reference to the variable instead of the value since it's subject to change. I think the following code will do it. struct ItemWeighter { int nsols; int ntot_sols; ItemWeighter(int _nsols, int& _ntot_sols) { nsols = nsols; ntot_sols = _ntot_sols; } float weight() { return nsols / float(ntot_sols); } }; But I'm surprised that ntot_sols is type int and not int &. How does the variable know that it's a reference?
You can't use the assignment operator to bind a reference. It has to be bound when first created. For a class member variable, this means you have to do it in a member initializer list; the body of the constructor is too late. Example: #include <iostream> class foo { private: int& x; public: foo(int& other_var) : x(other_var) { } ~foo() { } void print_x() { std::cout << x << std::endl; } }; int main() { int a = 5; foo my_foo(a); my_foo.print_x(); a = 10; my_foo.print_x(); return 0; } Try on godbolt. It prints out: 5 10 Note that such code, where your object holds a reference to another variable created elsewhere, can be risky. It is up to you to make sure that the referenced int has a lifetime at least as long as the foo object. It can be easy to get this wrong, and the compiler won't help you. Consider for instance: foo make_a_foo() { int a = 7; foo f(a); return f; } void other_func() { foo g = make_a_foo(); g.print_x(); // undefined behavior! } Here g.x is a reference to the local variable a from make_a_foo(), whose lifetime ended when make_a_foo() returned. It may be better after all to make x an ordinary int member variable, instead of a reference, and call a setter function to update its value when needed.
69,859,805
69,885,842
Consequences of and alternatives to use std::forward on non-forwarding-reference type template parameter
I am writing a factory. Both "interface" and the "implementation" are defined by template classes. #include <memory> template<class I, class ...Args> struct IFactory { virtual std::unique_ptr<I> Create(Args... args) = 0; }; template<class I, class C, class ...Args> struct Factory : IFactory<I, Args...> { std::unique_ptr<I> Create(Args... args) override { return std::make_unique<C>(std::forward<Args>(args)...); // args are no forwarding references } }; The code violates the sonar source rule RSPEC-5417, which states: std::forward has a single use-case: to cast a templated function parameter of type forwarding reference (T&&) to the value category (lvalue or rvalue) the caller used to pass it. [...] An error [...] has less dire consequences [than using std::move on a forwarding reference], and might even work as intended if the right template argument is used, but the code would be clumsy and not clearly express the intent. [Emphasis by me] I wonder, what are the less dire consequences if wrong template arguments used? what are the wrong template arguments? how to ensure the right template parameters are used? how to write the code less clumsy and express intent more clearly? I considered to use static_cast<Args&&>() directly, but that would make the code less readable in my opinion and i think it would only re-implement std::forward. Example usage of Factory<...> shows that Factory::Create() generates one additional move construction (for the ctor argument T1 a, in the example below): #include <string> #include <iostream> void P(std::string msg){std::cout << msg << std::endl;} // Debug print // Some types used as ctor arguments types of the class for which we want to create objects. struct T1{T1()=default; T1(const T1&){P("T1&");} T1(T1&&){P("T1&&");}}; // Move- and copyable struct T2{T2()=default; T2(const T2&){P("T2&");} T2(T2&&)=delete; }; // Copyable struct T3{T3()=default; T3(const T3&)=delete; T3(T3&&){P("T3&&");}}; // Moveable struct T4{T4()=default; T4(const T4&)=delete; T4(T4&&)=delete; }; // None of move/copy // Interface of the class struct IType { /*Some pure virtual functions.*/ }; struct Type : IType { T1 t1; T2 t2; T3 t3; T4& t4; Type(T1 a, const T2& b, T3&& c, T4& d) :t1(a), t2(b), t3(std::move(c)), t4(d) {} }; void F(const IFactory<IType, T1, const T2&, T3&&, T4&>& factory) { T1 t1; T2 t2; T3 t3a, t3b; T4 t4; std::cout << "Ctor:\n"; Type obj1(t1, t2, std::move(t3a), t4); std::cout << "Factory:\n"; auto ptri1 = factory.Create(t1, t2, std::move(t3b), t4); } int main() { Factory<IType, Type, T1, const T2&, T3&&, T4&> factory1; F(factory1); return 0; } Output: Ctor: T1& T1& T2& T3&& Factory: T1& T1&& <- additional move for the not optimal ctor argument T1& T2& T3&& Example on gobolt.org
If a template argument is deduced other than from a forwarding reference, it is never deduced as a reference: then std::forward<T> is just the overload set T&& forward(T&); T&& forward(T&&); which behaves exactly like std::move. If the function parameter was declared as T&, this is misleading: the argument will be moved from, so the function should probably accept an rvalue (or forwarding) reference instead. If the function parameter is just T, std::forward is harmless since the parameters are your own objects, but you might as well just use std::move. Your case, however, is a bit different: this interface requires explicit template arguments, which can be references at the discretion of the client. If it’s not a reference, it again behaves like std::move. If it is, then std::forward reproduces the same kind of reference, which seems to be the correct behavior. For completeness, consider the case of explicitly specifying the template argument for a function that accepts T&: regardless of the reference status of the template argument, the function will accept an lvalue reference, and will move from it(!) if the template argument is itself not a reference or an rvalue reference. The same two cases will result in a move when forwarding a non-forwarding T&& parameter, but then the (function) argument must be an rvalue. In conclusion, using std::forward<T> when the parameter is T& is wrong whether or not T is deduced, but is correct for T or T&& regardless. The quoted guideline is too strict in that case: the deduced-T case should just be std::move, but your usage is useful and correct.
69,860,863
69,899,951
Non-type template parameter specialization
When I compile with GCC it requires switch (A) to be set, while MSVC and Clang can't find MyType specialization and vice versa. Who is right? template <std::size_t col_size, auto val> struct sized_t2 { // static constexpr std::size_t size = col_size; // static constexpr auto value = val; using type = decltype(val); }; template <typename> struct MyType; /* // (A) #define GCC_CONST const /*/ #define GCC_CONST //*/ template <std::size_t col_size, auto val> struct MyType<GCC_CONST sized_t2<col_size, val>> { using type = int; }; template<sized_t2... Cols> auto Test2() { using XXX = std::tuple<typename MyType<decltype(Cols)>::type...>; (void)XXX{}; return; } int main() { struct x{}; Test2<sized_t2<42,x{}>{}>(); }
This is a GCC bug: decltype applied to a template parameter gives the (adjusted, deduced) type of the parameter, not of the (const-qualified) template parameter object to which the parameter name refers as an expression if it is of class type ([dcl.type.decltype]/1.2). Extra parentheses may be used as usual to obtain the expression interpretation.
69,860,976
69,861,386
C++ String Segfault on RHEL 8 with flto (but not RHEL 7)
I have this sample code: # CMakeLists.txt cmake_minimum_required(VERSION 3.18) project(RHBuildTest CXX) message(STATUS "C++ Compiler: ${CMAKE_CXX_COMPILER}") add_executable(script1 script1.cpp) set_target_properties(script1 PROPERTIES COMPILE_FLAGS "-flto") // script1.cpp #include <string> #include <iostream> int main() { const std::string msg = "this is a string"; std::cout << "msg.size(): " << msg.size() << "\n"; std::cout << "msg: " << msg << "\n"; std::cout << "msg.substr(0): " << msg.substr(0) << "\n"; return 0; } We now compile against g++ 10.2.0 on RHEL 7 and RHEL 8, but RHEL 8 gives a segault. If we take out -flto, then RHEL 8 runs just fine. Is this an ABI issue? Do I need to set certain paths so that the correct standard libs are loaded (when using -flto)? What could be causing this issue? RHEL 7: [~/code/rh_build_test/build_rh7]$ cat /etc/redhat-release; cmake ..; make; ./script1 Red Hat Enterprise Linux Server release 7.7 (Maipo) -- C++ Compiler: /app/.../el7.3.10/x86_64-gcc10.2.x/gcc-10.2.0/bin/g++ -- Configuring done -- Generating done -- Build files have been written to: ~/code/rh_build_test/build_rh7 [ 50%] Building CXX object CMakeFiles/script1.dir/script1.cpp.o [100%] Linking CXX executable script1 [100%] Built target script1 msg.size(): 16 msg: this is a string msg.substr(0): this is a string RHEL 8: [~/code/rh_build_test/build_rh8]$ cat /etc/redhat-release; cmake ..; make; ./script1 Red Hat Enterprise Linux release 8.4 (Ootpa) -- C++ Compiler: /app/.../el8_4.4.18/x86_64-gcc10.2.x/gcc-10.2.0/bin/g++ -- Configuring done -- Generating done -- Build files have been written to: ~/code/rh_build_test/build_rh8 [ 50%] Building CXX object CMakeFiles/script1.dir/script1.cpp.o [100%] Linking CXX executable script1 [100%] Built target script1 Segmentation fault (core dumped) Sometimes RHEL 8 prints a bit more, but it always fails at substr: ... [100%] Built target script1 msg.size(): 16 msg: this is a string Segmentation fault (core dumped)
This is a known bug in RHEL: Segfault when -flto is used to compile Catch framework tests on RHEL 8.4 To confirm that's the same bug you're running into, see if temporarily downgrading binutils to 2.30-79.el8 makes it work. If so, then it looks like it will be properly fixed when RHEL 8.5 is released. (EDIT: I just confirmed that this is indeed fixed in binutils 2.30-108, which was released with RHEL 8.5.)
69,861,396
69,861,629
How replicate eigen::matrix dynamically
During calculating the distance matrix between two feature maps. A:(M,1) B:(N,1) I want to repeat B columns to equal A rows. It is simple in NumPy: A = np.random,rand(100, 1) B = np.random.rand(88, 1) np.repeat(B, A.shape[0], axis=1) But in c++ Eigen, not work for dynamically assigning repeated shapes. MatrixXi A = MatrixXi::Random(100,1); MatrixXi B = MatrixXi::Random(88,1); B.replicate<1, A.rows()>(); // This will cause failure
The correct way to achieve the same effect as the python's numpy version in C++ would be: B.replicate<1, 100>(); The above will do the replication as you want. Or you can use: B.replicate(1, A.rows());
69,861,500
69,876,457
Making a POST request in C++ with curlpp
I am attempting to make a POST request using curlpp in C++ to Statistics Canada with their getDataFromVectorsAndLatestNPeriods. I can't seem to get a result from the request. #include <stdlib.h> #include <stdio.h> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> int main() { curlpp::Cleanup cleanup; curlpp::Easy request; curlpp::Forms form; request.setOpt(curlpp::options::Url(std::string("https://www150.statcan.gc.ca/t1/wds/rest/getDataFromVectorsAndLatestNPeriods"))); request.setOpt(curlpp::options::Verbose(true)); form.push_back(new curlpp::FormParts::Content("vectorID:54325508","latestN:1")); request.setOpt(new curlpp::options::HttpPost(form)); request.setOpt(new curlpp::options::WriteStream(&std::cout)); request.perform(); return 0; } I compiled it with g++ -std=gnu++11 -lcurl -lcurlpp cry.cpp And when the output when verbose is set to true is: * Trying 205.193.226.160... * TCP_NODELAY set * Connected to www150.statcan.gc.ca (205.193.226.160) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/cert.pem CApath: none * SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384 * ALPN, server did not agree to a protocol * Server certificate: * subject: C=CA; ST=Ontario; L=Ottawa; jurisdictionCountryName=CA; O=Statistics Canada; businessCategory=Government Entity; serialNumber=1970-01-01; CN=www150.statcan.gc.ca * start date: Oct 4 16:33:01 2019 GMT * expire date: Jan 3 17:02:58 2022 GMT * subjectAltName: host "www150.statcan.gc.ca" matched cert's "www150.statcan.gc.ca" * issuer: C=US; O=Entrust, Inc.; OU=See www.entrust.net/legal-terms; OU=(c) 2014 Entrust, Inc. - for authorized use only; CN=Entrust Certification Authority - L1M * SSL certificate verify ok. > POST /t1/wds/rest/getDataFromVectorsAndLatestNPeriods HTTP/1.1 Host: www150.statcan.gc.ca Accept: */* Content-Length: 161 Content-Type: multipart/form-data; boundary=------------------------8fe530d4d57d4b83 * We are completely uploaded and fine < HTTP/1.1 415 < Date: Sat, 06 Nov 2021 03:39:47 GMT < Content-Length: 0 < Connection: keep-alive < X-Content-Type-Options: nosniff < X-XSS-Protection: 1; mode=block < Content-Security-Policy: default-src 'self' 'unsafe-inline' *.statcan.gc.ca *.statcan.ca *.stc.ca *.demdex.net *.omtrdc.net *.everesttech.net blob:; style-src 'self' 'unsafe-inline' *.statcan.gc.ca *.statcan.ca https://fonts.googleapis.com blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' *.statcan.gc.ca *.statcan.ca *.googletagmanager.com *.adobedtm.com *.jsdelivr.net *.mathjax.org cdnjs.cloudflare.com blob:; connect-src 'self' *.statcan.gc.ca *.statcan.ca *.stc.ca *.demdex.net *.omtrdc.net https://api.mapbox.com/ https://events.mapbox.com/; img-src 'self' *.statcan.gc.ca *.statcan.ca *.stc.ca *.demdex.net *.omtrdc.net *.everesttech.net *.jsdelivr.net data: blob:; font-src 'self' *.statcan.gc.ca *.statcan.ca https://fonts.gstatic.com; worker-src 'self' 'unsafe-inline' 'unsafe-eval' *.statcan.gc.ca *.statcan.ca blob:; frame-src 'self' 'unsafe-inline' *.statcan.gc.ca *.statcan.ca *.stc.ca https://dv-vd.shinyapps.io *.demdex.net blob:; < Strict-Transport-Security: max-age=31536000; includeSubDomains < Strict-Transport-Security: max-age=31536000 < * Connection #0 to host www150.statcan.gc.ca left intact * Closing connection 0 What is happening and how can I get it to do what I actually want?
I haven't used libcurlpp, but for libcurl a natural way of making a POST request is through the CURLOPT_POST and CURLOPT_POST_FIELDS options, see for example How to use libcurl for HTTP post?. This leas to this simple main: int main() { curlpp::Cleanup cleanup; curlpp::Easy request; request.setOpt(curlpp::options::Url(std::string("https://www150.statcan.gc.ca/t1/wds/rest/getDataFromVectorsAndLatestNPeriods"))); // request.setOpt(curlpp::options::Verbose(true)); std::list<std::string> header = { "Content-Type: application/json", "accept: application/json" }; request.setOpt(new curlpp::options::HttpHeader(header)); std::string query = "[{\"vectorId\":54325508, \"latestN\":1}]"; request.setOpt(new curlpp::options::PostFields(query)); request.setOpt(new curlpp::options::WriteStream(&std::cout)); request.perform(); } The part setting the HTTP header can actually be skipped for the server you connect with. The solution is in complete agreement with example 12 from curlpp documentation, https://github.com/jpbarrette/curlpp/blob/master/examples/example12.cpp .
69,861,537
69,861,936
Catching an exception type with constructor from not-const reference in C++
Consider a struct A with copy-constructor deleted but having instead the constructor from not-const reference. Can one throw an object of A and then catch it by value as in the example program: struct A { A() {} A(A&) {} A(const A&) = delete; }; int main() { try { throw A{}; } catch( A ) { } } Both GCC and Clang allow such usage. Although MSVC prints an error: C2316: 'A': cannot be caught as the destructor and/or copy constructor are inaccessible or deleted Demo: https://gcc.godbolt.org/z/P4c6Ea9fz Indeed A(const A&) is deleted but A(A&) is accessible here. Is it a wrong diagnostics from MSVC?
This is an MSVC bug: exception objects are never cv-qualified, and handler variables are initialized from an lvalue that refers to them. (The standard doesn’t actually say what the type of that lvalue is, but there’s no reason it should be const-qualified.)
69,861,548
69,861,567
How does nodejs understand/read c++ code?
I clearly understand Javascript only. I am curious about how Node.js understand C++ code as they are completely different things. How do they communicate with each other?
Using language bindings. The JS interpreter is able to import and call into exported linker symbols from a library, and with language bindings you can provide these, e.g by writing some functionality in C++.
69,861,573
69,869,264
Is there a way to select a single column in a matrix within armadillo?
Is there a way to select all the elements within a column in a matrix in C++ armadillo library? For example, in MATLAB, I can use : to refer to all the elements within a column of the matrix: A = ones(5,5); A(:,1) = A(:,1) * 5; Here, I have choose to multiply by 5 all elements within column 1. A = 5 1 1 1 1 5 1 1 1 1 5 1 1 1 1 5 1 1 1 1 5 1 1 1 1 I have searched the documentation of armadillo but I didn't find what I need. Can I do that with armadillo?
To multiply the fist column of matrix A by 5, use A.col(0) *= 5. The documentation has a syntax conversion table between Armadillo and Matlab. The documentation also describes the many forms of submatrices.
69,861,666
69,861,697
How to overload + operator that can work on objects of class largeIntegers that can store a number upto 100 digits in an array?
I'm learning Data Structures from a book named "Data Structures using C++" by D.S. Malik. I am currently solving the below written programming exercise: In C++, the largest int value is 2147483647. So an integer larger than this cannot be stored and processed as an integer. Similarly, if the sum or product of two positive integers is greater than 2147483647, the result will be incorrect. One way to store and manipulate large integers is to store each individual digit of the number in an array. Design the class largeIntegers so that an object of this class can store an integer up to 100 digits long. Overload the operators + and – to add and subtract, respectively, the values of two objects of this class. (In the Programming Exercises in Chapter 3, we will overload the multiplication operator.) Overload the assignment operator to copy the value of a large integer into another large integer. Overload the stream extraction and insertion operators for easy input and output. Your program must contain appropriate constructors to initialize objects of the class largeIntegers. (Hint: Read numbers as strings and store the digits of the number in the reverse order. Add instance variables to store the number of digits and the sign of the number.) And below is my code for the above: #include <bits/stdc++.h> using namespace std; class largeIntegers { private: /* data */ int num[100] = {0}; int digits; bool isPositive; public: friend istream &operator>>(istream &, largeIntegers &); largeIntegers &operator+(largeIntegers &); void getLargeInteger(void); void setLargeInteger(string); void print(void); largeIntegers(); largeIntegers(string); }; int main() { largeIntegers num1; cin >> num1; largeIntegers num2; num2 = num1; cin >> num1; largeIntegers num3; num3 = num1 + num2; num3.print(); return 0; } largeIntegers &largeIntegers::operator+(largeIntegers &integer) { largeIntegers temp; int remainder = 0; int digi = max(digits, integer.digits); temp.digits = digi; for (int i = 0; i < digi; i++) { temp.num[i] = (remainder + num[i] + integer.num[i]) % 10; remainder = (remainder + num[i] + integer.num[i]) / 10; } if (remainder) { temp.num[digi] = remainder; temp.digits++; } return temp; } largeIntegers::largeIntegers(string n) { setLargeInteger(n); } largeIntegers::largeIntegers() { isPositive = true; digits = 0; } void largeIntegers::setLargeInteger(string n) { int start = 0; if (n[0] == '-') { isPositive = false; start = 1; } digits = 0; for (int i = n.length() - 1; i >= start; i--) { num[digits] = int(n[i]) - int('0'); digits++; } } void largeIntegers::getLargeInteger(void) { cout << "Enter a large integer:\n"; string n; cin >> n; setLargeInteger(n); } istream &operator>>(istream &isObject, largeIntegers &largeInt) { string num; isObject >> num; largeInt.setLargeInteger(num); return isObject; } void largeIntegers::print(void) { if (!isPositive) cout << "-"; for (int i = digits - 1; i >= 0; i--) { cout << num[i]; } cout << endl; } But my code is not working for the addition operation. It is giving Segmentation fault (core dumped) error. Can someone explain what's the problem and how to fix it?
The problem is that your overloaded operator+ was returning a reference to a local variable. To solve this, you can instead use the following version of operator+: //return by value largeIntegers operator+(const largeIntegers &lhs, const largeIntegers &integer) { largeIntegers temp; int remainder = 0; int digi = max(lhs.digits, integer.digits); temp.digits = digi; for (int i = 0; i < digi; i++) { temp.num[i] = (remainder + lhs.num[i] + integer.num[i]) % 10; remainder = (remainder + lhs.num[i] + integer.num[i]) / 10; } if (remainder) { temp.num[digi] = remainder; temp.digits++; } return temp; } For the above to work make operator+ a friend by adding a friend declaration as follows inside the class: friend largeIntegers operator+(const largeIntegers &lhs, const largeIntegers &rhs); The complete working program that uses the above shown modification can be seen here and is given below: #include <bits/stdc++.h> using namespace std; class largeIntegers { private: /* data */ int num[100] = {0}; int digits; bool isPositive; public: friend istream &operator>>(istream &, largeIntegers &); //i have added this friend declaration friend largeIntegers operator+(const largeIntegers &lhs, const largeIntegers &rhs); void getLargeInteger(void); void setLargeInteger(string); void print(void); largeIntegers(); largeIntegers(string); }; int main() { largeIntegers num1; cin >> num1; largeIntegers num2; num2 = num1; cin >> num1; largeIntegers num3; num3 = num1 + num2; num3.print(); return 0; } //i have modified the operator+ as shown below largeIntegers operator+(const largeIntegers &lhs, const largeIntegers &integer) { largeIntegers temp; int remainder = 0; int digi = max(lhs.digits, integer.digits); temp.digits = digi; for (int i = 0; i < digi; i++) { temp.num[i] = (remainder + lhs.num[i] + integer.num[i]) % 10; remainder = (remainder + lhs.num[i] + integer.num[i]) / 10; } if (remainder) { temp.num[digi] = remainder; temp.digits++; } return temp; } largeIntegers::largeIntegers(string n) { setLargeInteger(n); } largeIntegers::largeIntegers() { isPositive = true; digits = 0; } void largeIntegers::setLargeInteger(string n) { int start = 0; if (n[0] == '-') { isPositive = false; start = 1; } digits = 0; for (int i = n.length() - 1; i >= start; i--) { num[digits] = int(n[i]) - int('0'); digits++; } } void largeIntegers::getLargeInteger(void) { cout << "Enter a large integer:\n"; string n; cin >> n; setLargeInteger(n); } istream &operator>>(istream &isObject, largeIntegers &largeInt) { string num; isObject >> num; largeInt.setLargeInteger(num); return isObject; } void largeIntegers::print(void) { if (!isPositive) cout << "-"; for (int i = digits - 1; i >= 0; i--) { cout << num[i]; } cout << endl; } See the comments in the above code to check the modifications i made
69,861,671
69,861,819
Why does my code not work if I switch the position of commented line on top of the function? It's a memoization recall statement
I'm trying to memoize this unique paths grid problem. Until now, I always put the memoized return statement on top of the function. But here, it's not working. I don't understand why. Do those positions matter sometimes? Can you please explain the reason? I have just started dynamic programming. int grid(long long i, long long j, long long m, long long n, vector<vector<long long>> &memo) { if (memo[i][j] != -1) return memo[i][j]; // but not working here, WHY?? if (i == m - 1 && j == n - 1) return 1; if (i >= m || j >= n) return 0; // if (memo[i][j] != -1) return memo[i][j]; // works here memo[i][j] = grid(i + 1, j, m, n, memo) + grid(i, j + 1, m, n, memo); return memo[i][j]; }
int grid(long long i, long long j, long long m, long long n, vector<vector<long long>> &memo) { // delete the first statement if (i == m - 1 && j == n - 1) return 1; if (i >= m || j >= n) return 0; if (memo[i][j] != -1) return memo[i][j]; memo[i][j] = grid(i + 1, j, m, n, memo) + grid(i, j + 1, m, n, memo); return memo[i][j]; } In here, you check that if (i >= m || j >= n) first, to prevent out-of-bounds error, before you try to access memo[i][j]; But: int grid(long long i, long long j, long long m, long long n, vector<vector<long long>> &memo) { if (memo[i][j] != -1) return memo[i][j]; if (i == m - 1 && j == n - 1) return 1; if (i >= m || j >= n) return 0; // delete the second statement memo[i][j] = grid(i + 1, j, m, n, memo) + grid(i, j + 1, m, n, memo); return memo[i][j]; } In here, you try to access memo[i][j]; first, before you check if (i >= m || j >= n) return 0;, so an out-of-bounds error could happen here, and you get undefined behaviour.
69,861,865
69,861,919
Seeking helps in explanation of syntax for var[x[n]]
How does the below syntax work? class Solution { public: int lengthOfLongestSubstring(string s) { const int n = s.length(); int ans = 0; // Set a variable as the answer; for(int i = 0; i < n; ++i) { vector <int> seen(128); int j = i; while(j < n && !seen[s[j]]) <---- Here seen[s[j++]] = 1; <---- Here ans = max(ans, j - i); <---- Here } return ans; } }; What does the syntax !seen[s[j]] mean? And the same for seen[s[j++]]=1. Also, why can i be subtracted by j?
Case 1 s[j] The above means the element at index j of the string named s. Case 2 seen[s[j]] The above means the element at index s[j] of variable named seen. Case 3 seen[s[j++]] = 1; For the above you have to know about the post-increment operator. So let’s say we have: int var = 0; std::cout << var++ <<std::end; // This will print 0 The ++ in var++ means we are incrementing the value of var by 1, so that it now becomes 1, but var++ returns the old value of the variable var which is why we get 0 as the output. Now let’s come back to: seen[s[j++]]=1; The above means the element at index s[j++] of the variable named seen. But note j++ will do two things: First it will increment j by 1 and second it will return the old value of j. So s[j++] essentially means the element at index j of the string named s meanwhile the value of j is also incremented by 1. Thus as a whole, you're assigning a value of 1 to the element at index s[j] of the variable named seen meanwhile also increment the value of j by one. Why can i be subtracted by j? This is because the value of j is incremented by 1 inside the while loop.
69,861,914
69,862,042
Derived classes' attributes are empty
I am new to C++ and I am currently playing with inheritance. I am creating a base Polygon class that is inherited by Rectangle and Triangle classes respectively. From there I want to print out the area as defined in calcArea. However, the output of my derived class instances seem to be null. From what I understand the Polygon:(name, width, height) can help to initialize variables that already exist in the base class. Thanks for all the help! Here's my code: #include <iostream> #include <string> using namespace std; enum Polytype {POLY_PLAIN, POLY_RECT, POLY_TRIANG}; class Polygon { public: Polygon(string name, double width, double height){ _name = name; _width = width; _height = height; _polytype = POLY_PLAIN; } virtual ~Polygon() { cout << "Destroying polygon" << endl; } virtual Polytype getPolytype(){ return _polytype; } virtual void setPolytype(Polytype polytype){ _polytype = polytype; } virtual string getName(){ return _name; } virtual double calcArea(){ return _width * _height; } private: string _name; double _width; double _height; Polytype _polytype; }; class Rectangle: public Polygon { public: Rectangle(string name, double width, double height) : Polygon(name, width, height){ _polytype = POLY_RECT; }; ~Rectangle() { cout << "Destroying rectangle" << endl; } Polytype getPolytype(){ return _polytype; } void setPolytype(Polytype polytype){ _polytype = polytype; } double calcArea(){ return _width * _height; } string getName(){ return _name; } private: string _name; double _width; double _height; Polytype _polytype = POLY_RECT; }; class Triangle: public Polygon { public: Triangle(string name, double width, double height) : Polygon(name, width, height){ _polytype = POLY_TRIANG; }; ~Triangle() { cout << "Destroying triangle" << endl; } Polytype getPolytype(){ return _polytype; } void setPolytype(Polytype polytype){ _polytype = polytype; } string getName(){ return _name; } double calcArea(){ return 0.5 * _width * _height; } private: string _name; double _width; double _height; Polytype _polytype; }; int main(){ //Initialize rectangle and triangle and store them onto the stack Rectangle rect("RectA", 10.0, 20.0); Triangle triang("TriangB", 10.0, 20.0); cout << "Name is " << rect.getName() << endl; cout << "Name is "<< triang.getName() << endl; string rectArea = to_string(rect.calcArea()); string triangArea = to_string(triang.calcArea()); cout << "RectA's area is " << rectArea << endl; cout << "TriangB's area is " << triangArea << endl; return 0; } And here's my output: Name is Name is RectA's area is 0.000000 TriangB's area is 0.000000 Destroying triangle Destroying polygon Destroying rectangle Destroying polygon
The main problem is that you have variables in the sub classes shadowing the names in the base class - so you assign values to the variables in the base class, but you later print the values of the default initialized variables in the sub classes. You actually mostly need to remove code. I would rethink the name of the base class though. Polygon is not a good name for a class with only width and height. I'll leave that up to you. I've replaced all endl with \n. They do the same thing, but endl flushes the output, which is usually not needed - but it is usually also expensive. Example: #include <iostream> #include <string> enum Polytype { POLY_PLAIN, POLY_RECT, POLY_TRIANG }; class Polygon { public: Polygon(std::string name, double width, double height) : Polygon(name, width, height, POLY_PLAIN) {} virtual ~Polygon() { std::cout << "Destroying polygon\n"; } // make member functions that does not change the object `const`: virtual Polytype getPolytype() const { return _polytype; } virtual void setPolytype(Polytype polytype) { _polytype = polytype; } virtual const std::string& getName() const { return _name; } // in your case, the implementation could actually be in the base class - but // I've made it into a pure virtual here. virtual double calcArea() const = 0; // no instances can be made of Polygon protected: // only derived classes can access this constructor: Polygon(std::string name, double width, double height, Polytype ptype) : _name(name), _width(width), _height(height), _polytype(ptype) {} std::string _name; double _width; double _height; Polytype _polytype; }; class Rectangle : public Polygon { public: Rectangle(std::string name, double width, double height) //use the protected base class ctor: : Polygon(name, width, height, POLY_RECT) {}; ~Rectangle() { std::cout << "Destroying rectangle\n"; } // the only implementation needed in this sub class: double calcArea() const override { return _width * _height; } }; class Triangle : public Polygon { public: Triangle(std::string name, double width, double height) : Polygon(name, width, height, POLY_TRIANG) {}; ~Triangle() { std::cout << "Destroying triangle\n"; } // the only implementation needed in this sub class: double calcArea() const override { return 0.5 * _width * _height; } }; int main() { // Initialize rectangle and triangle and store them onto the stack Rectangle rect("RectA", 10.0, 20.0); Triangle triang("TriangB", 10.0, 20.0); std::cout << "Name is " << rect.getName() << '\n'; std::cout << "Name is " << triang.getName() << '\n'; std::cout << "RectA's area is " << rect.calcArea() << '\n'; std::cout << "TriangB's area is " << triang.calcArea() << '\n'; }
69,862,537
69,862,543
Why using if in this way is preventing it from running
so here the if inside the loop is it possible to write the if statement in an optimized way or should I just split the two conditions? #include <iostream> using namespace std; int main() { int grade, counter = 1, total = 0, average; while (counter <= 10) { cout << "Enter grade /100: "; cin >> grade; if (grade < 0 && grade > 100) //HERE PLEASE { cout << "invalid grade value." << endl; cout << "Reenter grade value */100*: "; cin >> grade; } total = total + grade; counter++; } average = total / 10; cout << "\nThe class average is: " << average << endl; return 0; }
if (grade < 0 && grade > 100) There is no number that is lower than 1 and bigger than 100, so that conditions will return false every time. If you want lower than 1 or bigger than 100, try: if (grade < 0 || grade > 100) Overall, your code should be: #include <iostream> // using namespace std; is bad practice, so don't use it int main() { int grade = 0, counter = 1, total = 0, average = 0; while (counter <= 10) { std::cout << "Enter grade /100: "; std::cin >> grade; if (grade < 0 || grade > 100) { // use newline character instead of std::endl std::cout << "invalid grade value." << '\n'; std::cout << "Reenter grade value */100*: "; std::cin >> grade; } // a = a + b is equal to a += b total += grade; ++counter; } average = total / 10; std::cout << "\nThe class average is: " << average << '\n'; return 0; }
69,862,779
69,862,809
where is the const-ness in this lambda capture argument introduced?
This code compiles correctly. #include <asio.hpp> #include <memory> #include <iostream> struct Message { int msg; }; // never mind global variables, just for the sake of making this a minimal example extern asio::ip::tcp::socket mysocket; void handler(std::shared_ptr<Message> pmsg, asio::error_code error, size_t nbytes); void readMessage() { std::shared_ptr<Message> pmsg{ new Message }; asio::async_read(mysocket, asio::buffer(&pmsg->msg, sizeof(int)), [pmsg](auto err, auto nbytes) { handler(pmsg, err, nbytes); }); } However, when I add a reference to the first argument of the handler function void handler(std::shared_ptr<Message>& pmsg, asio::error_code error, size_t nbytes); the code no longer compiles, complaining that I am trying to convert pmsg from a const std::shared_ptr<Message>& to a std::shared_ptr<Message>&. To get it to work again, I have to introduce a const_cast<std::shared_ptr<Message>&> in the call to the handler. Where is the const-ness introduced? Thanks
psmg is captured by value, so it is read only inside closure. If you need it to be modifiable (because that is required by handler) you have to add mutable to the lambda: [pmsg](auto err, auto nbytes) mutable { handler(pmsg, err, nbytes); }); Live demo based on BoostAsio When pmsg is capture by value, the compiler is allowed to make one implicit conversion, so from pmsg is created temporary shared_ptr instance and passed to handler, but temporary object cannot be bound to Lvalue reference (it could be work with const lvalue ref).
69,863,023
69,863,074
How to put numbers from txt file into vector in c++
I must say I'm completely new to C++. I got the following problem. I've got a text file which only has one 8 digits number Text-File: "01485052" I want to read the file and put all numbers into a vector, e.g. Vector v = ( 0, 1, 4, 8, 5, 0, 5, 2 ). Then write it into another text file. How do I implement it the best way? That's what I made possible so far: #include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> using namespace std; int main() { char matrikelnummer[100]; cout << "Enter file name: "; cin >> matrikelnummer; // Declare input file stream variable ifstream inputFile(matrikelnummer); string numbers; //Check if exists and then open the file if (inputFile.good()) { // while (getline(inputFile, numbers)) { cout << numbers; } // Close the file inputFile.close(); } else // In case TXT file does not exist { cout << "Error! This file does not exist."; exit(0); return 0; } // Writing solutions into TXT file called Matrikelnummer_solution.txt ofstream myFile; myFile.open("Matrikelnummer_solution.txt"); myFile << "Matrikelnummer: " << numbers << '\n'; myFile.close(); return 0; }
You can use the following program for writing the number into another file and also into a vector: #include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> using namespace std; int main() { ifstream inputFile("input.txt"); std::string numberString; int individualNumber; std::vector<int> vec; if(inputFile) { std::ofstream outputFile("outputFile.txt"); while(std::getline(inputFile, numberString,'\n'))//go line by line { for(int i = 0; i < numberString.size(); ++i)//go character by character { individualNumber = numberString.at(i) - '0'; outputFile << individualNumber;//write individualNumber into the output file vec.push_back(individualNumber);//add individualNumber into the vector } } outputFile.close(); } else { std::cout<<"input file cannot be openede"<<std::endl; } inputFile.close(); //print out the vector for(int elem: vec) { std::cout<<elem<<std::endl; } return 0; } The output of the above program can be seen here.
69,863,051
69,863,357
what's wrong with my code? ( C++ if else with datastructures )
I was working on data structures with C++. Everything looks OK. This is a simple C++ file read. I think this code's output should be: 1 K 3 4 5 But I'm seeing: 1 2 3 4 5 How can I take data[4] in if? This is file.txt A(1#Jordan) A(2#Kyrie) A(3#Lebron) A(4#Harden) A(5#Doncic) This is my code #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ fstream file; file.open("file.txt", ios::in); if(file.is_open()){ while(!file.eof()) { char data[20]; file >> data; if(2 == data[2]) cout << data[4]<< endl; //** else cout << data[2] << endl; } } file.close(); return 0; }
there is a small error in how you compare a char to an int; the correct comparison is using '2': #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ fstream file; file.open("file.txt", ios::in); if(file.is_open()){ while(!file.eof()) { char data[20]; file >> data; if('2' == data[2]) cout << data[4]<< endl; //** else cout << data[2] << endl; } } file.close(); return 0; }
69,863,335
69,863,507
Reading a file in c++ and comparing between lines
Assuming a file.txt contains random files names as follows: a.cpp b.txt c.java d.cpp ... The idea is I want to sperate the file extension from the the file name as substring, and then compare between extensions to look for duplicates. Here is my code: #include<iostream> #include<fstream> #include<string> using namespace std; int main() { ifstream infile; infile.open("file.txt"); string str,sub; int count,pos=0; while(infile>>str) { pos=str.find("."); sub=str.substr(pos+1); if(sub==?) // I stopped here count++; } cout<<count; return 0; } I'm new to C++ so I don't know which function to use to jump to the next line, I searched a lot to figure it out, but nothing.
You can use the following program to print the count corresponding to each extension in the input file. The program uses std::map to keep track of the count. #include <iostream> #include <map> #include <fstream> int main() { std::ifstream inputFile("input.txt"); std::map<std::string, int> countExtOccurence; //this will count how many time each extension occurred std::string name, extension; if(inputFile) { while(std::getline(inputFile, name, '.')) //this will read upto a . occurrs { std::getline(inputFile, extension, '\n'); { countExtOccurence[extension]++; //increase the count corresponding to a given extension } } } else { std::cout<<"input file cannot be opened"<<std::endl; } inputFile.close(); //lets print out how many times each extensino occurred in the file for(const std::pair<std::string, int> &pairElem: countExtOccurence) { std::cout<<pairElem.first<<" occurred: "<<pairElem.second<<" time"<<std::endl; } return 0; } The output of the above program can be seen here.
69,863,494
69,863,689
How to return an pointer to an item in the linear list
i have funcion that search a key in the linear list, but i have error when i want return pointer on an element. struct Item { datatype key; Item* next; Item* prev; }; int List::search(int x) { Item* temp = head; if (head == NULL) { cout << "Empty List" << endl; } while (temp != NULL) { if (temp->key == x) { break; } else { temp = temp->next; } } return *temp;\\here i have a error }
How to return an pointer to an item in the linear list It is evident that for starters you need to change the return type of the function from int to Item *. Item * List::search( int x ); And within function you need to return indeed a pointer instead of the pointed item. The function should not output any message. It is the user of the function that will decide to output any message or not dependent on whether a null pointer is returned or not. The function should be overloaded for constant and non-constant list. Here is shown how it can be defined Item * List::search( int x ) { Item *target = head; while ( target != nullptr && target->key != x ) { target = target->next; } return target; } and const Item * List::search( int x ) const { const Item *target = head; while ( target != nullptr && target->key != x ) { target = target->next; } return target; }
69,863,533
69,896,899
How to resize TextureArray in directx 11
I'm using a Texture2DArray to store the shadow maps of my directional lights. When a new directional light is added I want to resize the texture array to be able to hold the new shadow map. How can I achieve this? I need this, because it's very convenient to pass texture array to my shader and just index the correct texture based on the light index. One possibility I see is to instead keep multiple Texture2Ds, create a Texture2DArray before rendering with the required shader and copy to the corresponding subresource. This does not sound very convenient and efficient to me, though.
Recreating resource every frame is certainly wasteful, so creating a texture array and copy is definitely not very efficient. If your light count doesn't really change on a per scene basis, you can still totally create a new resource at the beginning of the scene (during load). In case you want it fully dynamic, you will indeed have to pick a maximum number of light, in case you go over that number you can either decide to create a new resource, or issue an error stating that you are over the maximum allowed. Also if you don't want to over commit memory (if you create a an array with 128 slices for example, but use only 5 lights you waste tons of vram), you can consider using Tiled Resources. The idea is that you create a large resource up front, but with no memory assigned to it. On top of it you create a buffer with the Tile pool flag (note that in this case you are allowed to set a zero size, and size is always a multiple of 65536). When you need to increase size, you can use ResizeTilePool on your buffer. To assign blocks of memory from your tile pool to your texture, you use UpdateTileMappings As a side note since you actually can use those tile memory on several resources at once you also might need to issue TiledResourceBarrier on your context (this is normally only needed if your tiles are used by several resources at once). I used that technique for many use cases in my renderer, and had some very good memory usage improvements.
69,863,585
69,863,753
Printing the values from vector
I know the reason why this is happening but don't know how to solve this as I am new to STL. I am taking the inputs from the user and representing the weighted graph using vectors. I declared a vector pair<int,int> to store the value of the edge and the weight. #include<iostream> #include<vector> using namespace std; int main() { int n,m,c; cout<<"Enter n,m : "<<endl; cin>>n>>m; vector<pair<int,int>> adj[n+1]; cout<<"If un-directed input 1 else input 0: "<<endl; cin>>c; cout<<"Enter the values of u,v and the waight : "<<endl; for(int i=0;i<m;i++) { int u,v,w; cin>>u>>v>>w; adj[u].push_back({v,w}); if(c==1) adj[v].push_back({u,w}); } for(int i=0;i<=n;i++) { for(int j:adj[i]) { cout<<i<<"->" << j <<endl; } cout<<endl; } cout<<"Inserted Successfully"; return 0; } But when i am printing the values i am not able to compile the program. It is due to this for loop. for(int j:adj[i]) { cout<<i<<"->" << j <<endl; } As the value in adj[i] is a pair of edge and weight thus ,the for_each loop is unable to convert the pair value to a single int value. This might be the reason but i am unable to solve this as i am new to the STL. Please Help.
j is a pair of int in order to access the first/second int you have to use j.first/ j.second for(pair<int,int> j:adj[i]) { cout<<i<<"->" << j.second <<endl; }
69,863,605
69,864,339
C++ different using declarations for different concepts
Let's say, I have my List<T> class. I have a lot of functions where I have to pass a single object of my T type. For instance void add(const T& item) { ... } and it makes sense if T is some class or a struct. However, if T is a byte or integer, it's pointless or even wrong to pas it via reference, since memory pointer costs 8 bytes (4 on 32 bit system), i.e. I pass 1 byte size data type via 8 byte size pointer. And so I decided to define argument data type using using directive. Kind of: using argType = const T&; requires sizeof(T) > 8 using argType = T; requires sizeof(T) <= 8 But, obviously, this code doesn't work. Can you, please, propose me other solutions for that?
It sounds like what you need is conditional_t: #include <type_traits> template<class T> class List { using argType = std::conditional_t<(sizeof(T) > 8), const T&, T>; void add(argType item) { } };
69,863,700
69,863,872
Vector of vectors memory layout
A std::vector<T> has the property of storing its elements continuously in memory. But what about a std::vector<std::vector<T>>? The elements within an individual std::vector<T> are continuous, but are the vectors themselves continuous in memory (that is, the whole data kept in the outer vector would be one memory block)? Would not this imply, that if I resize one of the inner vectors I would have to copy (or move) many objects to preserve continuity? And what about a std::array<std::array<T,N>,N>? Here I would assume memory continuity just as for T[N][N]
A std::vector<T> internally stores a pointer to dynamically allocated memory. So while the elements of a single std::vector<T> will be continuous in memory there is no relationship to any pointers that those elements store themselves. Therefore a std::vector<std::vector<T>> will not have the elements of the "inner vectors" stored continuously in relation to each other. It would also be impossible for a resize of one of those "inner vectors" to affect the others, since at the point where the resize happens there is no information about any relationship to other std::vector<T> objects. On the other hand a std::array is a (thin) wrapper around a C-style array and uses neither dynamic allocation nor is resizable, so a std::array<std::array<T,N>,N> will have the same memory layout as a T[N][N] array.
69,863,903
69,864,190
How to fix Debug Error from Microsoft Visual C++ Runtime library when dealing with threads?
I'm writing a program that will detect a key press and do something (in this case, show a message box). It all works fine, except when I try to exit the program, it shows a popup like this error window: Now, this window doesn't mess up anything in my program, so I could leave it there, but it is annoying. Here's a Minimal Reproducible Sample, I'm just beginning to code in Win32 so please don't criticize my inefficent code. #include <Windows.h> #include <thread> #include <chrono> #define HFFFA 1001 #define MAINWINDOWSTYLE WS_OVERLAPPED| WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX std::chrono::milliseconds THREAD_WAIT(50); LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { switch (msg) { case WM_COMMAND: { switch (wp) { case HFFFA: { MessageBox(hwnd, L"Sucess", L"Success", MB_OK); break; } break; } break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW)); EndPaint(hwnd, &ps); break; } case WM_DESTROY: { PostQuitMessage(0); break; } break; } return DefWindowProc(hwnd, msg, wp, lp); } void GetKeyPress(HWND hwnd) { int keypressed = -1; while (TRUE) { if (GetAsyncKeyState(VK_F6)) { SendMessage(hwnd, WM_COMMAND, (WPARAM)HFFFA, TRUE); } std::this_thread::sleep_for(THREAD_WAIT); } } int WINAPI wWinMain(HINSTANCE hinst, HINSTANCE hiprevinst, PWSTR nCmdLine, int ncmdshow) { const wchar_t CLASS_NAME[] = L"Axom"; WNDCLASS wc = { }; wc.lpfnWndProc = WndProc; wc.hInstance = hinst; wc.lpszClassName = CLASS_NAME; wc.hCursor = LoadCursor(NULL, IDC_ARROW); RegisterClass(&wc); HWND hwnd = CreateWindowEx(0, CLASS_NAME, L"Axom", MAINWINDOWSTYLE, CW_USEDEFAULT, CW_USEDEFAULT, 592, 600, NULL, NULL, hinst, NULL); ShowWindow(hwnd, ncmdshow); std::thread td(GetKeyPress, hwnd); MSG msg; while (GetMessage(&msg, NULL, NULL, NULL)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }
When the events loop ends, all of wWinMain's local variables are destroyed. One of them is td as your thread. When std::thread is destroyed while it is in joinable state, std::terminate() is called: std::terminate is called by the C++ runtime when the program cannot continue for any of the following reasons: a joinable std::thread is destroyed or assigned to The default std::terminate() behaviour is to invoke the std::abort() function. The default std::terminate_handler calls std::abort. You have to call detach() or join() on the td thread before it is destroyed. If you join the thread, you have to add some mechanism (for example, via a global flag variable) to inform the GetKeyPress thread function when to leave. std::atomic_bool stopFlag; // global variable void GetKeyPress(HWND hwnd) { int keypressed = -1; while (!stopFlag) { if (GetAsyncKeyState(VK_F6)) SendMessage(hwnd, WM_COMMAND, (WPARAM)HFFFA, TRUE); std::this_thread::sleep_for(THREAD_WAIT); } } std::thread td(GetKeyPress, hwnd); MSG msg; while (GetMessage(&msg, NULL, NULL, NULL)) { TranslateMessage(&msg); DispatchMessage(&msg); } stopFlag = true; td.join();
69,864,187
69,865,621
C++ choose method based argument's dynamic type
Question Imagine I have some simulator library, that takes from me some objects (aka event handlers) and generates events for these objects by calling their handle_event(Event) method. The library provides me with the following classes: class Event {}; // Base class for all events // All event classes are derived from `Event` class SomeParticularEvent : public Event {}; // Some event class class AnotherParticularEvent : public Event {}; // Some event class // Object aka event handler. I should inherit this class and then give objects to the simulator class AbstractEventHandler { public: virtual void handle_event(Event) = 0; }; I want to implement an object that handles different events differently. The first code I came up with is the following: #include <iostream> class MyObject : public AbstractEventHandler { public: void actual_handle_event(SomeParticularEvent) { std::cout << "`SomeParticularEvent` occurred\n"; } void actual_handle_event(AnotherParticularEvent) { std::cout << "`AnotherParticularEvent` occurred\n"; } void actual_handle_event(Event e) { std::cerr << "Unknown event type occurred\n"; } virtual void handle_event(Event e) override { actual_handle_event(e); } }; Сontrary to my expectations, MyObject::handle_event(Event) will always call MyObject::actual_handle_event(Event) regardless of the dynamic type of e. My question is: What is the correct way to implement MyObject (preferrably, making it possible to easily add new event type)? All the code together #include <iostream> class Event {}; // Base class for all events // All event classes are derived from `Event` class SomeParticularEvent : public Event {}; // Some event class class AnotherParticularEvent : public Event {}; // Some event class class AbstractEventHandler { public: virtual void handle_event(Event) = 0; }; class MyObject : public AbstractEventHandler { public: void actual_handle_event(SomeParticularEvent) { std::cout << "`SomeParticularEvent` occurred\n"; } void actual_handle_event(AnotherParticularEvent) { std::cout << "`AnotherParticularEvent` occurred\n"; } void actual_handle_event(Event e) { std::cerr << "Unknown event type occurred\n"; } virtual void handle_event(Event e) override { actual_handle_event(e); } }; int main() { MyObject o{}; o.handle_event(SomeParticularEvent{}); // Prints "Unknown event type occurred" } Additional question Is it also possible to create a class derived from MyObject and implement additional event handlers (not override old ones, but add support for new events) without rewriting the handle_event method in the derived class?
Based on the requirements in the question and things discussed in the comments to @ypnos answer, I believe that you want or need to implement the visitor pattern here. One possible implementation would look like this (based on the Wikipedia article about Visitor Pattern: https://en.wikipedia.org/wiki/Visitor_pattern#C++_example) #include <iostream> // Forward declare all Event classes class Event; class SomeParticularEvent; class AnotherParticularEvent; class AbstractEventHandler { public: virtual void handle_event(const Event&) = 0; virtual void handle_event(const SomeParticularEvent&) = 0; virtual void handle_event(const AnotherParticularEvent&) = 0; }; class Event { public: // virtual function for accepting the "visitor" virtual void accept(AbstractEventHandler& handler) { handler.handle_event(*this); } }; // Base class for all events // All event classes are derived from `Event` class SomeParticularEvent : public Event { public: // Needs to be overriden to call `handle_event` with the correct type void accept(AbstractEventHandler& handler) override { handler.handle_event(*this); } }; // Some event class class AnotherParticularEvent : public Event { public: void accept(AbstractEventHandler& handler) override { handler.handle_event(*this); } }; // Some event class class MyObject : public AbstractEventHandler { public: void handle_event(const SomeParticularEvent&) override { std::cout << "`SomeParticularEvent` occurred\n"; } void handle_event(const AnotherParticularEvent&) override { std::cout << "`AnotherParticularEvent` occurred\n"; } void handle_event(const Event& e) override { std::cerr << "Unknown event type occurred\n"; } }; int main() { MyObject o{}; SomeParticularEvent{}.accept(o); AnotherParticularEvent{}.accept(o); }
69,864,408
69,865,077
What datatype would is expected for the arrays in c++?
I've been trying to assign a datatype to the three-dimensional arrays, e.g., double, but keep getting the error error: request for member 'size' in 'msd_x', which is of non-class type 'const sample_type' {aka 'const long unsigned int'} -> size_t N = msd_x.size(); class mean_square_displacement { public: typedef boost::multi_array_types::size_type sample_type; //typedef fixed_vector<double, 3> result_type; typedef double result_type; result_type operator() (sample_type const& msd_x, sample_type const& msd_y, sample_type const& msd_z) const { size_t N = msd_x.size(); result_type msd = 0; for (unsigned int i = 0; i < N; ++i) { for (unsigned int j = 0; j < N; ++j) { auto dr = (msd_x[i+1][j] - msd_x[i][j]) + (msd_y[i+1][j+1] - msd_y[i][j+1]) + (msd_z[i+1][j+2] - msd_z[i][j+2]); } // accumulate squared displacements msd += dr * dr; } return msd / N; } } Along with that it throws one more error: error: invalid types 'const sample_type {aka const long unsigned int}[unsigned int]' for array subscript I guess the way code accessing the arrays is fine. But it still throws the error. The data code reads is of double datatype, shown in the code below: int main(int argc, char const* argv[]) { correlator::multi_tau_correlator<double> corr( // TODO replace sample type nsamples * sampling_interval / 30 trajectory length , sampling_interval // time resolution at lowest level , 10 ); // define time correlation functions auto msd = make_correlation(correlator::mean_square_displacement(), corr); corr.add_correlation(msd); // main loop for all coordinates for (size_t i = 1; i < nsamples; ++i) { auto position_array = first_rows[i]; // append data to the correlator, which possibly computes some time correlations corr.sample(position_array); } corr.finalise(); return 0; } Does anyone point out what is wrong with the datatypes?
I'm guessing here based on the many questions leading up to this. It is pretty obvious that you do not want sample type to be a scalar, but a 2-dimensional array. I will sketch a generic short-cut that would allow you to write mean_square_displacement::operator() to accept those, potentially even without knowing the concrete type(s) of the arguments. Caution However, I want to first caution that there is no way to know whether that will work with the multi_tau_correlator framework that you've never described. It seems like you are trying to apply the correlator in a parallel fashion. Firstly it's unknown whether the correlator framework allows you to do that (technically) and secondly it is likely not going to be fast, as this kind of parallelism is the realm of highly optimized libraries (that use actually vectorized operations like SIMD, AVX, OpenGL/Cuda). All I see here is a raw quadratic loop, which does not bode well for efficiency. The blind fix Since you don't want sample_type to be what you define it to be, simply define it as something else, preferrably, the thing you need it to be! typedef array_2d_t sample_type; There's a good chance that this is not what you actually are passing either (I suspect a sub_array view or (optionally strided) multi_array_view slice of a 3D multi array). But you can let the compiler figure it out based on the fact that you know you can index the arguments like this arg[int][int]: template <typename Sample> result_type operator()(Sample const& msd_x, Sample const& msd_y, Sample const& msd_z) const This lets the compiler deduce the concrete type, assuming all arguments have the same statical type. Otherwise, you can go even more open: template <typename Sx, typename Sy, typename Sz> result_type operator()(Sx const& msd_x, Sy const& msd_y, Sz const& msd_z) const More Caution I can see you're out of your depth. E.g. in your mean_square_displacement we see auto dr being used outside its scope. It will not compile. For the above I have GUESSED that you meant to place the accumulation into the inner loop. you're also explicitly addressing msd_x out of bounds (index N doesn't exist, since N == msd_x.size()). Likely msd_y/msd_z have the same extents, so they too have this issue, but even with +2 If course the naive fix to loop till N-2 risks UB again unless you make sure that N is never <2 Here's the minimum fixes that make this code look like it might technically work, though: struct mean_square_displacement { //typedef fixed_vector<double, 3> result_type; typedef double result_type; template <typename Sample> result_type operator()(Sample const& msd_x, Sample const& msd_y, Sample const& msd_z) const { size_t N = msd_x.size(); assert(N>=2); result_type msd = 0; for (unsigned int i = 0; i < N-1; ++i) { for (unsigned int j = 0; j < N-2; ++j) { auto dr = // (msd_x[i + 1][j + 0] - msd_x[i][j + 0]) + (msd_y[i + 1][j + 1] - msd_y[i][j + 1]) + (msd_z[i + 1][j + 2] - msd_z[i][j + 2]); // accumulate squared displacements msd += dr * dr; } } return msd / N; } };
69,864,471
69,888,932
SFML no sound playing with soundbuffers stored in ResourceHolder
i'm currently working on a small game with sfml. For resource loading and holding i'm using the ResourceHolder described in the SFML Game Development Book: SFML ResourceHolder Basically the resources are stored as unique_ptr in a map. Inside a SoundManager class i'm loading different sounds to this ResourceHolder. This SoundManager has a playSound function when i want to play a sound. void SoundManager::playSound(SoundType soundToPlay) { auto buffer = sounds.get(soundToPlay); auto sound = sf::Sound(buffer); sound.play(); } but i don't hear any sounds. Do i have to store different sound objects for every sound in a map? I also tried to use a sf::Sound object as a class member, but this also didn't worked. Using this ResourceHolder my textures are loaded correctly. Thank you for you help
I was able to fix this issue with some enter link description here in the sfml-dev forum.
69,864,580
69,864,963
Quick method for search a value in a (sorted) circular data structure
I'm looking for an algorithm similar to binary search but which works with data structures that are circular in nature, like a circular buffer for example. I'm working on a problem which is quite complicated, but I's able to strip it down, so it's easier to describe (and, I hope, easier to find a solution). Let's say we have got an array of numbers with both its ends connected and an view window which can move forward and backward and which can get a value from the array (it's something like a C++ iterators which can go forward and backward). One of the values in the array is zero, which is our "sweet point" we want to find. What we know about values in the array are: they are sorted, which means when we move our window forward, the numbers grow (and vice versa), they are not evenly spaced: if for example we read "16", it doesn't mean if we go 16 elements backward, we reach zero, at last but not least: there is a point in the array where, up to that point values are positive, but after that point they are "flipped over" and start at a negative value (it is something like if we were adding ones to an integer variable until the counter goes around) The last one is where my first approach to the problem with binary search fails. Also, if I may add, the reading a value operation is expensive, so the less often it is done the better. PS: I'm looking for C++ code, but if You know C#, Java, JavaScript or Python and You like to write the algorithm in one of those languages, then it's no problem :).
If I understand correctly, you have an array with random access (if only sequential is allowed, the problem is trivial; that "window" concept does not seem relevant), holding a sequence of positive then negative numbers with a zero in between, but this sequence is rotated arbitrarily. (Seeing the array as a ring buffer just obscures the reasoning.) Hence you have three sections, with signs +-+ or -+-, and by looking at the extreme elements, you can tell which of the two patterns holds. Now the bad news: no dichotomic search can work, because whatever the order in which you sample the array, you can always hit elements of the same sign, except in the end (in the extreme case of a single element of opposite sign). This contrasts with a standard dichotomic case that would correspond to a +- or -+ pattern: hitting two elements of the same sign allows you to discard the whole section in-between. If the positive and negative subsequences are known to have length at least M, by sampling every M/2 element you will certainly find a change of sign and can start two dichotomies.
69,864,700
69,864,788
In place construction of a pair of nonmovable, non copyable in a std::vector
Assume a following non copyable and non movable struct X with no default constructor and with no single argument constructor: struct X { X(int x, int y) { } X(const X&) = delete; X(X&&) = delete; }; and a vector std::vector<pair<X,X>> v. For inserting into v one could use emplace_back if X was constructible from just one argument, since it effectively calls the constructor of std::pair<X,X>. We could do something like this: v.emplace_back(X(42,42),X(69,69)); but in this case a move constructor of X gets called and the latter does not compile. Since this is not possible, we have to make use of the std::piecewise_construct constructor of std::pair and call: v.emplace_back(std::piecewise_construct, std::forward_as_tuple(42,42), std::forward_as_tuple(69,69)); I would expect this to work properly, but the vector, for some reason, is calling move ctor (or copy, if only move was deleted). For example changing the container to be std::list, everything works just fine. Adding a < operator to X and creating a std::map<X,X> (which has pairs of X as the nodes) or std::set<std::pair<X,X>> and using emplace instead of emplace_back all seems to work. What is wrong with std::vector? Full code snippet can be found here.
std::vector is subject to reallocation once the size reach the capacity. when reallocating the elements into a new memory segment std::vector has to copy/move the values from the old segment and this is made by calling copy/move constructors. if you don't need that the elements are sequential in memory you can use std::deque instead, since std::deque doesn't reallocate the elements internally. you can't store non copyable and non moveable objects into std::vectors. EDIT suggested by @François Andrieux In case you still need for any reason an std::vector you may think to use a vector made using std::unique_ptr<X> as value type using std::vector<std::unique_ptr<X>>. With this solution you still don't get a sequential order in memory of your elements, and they are keep in memory till they are still in the vector, so except in case you are forced by any reason to use std::vectors, i think the best match is still the std::deque.
69,864,834
69,864,912
How to std::copy between std::vectors<T> when T has const memers?
My main goal is to combine std::vector with ompenMP to make some parallel computations. I want to go with Z boson's answer where each thread works on its own copy of vector and at the end, we std::copy from all private vectors to the global one. Consider this example: #include<iostream> #include <vector> const int N = 10; class foo { public: foo(int i) : heavy(i), ptr(nullptr) { } foo() : heavy(0), ptr(nullptr) { } // needed by std::vector.resize() const int heavy; // type is not assignable ... foo * const ptr; // drop const to make it work }; int main() { std::vector<foo> tree; tree.resize(N); for (int i = 0; i < N; i += 2) { std::vector<foo> vec_private; vec_private.emplace_back(i ); vec_private.emplace_back(i+1); std::copy(vec_private.begin(), vec_private.end(), tree.begin() + i); } for (auto& x : tree) std::cout << x.heavy << '\n'; return 0; } I have a good reason to keep those consts in foo class. Is there any walk-around to keep them and not get a compile-time error? Would it be possible to employ move semantics for better performance (and possibly to solve problem 1) ? For all I know the elements of std::vector must be stored as a contiguous block of memory, so I'm not sure if move semantics applies here.
Instead of calling resize and then copy-assigning your elements, you can reserve and then copy-initialize them: std::vector<foo> tree; tree.reserve(N); for (int i = 0; i < N; i += 2) { ... std::copy(vec_private.begin(), vec_private.end(), std::back_inserter(tree)); } This won't work if the goal is to have each thread copy their own data into a pre-allocated memory, in parallel. In such a case your options are: Remove the const from the member -- a rather pragmatic approach. Use uninitialized memory instead of a vector: foo *tree = (foo*)::operator new(sizeof(foo)*N); for (int i = 0; i < N; i += 2) { ... // then each thread can do: std::uninitialized_copy(vec_private.begin(), vec_private.end(), tree + i); } With this approach you'll need to call the destructors (tree[i].~foo()) and deallocate (::operator delete(tree)) correctly. This will be tricky though, because you'll need to keep track which threads copy-initialized their elements and which didn't.
69,864,883
69,865,376
How can I use 2d vector as class member in private for create a game-board?
#include <iostream> #include <vector> using namespace std; class board{ public: /* vector<vector<int>>getmyvector(){ return vect; } board(vector<vector<int>>vect2){ vect=vect2; }*/ private: vector<vector<int>vect; }; /* vector<vector<int>> getmyvector(){ //getter return vect; } board :: board(vector<vector<int>>vect2):vect(vect2){ //constructor } */ int main() { vector<vector<int>>vec; vec{ {0,0,1,1,2}, {1,1,0,2,1}, {1,1,2,2,0}, }; board a(vec); return 0; } I am trying to creat a 2d vector in private.But ı try access this vector ı get fail.How can ı load a board 2d vector in private and how can ı use this board publically ? How can ı create a getter,setter or constructor for 2d vector?
You can use the below given program as a starting point(reference). The class board has a private data member named vect and public member functions called getVector, setVector and display. #include <iostream> #include <vector> class board{ public: //create getter std::vector<std::vector<int>> getVector() const { return vect; } //create setter void setVector(std::vector<std::vector<int>> pvect) { vect = pvect; } //display() function that prints elements of the vect data member void display() { for(const std::vector<int> &elem: vect) { for(int intElem: elem) { std::cout<<intElem<<std::endl; } } } private: std::vector<std::vector<int>> vect; }; int main() { //create a board instance board myBoard; std::vector<std::vector<int>> vect{ {0,0,1,1,2}, {1,1,0,2,1}, {1,1,2,2,0}, }; //use the setter to set the vect data member myBoard.setVector(vect); //lets print out the elements of the data member vect for the object myBoard using the display() member function myBoard.display(); return 0; } The output of the above program can be seen here.
69,864,982
69,865,039
How to instantiate a class from the stack with different constructors?
I need to create a class instance from the stack, but depending on a variable I need to call it with different constructors class A { public: A(std::string str); A(int value) }; void main(void) { bool condition = true; A class_a {condtion ? "123" : 456}; } But I can't get it to compile.
The ternary operator can't return different types for true and false. You could solve it like this: A class_a = condition ? A("123") : A(456); Other fixes: #include <string> class A { public: A(std::string str) {} // the function must have an implementation A(int value) {} // the function must have an implementation }; int main() { // not void main bool condition = true; A class_a = condition ? A("123") : A(456); }
69,865,183
69,865,504
Get address of object cast to arithmetic type at compile time
I'm trying to implement x86 page tables/page directories in C++ and I would like to be able to construct these at compile time. In order to do this I need to be able to obtain the address of static constexpr page table objects at compile time, cast to an arithmetic type, such that I can use them to construct static constexpr page directory entries as such: struct PageTable { /* ... */ }; struct PageDirectory { constexpr PageDirectory(std::initializer_list<uint32_t> entries) { /* ... */ } /* ... */ }; static constexpr PageTable pt { /* ... */ }; static constexpr PageDirectory pd { reinterpret_cast<uint32_t>(&pt) | WRITE | PRESENT, /* ... */ }; This does not work because reinterpret_cast cannot be used inside a constant expression. Is there any other way I could realize this or something similar?
At compile-time, you're not generally allowed to do low-level chicanery like accessing the numerical value of an address. Even C++20's bit_cast is explicitly not constexpr if the source object is (or contains) a pointer. This is important because the address of things at runtime is not the same as their compile-time address. Indeed, the part of your build system that deals with constant evaluation (aka: the compiler) is not the same part of the build system that deals with assigning addresses to things (aka: the linker). Since the compiler cannot see the future, it is incapable of computing what the runtime address of a compile-time object will be. Of course, there's also the fact that the linker itself may not know what that address will be, as modern OS's typically assign executables to arbitrary virtual addresses that are different with each loading of the executable. And while the linker/OS doesn't have to do this, the language does need to take this into account in terms of its design. That is, it can't do something that would make such things impossible or infeasible to implement.
69,865,908
69,866,046
The c++ standard documentation says a program shall not call the main function, but I did
It explicitly says in the c++ standard documentation that a program may not call main. Yet I wrote a program that calls main and works perfectly fine, why is that? The code: #include<iostream> static int counter = 0; int main(){ counter++; std::cout << counter << " It works" << std::endl; while(counter < 10){ main(); } return 1; } It prints to console "It works" 10 times. According to the standard documentation, this should not work, yet it works. What's going on?
basic.start.main/3: The function main shall not be used within a program. Violating this rule makes your program have undefined behavior - which means that the program can do pretty much anything. It may even do what you wanted it to do or appear to do what you wanted but have devastating side effects, so avoid having undefined behavior in your programs. Regarding the lack of diagnostic messages: I suspect that some compilers, like g++, actually support calling main as an extension. I had to turn on -pedantic or -pedantic-errors to get the diagnostic message "ISO C++ forbids taking address of function '::main' [-Wpedantic]"
69,866,102
69,866,160
How to avoid copy when i want to move data from stack to vector?
I have a very-frequently used operation, which need to move data from stack into vector. let me write a demo code: void handle(const std::vector<std::vector<std::pair<size_t, double>>> & v) { // this is my handle data function } int main() { std::stack<std::vector<std::pair<size_t, double>>> data; // this is my data container, it's a stack int cnt = 0; std::vector<std::vector<std::pair<size_t, double>>> params(3); while (cnt++ < 3) { // assume this handle need 3 data const auto & v = data.top(); params[cnt] = v; // i think this will involve copy operation // and in real scene, i need to keep params in order, // so i cant use emplace back, only can use [i] data.pop(); } handle(params); } can you help on this, how can i avoid copy and speed up my code?
This, your code, will create a copy of the vector. const auto & v = data.top(); params[cnt] = v; This will avert the copy, by moving the vector out of data. auto & v = data.top(); params[cnt] = std::move(v); Both operations are described, as forms (1) and (2), in cpprefernce.
69,866,267
69,866,419
Downloading files within a QCoreApplication
I work in a team to develop a QT Application with c++. Among other things, the app needs to download files from the internet. Here is the code I wrote to download files: int main(int argc, char *argv[]){ QCoreApplication app(argc, argv); QNetworkAccessManager man; std::string urlc = "https://upload.wikimedia.org/wikipedia/commons/7/73/Flat_tick_icon.svg"; //Ramdom svg file QUrl url(QString::fromStdString(urlc)); QNetworkRequest req(url); QNetworkReply* reply = man.get(req); QObject::connect(reply, &QNetworkReply::finished, [department, region, &reply](){ QByteArray read = reply->readAll(); QString savefile = QString::fromStdString("file.png"); QFile out(savefile); out.open(QIODevice::WriteOnly); out.write(read); out.close(); reply->close(); reply->deleteLater(); app.quit(); }); return app.exec(); } The above code works well and downloads the file at the specified url. However, if I try to extract the downloading of files to a separate function (see code below), the program doesn't work. In fact, it never even starts downloading the file. std::string download_file(){ QNetworkAccessManager man; std::string urlc = "https://upload.wikimedia.org/wikipedia/commons/7/73/Flat_tick_icon.svg"; //Ramdom svg file QUrl url(QString::fromStdString(urlc)); QNetworkRequest req(url); QNetworkReply* reply = man.get(req); QObject::connect(reply, &QNetworkReply::finished, [department, region, &reply](){ QByteArray read = reply->readAll(); QString savefile = QString::fromStdString("file.png"); QFile out(savefile); out.open(QIODevice::WriteOnly); out.write(read); out.close(); reply->close(); reply->deleteLater(); }); return "file.png"; } int main(int argc, char *argv[]){ QCoreApplication app(argc, argv); std::string path = download_file(); std::cout << path << std::endl; return app.exec(); } What can be the reason for such behaviour?
The difference is that QNetworkAccessManager has a greater scope in the first case, as opposed to the second case, which is only a local variable, so it will be destroyed at the attempt. One way to solve is to create a class that handles all the logic: #include <QCoreApplication> #include <QFile> #include <QNetworkAccessManager> #include <QNetworkReply> class Downloader: public QObject{ Q_OBJECT public: Downloader(QObject *parent=nullptr):QObject(parent){ connect(&m_manager, &QNetworkAccessManager::finished, this, &Downloader::handle_finished); } void download(const QUrl & url, const QString & filename){ QNetworkRequest request; request.setUrl(url); request.setAttribute(QNetworkRequest::User, filename); m_manager.get(request); } Q_SIGNAL void finished(bool); private: void handle_finished(QNetworkReply *reply){ bool ok = false; if(reply->error() == QNetworkReply::NoError){ QByteArray read = reply->readAll(); QString filename = reply->request().attribute(QNetworkRequest::User).toString(); QFile out(filename); if(out.open(QIODevice::WriteOnly)){ out.write(read); out.close(); ok = true; } } else{ qDebug() << reply->error() << reply->errorString(); } reply->deleteLater(); Q_EMIT finished(ok); } QNetworkAccessManager m_manager; }; #include "main.moc" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Downloader downloader; QObject::connect(&downloader, &Downloader::finished, [](bool sucess){ qDebug() << "download" << sucess; }); downloader.download(QUrl("https://upload.wikimedia.org/wikipedia/commons/7/73/Flat_tick_icon.svg"), "file.svg"); return a.exec(); }
69,866,617
69,866,683
Printing Value From Array in C++
I want to write a method in C++ which creates an array of monotonically increasing values. It has the inputs of int begin, int end, int interval. In this example; method should return the array of [0,1,2,3,4,5,6,7,8,9,10]. When I print the results it should print out the first two indexes and get 0 and 1. However, when I print it, it gives 0 for the first one and 9829656 for the second one. When I only print one index it is always correct, but when I print more than one index, every value except for the first printed one gives a different result. I think the other results are related to memory address since I used pointers. #include <iostream> using namespace std; int* getIntervalArray(int begin, int end, int interval){ int len = (end - begin) / interval + 1; int result[11] = {}; for (int i = 0; i <= len - 1; i++) { result[i] = begin + interval * i; } return result; } int main(){ int begin = 0; int end = 10; int interval = 1; int* newResult = getIntervalArray(begin, end, interval); cout << newResult[0] << endl; cout << newResult[1] << endl; return 0; }
try this. also add deletion of the newResult #include <iostream> using namespace std; int* getIntervalArray(int begin, int end, int interval){ int len = (end - begin) / interval + 1; int* result = new int[len]; int lastValue = begin; for (int i = 0; i <= len - 1; i++) { result[i] = lastValue; lastValue += interval; } return result; } int main(){ int begin = 0; int end = 10; int interval = 1; int* newResult = getIntervalArray(begin, end, interval); cout << newResult[0] << endl; cout << newResult[1] << endl; // add delete here. return 0; }
69,867,071
69,867,157
How to save data in file I/O in c++
i was trying to create login and registration syste. The registration work perfectly well until i stop the app and run it again so that i can login(it delete everything in the file). How can I make my file save even when I run again my app bellow is attached my code #include <iostream> #include <fstream> using namespace std; double amount; int main () { ifstream fin; ofstream fout; fin.open("admin.txt"); fout.open("userDB.txt"); int number; string username,password, adminUsername, adminPassword,newusername,newpassword; fin>>adminUsername; fin>>adminPassword; if(number == 1){ cout<<"Welcome to the Normal User Login Page : \n\n"; cout<<"Enter Username : "; cin>>username; cout<<"Enter password : "; cin>>password; } else if(number == 2) { cout<<"Welcome to the Registration and Deposit Page\n"; cout<<"Enter administrator username and password.\n"; cout<<"Enter username : "; cin>>username; cout<<endl; cout<<"Enter Password : "; cin>>password; if(username == adminUsername){ if(password == adminPassword){ cout<<"Welcome admin \n"; cout<<"1. Deposit money for client\n"; cout<<"2. Register new client\n"; cout<<"3. Reset your password \n\n"; cout<<"Enter option to proceed : "; cin>>number; if(number==2){ cout<<"Client register form\n"; cout<<"Enter client username : "; cin>>newusername; cout<<"Enter client password : "; cin>>newpassword; cout<<"initial deposit : "; cin>>amount; fout<<newusername<<endl; fout<<newpassword<<endl; fout<<amount<<endl; } } else{ cout<<"Wrong password"; } } else{ cout<<"Wrong UserName"; } } fin.close(); fout.close(); return 0; } I am new to C++ kindly help.
It is because whenever the output file is opened it clears the contents of it. You need to specify the option to append to the file in order to prevent that: fout.open("userDB.txt",std::ios_base::app);
69,867,221
69,868,066
Solving a C2039 error and a C3861 error using std::minmax_element
I'm newer to C++. I've written the following line in a test function inside a standard VS2019 test project: auto minAndMaxYards = std::minmax_element(simResults.begin(), simResults.end()); It yields both C2039 and C3861 errors for the minmax_element function even though intellisense recognizes it as a member of std, and I can peek its definition. I can't figure out what I'm missing. I've included the algorithm file as well at the top of the test project. Is there a project setting that I don't have right? Full error text: C2039 'minmax_element': is not a member of 'std' C3861 'minmax_element': identifier not found Edit, including code in case it helps #include <algorithm> #include "pch.h" #include "CppUnitTest.h" #include "Playbook.h" #include "PlaySim.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; std::string output; using std::vector; namespace FootballDynastyV20UnitTest { TEST_CLASS(PlaybookIO) { public: TEST_METHOD(setAndGetPlayblookName) { Playbook testPlays; string testName = "testPlays"; testPlays.setName(testName); string name = testPlays.getName(); Assert::IsTrue(name == testName); } TEST_METHOD(addPlayIncrementsPlayNum) { Playbook testPlays; string playName = "Play1"; int numDLine = 4; int numLB = 3; vector<int> playerPos = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 19 }; vector<int> playerStance = { 2, 1, 0, 0, 1, 2, 2, 3, 2, 3, 3 }; vector<int> playerBlitzGaps = { 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0 }; testPlays.setName("testPlays"); testPlays.addPlay(playName, numDLine, numLB, playerPos, playerStance, playerBlitzGaps); Assert::IsTrue(testPlays.getNumPlays() == 1); } TEST_METHOD(saveAndLoadPlayblook) { Playbook testPlays; Playbook testPlaysLoad; string playName = "Play1"; int numDLine = 4; int numLB = 3; vector<int> playerPos = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 19 }; vector<int> playerStance = { 2, 1, 0, 0, 1, 2, 2, 3, 2, 3, 3 }; vector<int> playerBlitzGaps = { 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0 }; testPlays.setName("testPlays"); testPlays.addPlay(playName, numDLine, numLB, playerPos, playerStance, playerBlitzGaps); testPlays.save(); testPlaysLoad.load(testPlays.getName()); Assert::IsTrue(testPlays == testPlaysLoad); } }; TEST_CLASS(PlaySimTesting) { public: TEST_METHOD(playSimReturnsYdsGainedBetweenNegative10And40) { PlaySim newPlay; int numSims = 2000; int lwrBound = -10; int uprBound = 40; vector<int> simResults; for (int i = 0; i < numSims; i++) { newPlay.Run(); simResults.push_back(newPlay.GetYds()); } auto minAndMaxYards = std::minmax_element(simResults.begin(), simResults.end()); int actualMin = *minAndMaxYards.first; int actualMax = *minAndMaxYards.second; int yds = newPlay.GetYds(); Assert::IsTrue((actualMin >= lwrBound) && (actualMax <= uprBound)); } }; }
Move #include "pch.h" to the top of the file. When using precompiled headers, the compiler ignores everything above this line. In your example, that would be #include <algorithm>, that's why std::minmax_element is not found.
69,867,376
69,867,492
Why does calling a function on seperate lines change the result in c++?
It seems that for some reason when I try to call two functions on the same line, the first function receives an nullptr from ".get()" as the first argument getSomePtr(someUniquePtr.get(), someArray)->moveUniquePtr(std::move(someUniquePtr)); But when separating these functions in to two separate lines, everything seems to work: auto* somePtr = getSomePtr(someUniquePtr.get(), someArray); somePtr->moveUniquePtr(std::move(someUniquePtr)); Why does this happen?
When evaluating an expression, function arguments are evaluated before the function that takes those arguments is called. However, outside that rule, the compiler gets to choose the order of evaluation. It looks like, in your first case, it chose to evaluate moveUniquePtr before evaluating someUniquePointer.get(). Because one sub-expression modifies the state used in the other sub-expression, the result of the overall expression is not well-defined. Splitting the expression into sequential statements, as in your second case, explicitly chooses the order of evaluation, and is the right thing to do in cases like this.
69,867,527
69,867,654
Can void loops run independently?
Basically, I have an Arduino Uno R3 hooked up to a 16x2 LCD screen and I want to make 3 different texts appear in the span of 16 seconds on line 0, and on line 1 I would like to add a seconds counter. When starting it the text portion works just fine but the seconds counter only appears after the 16 seconds when all 3 texts have been shown, showing the number 16. When those 3 texts appear once more the counter will now say 32 then 48, 64 so on and forth. So it only shows something after 16 seconds have passed. What I would like it to do is show every second that has passed (for example 1, 2, 3, 4, 5, 6). Here is what I have so far: #include <LiquidCrystal.h> const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { lcd.begin(16, 2); } void loop() { text(); counter(); } void text() { lcd.setCursor(6, 0); lcd.print("Text1"); delay (8000); lcd.setCursor(6, 0); lcd.print(" "); lcd.setCursor(6, 0); lcd.print("Text2"); delay (4000); lcd.setCursor(6, 0); lcd.print(" "); lcd.setCursor(6, 0); lcd.print("Text3"); delay (4000); lcd.setCursor(6, 0); lcd.print(" "); } void counter() { lcd.setCursor(7, 1); lcd.print(millis() / 1000); } Any help will be greatly appreciated.
Arduinos are single core controllers, so you are not able to run multiple loops in parallel without additional tasking features. What you most propably are looking for is called the Superloop. This is basically an endless loop, containing all tasks of your system. Tasks are then executed if a timing condition matches. You can find a lot of introduction and literature to it in the internet and sites like: WikiBooks: Embedded Systems/Super Loop Architecture Novos: Super Loop – a Good Approach? Microcontrollerslab: Bare-metal and RTOS Based Embedded Systems You can achieve this in a very simple way like: void loop() { //Check if task 1 needs to be executed if (millis() - task1LastMillis >= 100) { //Get ready for the next iteration task1LastMillis = millis(); myFunction1(); } //Check if task 2 needs to be executed if (millis() - task2LastMillis >= 500) { //Get ready for the next iteration task2LastMillis = millis(); myFunction2(); } //... } Note that there are other but more complicated options like using RTOS achieving similar multitasking behaviours.
69,867,860
69,867,913
Forging multiple name lists from a text file into one
I need to get a list of names from a txt file, and then sort them in alphabetical order. But let's just focus first on getting the list itself.. This is the input txt file (the format is given by the exercise) (comments are explanation given by the exercise, they're not actually there) 3 // the number of total name groups 5 // the number of names in the individual group Ambrus Anna Bartok Hanna Boglar Berkeczi Aron Kovacs Zoltan David Sukosd Mate 7 Biro Daniel Csoregi Norbert Drig Eduard Dulf Henrietta Fazekas Gergo Gere Edit Pandi Aliz 6 Albert Nagy Henrietta Benedek Andor Gere Andor Lupas Monika Pulbere David Sallai Mark So, I'm trying to get all 3 of the individual name groups and put them in a single array.. Here is the code: #include <iostream> #include <fstream> #include <string.h> using namespace std; void input(const char* fname, int& n, char students[100][100]) { ifstream file(fname); int groups, studNum; char temp[50], emptyline[50]; file >> groups; for(int i = 0; i < groups; i++) { file >> studNum; file.getline(emptyline, 100); //I actually don't know why there is an empty line after the numbers for(int j = 0; j <= studNum; j++) { //I'm going line by line with getline.. I'm not using fin, because sometimes the name consists of 3 elements, sometimes of 2 file.getline(temp, 100); strcat(students[j + n], temp); } n += studNum; } file.close(); } int main() { int n = 0; char students[100][100]; input("aigi4153_L2_6.txt", n, students); //printing the array for(int i = 0; i < n; i++) { cout << students [i] << endl; } return 0; } So, the code looks good, and it almost works.. The output is 99% great, but there is a mysterious "6" before the name "Pulbere David".. And I have no idea how that goes there.. I don't think it has to do anything with the "6" before "Albert Nagy Henrietta", because if I change it to "7" for example, the mysterious "6" will remain the same number.. So, output is like this: Ambrus Anna Bartok Hanna Boglar Berkeczi Aron Kovacs Zoltan David Sukosd Mate Biro Daniel Csoregi Norbert Drig Eduard Dulf Henrietta Fazekas Gergo Gere Edit Pandi Aliz Albert Nagy Henrietta Benedek Andor Gere Andor Lupas Monika 6Pulbere David //here is the "mysterious 6" Sallai Mark Any ideas on how that 6 got there?
You're reading the 6 as part of the names, your innermost loop should be: for(int j = 0; j < studNum; j++) and not for(int j = 0; j <= studNum; j++) Also, you never initialize the contents of the students array, so strcat will try to append the name to a string that possibly contains anything. You should zero out the contents: char students[100][100]; memset(students, 0, sizeof(students));
69,867,979
69,868,032
Checking if a string contains a substring C++
I'm trying to make a program that checks if a string contains a substring of another string, but it's not working. Here is my code: #include <iostream> #include <algorithm> using namespace std; //Struct to store information struct strings { char string1[20], string2[20]; } strings; //Function to check if the strings are equal void equalCheck(){ int check = 0, i = 0; while (strings.string1[i] != '\0' || strings.string2[i] != '\0'){ if (strings.string1[i] != strings.string2[i]){ check = 1; break; } i++; } if (check == 0){ cout << "The strings are equal" << endl; } else cout << "The strings are not equal" << endl; } //Function to check for a substring void substringCheck(){ if (strings.string1.find(strings.string2) != string::npos) { cout << "found!" << '\n'; } } int main() { //Ask the user for two strings cout << "Please type the first string: "; cin >> strings.string1; cout << "Please type the second string: "; cin >> strings.string2; //Prints out the two strings //cout << "The two strings are " << strings.string1 << " and " << strings.string2; equalCheck(); substringCheck(); return 0; } This is the problem I get: Any ideas?
Wouldn't it be easier for strings to have two std::string instead of two char[20]? Then you would be able to say this with no problem: if (strings.string1.find(strings.string2) != std::string::npos) { std::cout << "found!" << '\n'; } char is not a class like std::string, it doesn't have any member functions. This means char[20].find doesn't exist. std::string is a class, however. And it does have a member function called std::string::find(), so doing this to a std::string is legal.
69,868,100
69,868,255
Why would you ever use heap allocation for objects you will reference through an std::vector?
I'm going through some code from this article about ECS-systems in game programming and trying to understand it, and something I'm seeing a lot is using heap memory in places where it seems like there is no benefit in doing so. Take this as an example: class ECS { public: void someFunction() { archetypes.push_back(new Archetype); } ~ECS() { for(Archetype* a : archetypes_) { delete a; } } private: std::vector<Archetype*> archetypes_; }; This is the only way that the archetypes are manipulated in memory in the code. There is also no polymorphism involved here whatsoever. The archetypes being on the heap here has seemingly no impact on the code other than the fact that the archetypes are referenced by pointers. Why would you ever choose to use allocated memory for this? I see this often in code and it seems to me like using heap memory just because it feels like the right thing to do, and not actually considering if it's the appropriate place for it. std::vector already uses heap memory behind the scenes so why not just copy a stack variable into the vector when we want to add a new archetype, and let the vector handle the allocation? class ECS { public: void someFunction() { archetypes.push_back(Archetype()); } private: std::vector<Archetype> archetypes_; }; Or are there valid reasons for using heap memory in cases like this?
The obbious reason would be that you don't want the data items to be moved/copied when the vector grows, There may be several reasons for that, one is that the types are expensive (or even impossible) to move/copy, another is that you don't want pointers to the individual archetypes to be invalidated by changes to the vector,
69,868,397
69,868,458
Vector Iterators Incompatible: proper way to iterate over two vectors?
One of my teachers has tasked us with creating a class that can iterate over two different vectors to make them appear as though they are contiguous from the pov of the caller. One of the requirements is that the vectors mustn't be copied. From what I understand, iterators from two different vectors cannot be compared so I fail to see what the proper way to write this class would be. Here's the teacher's version with a few fixes from me: class concat { std::vector<std::string>& vec1; std::vector<std::string>& vec2; public: concat(std::vector<std::string>& v1, std::vector<std::string>& v2) : vec1(v1), vec2(v2) {} class iterator { std::vector<std::string>::iterator it; concat* context; public: iterator(std::vector<std::string>::iterator& it, concat* context) : it(it), context(context) {} std::string& operator*() { return *it; } iterator& operator++() { it++; if (it == context->vec1.end()) it = context->vec2.begin(); return *this; } bool operator!=(const iterator& other) const { return (context != other.context) || (it != other.it); } }; iterator begin() { return iterator(vec1.size() ? vec1.begin() : vec2.begin(), this); } iterator end() { return iterator(vec2.end(), this); } }; And the corresponding main: vector<string> v1; v1.push_back("abc"); v1.push_back("def"); vector<string> v2; v2.push_back("ghi"); v2.push_back("jkl"); concat conc = concat(v1, v2); for (const string& s : conc) cout << s << ":"; This fails on debug with a "Debug Assertion Failed" message: Vector Iterators Incompatible on line return (context != other.context) || (it != other.it); using Visual Studio 2019.
The way to do this is to hold internally two iterators. One to vec1, the other to vec2. First use the first one, then after the first one reaches the end of vec2 switch to the other one. Some snippets to see what I mean: itnerator& operator++() { if (it1 != vec1.end()) ++it1; else ++it2; return *this; } std::string& operator*() { if (it1 != vec1.end()) return *it1; else return *it2; }
69,868,761
69,868,960
Should i use pointers or references?
I'm having problems figuring out if i should use pointers or references in certain methods I have a method called issueOrders(Orders* order) which takes a reference to an Orders object This method should add the pointer to order to a vector containing pointers to orders void Player::issueOrder(Orders* order) { ordersList->getOrdersList().push_back(order); } where ordersList is an object containing a vector of ordersList as parameter Like this: class OrdersList{ private : vector<Orders*> ordersList public: vector<Orders*> getOrdersList(); } But the issueOrders method doesnt work, that is, nothing is pushed in the vector and im confused as to why. Thanks for reading and any help is appreciated! :)
As @UnholySheep pointed out, your getter returns a copy of the ordersList vector. What you want is a reference (or a pointer), so that your push_backs affect the vector. So you want to change its declaration to this: vector<Orders*>& getOrdersList(); And change its definition accordingly. Whether or not you should store your Orders as pointers or references has nothing to do with the problem. And as the correct answer to the question in your title is largely dependent on the type of the data and the way it's going to be used, it's hard to give you an answer with just the code snippets. I suggest you take a look at this answer: https://stackoverflow.com/a/8259173/13191576
69,868,833
69,868,995
Cython: How to export C++ class to .hpp header instead of C .h header
This works fine in .pxd file: cdef public: struct foo: float bar But this doesn't work: cdef public: class foo: float bar # Syntax error in simple statement list This works but Cython is still making struct instead of class and the resulting file is .h file instead of .hpp (or .hh) file: cdef public: cppclass foo: float bar My file is called mod.pyx and Cython transpiles the cppclass right above as: #ifndef __PYX_HAVE__mod #define __PYX_HAVE__mod #include "Python.h" struct foo; struct foo { /* "mod.pyx":21 * * cdef public: * cppclass foo: # <<<<<<<<<<<<<< * float bar * */ float bar; }; How to make real C++ output from Cython transpilation? I mean .hpp or .hh files with class keyword inside. It's possible to use a separate C++ header file instead but I would like to make the source code fully Cython. The transpile command is: cython3 -3 --cplus --fast-fail mod.pyx
I've figured out how to define C++ class (not the Python extension type 'class') in Cython only; it is still transpiled to .h file as struct but with methods inside: # Declaration cdef public: cppclass foo: float bar foo() # Constructor method() # Sample method # Implementation cdef cppclass foo: method(): cdef foo* p = this # 'this' can be used print(p.bar+1) # Test There are some notes: The nullary constructor is a must, Cython says so This doesn't require constructor: cdef foo* f = new foo() This requires a constructor: cdef foo f = foo() Or error: no constructor found for C++ type 'foo' No overloads in Python, which applies to Cython and so no constructor overloads (?); properties to be set by a method instead
69,868,985
69,869,287
c++ fstream getline function adds \r to the line size
When I run my code on Clion I dont get this error. But when i run my code on my school's dev server, I realize every line size except the last line in my file below has a size line.size()+1. This is my file 6 5 8 2 5 6 7 5 4 7 3 2 1 2 5 3 4 7 5 6 5 8 7 2 3 6 4 3 1 1 2 2 7 8 2 1 6 2 1 1 2 2 4 4 0 5 3 2 2 It reads first line size as 2 etc. It reads every line size as size +1 except last line. And this is my code. #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> using namespace std; int num; vector <vector <int> >board; int points = 0; int main(int argc, char **argv) { string file_name_2 ; vv << argv[2]; vv >> file_name_2; stringstream vd; fstream myFile; myFile.open(file_name_2, ios::in); if (myFile.is_open()) { string line; int index = 0; while(getline(myFile, line)){ if (line.size()== 1 || line.size()==2 || line == "100"){ stringstream zz; zz << line; zz >> num; . . . I am using getline(file_name, line) to read lines. What causes this and how can i fix it?
The problem was caused by the text file not having UNIX-style line endings ("\n"), but instead having Windows-style line endings ("\r\n"). On Windows, when opening a file in text mode (without ios::binary), the "\r\n" line endings are automatically converted to "\n" line endings. On Linux, this conversion is not necessary, because they are supposed to be stored as "\n" in the first place. Therefore, on Linux, there is no difference between opening a file in text mode or binary mode, because in both cases, no conversion is performed. However, uploading a text file with Windows-style line endings onto a Linux server is likely to cause trouble. As described above, on Linux, the "\r\n" line endings will not automatically be converted to "\n" line endings when opening the file in text mode, because on Linux, text files are expected to already have "\n" line endings. This is probably the reason why you say that getline reads an extra byte when running your program on the Linux server. Most text editors running on Windows create Windows-style line endings. However, some advanced text editors also allow you to save the file with UNIX-style line endings. Also, some data transfer programs allow you to convert the files as part of the data transfer process. In order to convert a text file from Windows-style line endings to UNIX-style line endings, you can use programs such as dos2unix or sed. You can also easily write such a program yourself, since the program does nothing else than remove all carriage return ('\r') characters: #include <stdio.h> int main(void) { int c; while ( ( c = getchar() ) != EOF ) if ( c != '\r' ) putchar( c ); }
69,869,100
69,869,236
Is it possible for a C++ iterator to have gaps and not be linear?
I wrote a C++ iterator to go over an std::string which is UTF-8. The idea is for the iterator to return char32_t characters instead of bytes. The iterator can be used to go forward or backward. I can also rewind and I suppose the equivalent of rbegin(). Since a character can span multiple bytes, my position within the std::string may jump by 2, 3, or 4 bytes (the library throws if an invalid character is encountered). This also mean the distance to a certain character does not always increment one by one. In other words, ++it may increment the position by a number from 1 to 4 and --it reverse subtract in a similar manner. Is that an expected/legal behavior for a C++ iterator?
Many algorithms in C++ work equally well with plain pointers in addition to iterators. std::copy will work with plain pointers, just fine. std::find_if will be happy too. And so on. By a fortunate coincidence std::copy invokes the ++ operator on the pointers you feed to it. Well, guess what? Passing a bunch int *s to std::copy results in the actual pointer being increment by sizeof(int), instead of 1. std::copy won't care. The properties of iterators and their requirements are defined in terms of the logical results and the logical effects of what the various operators cause to happen (as well as which operators are valid for a given iterator). Whether the internal implementation of an iterator increments the internal value, that represents the iterator in some way, by 1, 2, 4, or 42, is immaterial. Note that reverse iterators result in the actual internal pointer getting decremented by its ++ operator overload. If your custom iterator's implementation of the ++, --, *, [], +, and - operators (whichever ones are appropriate for your iterator) meets all requirements of their assigned iterator category, then the actual effects of these operators on the actual raw pointer value, that represents your iterator, is irrelevant. The answer to your question is as follows, assuming that your custom iterator is a random access iterator: if all the required operator overloads meet all requirements of a random access iterator, then the actual effects on the underlying pointer value are irrelevant. The same holds true for any iterator category, not just random access.
69,869,356
70,051,285
Makefile objects in different folders with wildcard & headers (modular compile)?
UPDATE#04: Got everything compiling. Will keep the answer concise so here are some intermediary steps. Basically the Rules only partially worked because the objects were being made in their own folder still. After creating new local object Rules it compiled. However since they were now in their own directory the modular compile could not assemble the objects & work properly (programs will error when run). The answer is a new patsubst pattern (of course), but I finally found one by trial & error that will allow output with wildcard + the original Rules + Recipes (for modular compiling with multiple targets). See the answer below. UPDATE#03: Modular wildcard compile now works for the Client by trying patterns & rules in the order below & only changing them if they fail. However, I'm now unable to compile the Server from the Client objects & getting a bunch of .c:(.text+0xb28): undefined reference to My_Func_Call type errors. I've sorta given up on trying to move the objects to another path because Make just refuses to follow the rules properly or compile (will come back to that later). Anyone know why objects/refs can't be reused now from the Client for the Server or any ideas on what might work? # Pattern 1: CODE = $(wildcard $(PATH)/*.c) OBJS += $(CODE) # Pattern 2: CODE = $(wildcard $(PATH)/*.c) CODE_OBJS = $(CODE:%.c=%.o) OBJS += $(CODE_OBJS) # Pattern 2 & Rule: CODE = $(wildcard $(PATH)/*.c) CODE_OBJS = $(CODE:%.c=%.o) OBJS += $(CODE_OBJS) $(BPATH)/%.o: $(PATH)/%.c $(PATH)/%.h $(COMMON_PATH)/%.h %.o: %.c $(DO_CC) UPDATE#02: I continued to implement this pattern of wildcarding other sub dirs & just ignored where the objects are stored, but now the new compiled sub dirs seem to be causing conflicts. The previous header vars are missing (even though I changed nothing in the previous compiled code). This is caused by having multiple nested %o: %c rules I'm guessing (so that means I can't do anymore sub dirs argh). I'm very open to someone pointing me towards some pattern or resources that might be in the area of this issue? Most of what I've seen are these simple Makefiles that have the same solutions over & over (non-modular compiles). Otherwise, I think I'm going to go download GNU Make & start going line by line commenting it to figure out what is going on with the data. One thing is reading about stems & another is knowing what syntax or structure that Make actually needs to not break. UPDATE#01: Need a Makefile with objects in different folders & working with headers. I have it working in one path setup, but with a different path it's requiring more code to find the headers & not able to place the objects in a different folder. This is basically what is happening in a minimal example -- any ideas?: CODE00 = $(wildcard $(PATH00)/*.c) OBJ00 = $(CODE00:%.c=%.o) OBJS = $(OBJ00) CODE = $(wildcard $(PATH)/*.c) HEADER = $(wildcard $(PATH)/*.h) $(wildcard $(COMMON_PATH)/*.h) # Alt header. #OBJ = $(patsubst %.c, %.o, $(CODE)) # Also works. OBJ = $(CODE:%.c=%.o) OBJS += $(OBJ) ############ # RULES: ############ # Works: $(BPATH00)/%.o: $(PATH00)/%.c $(PATH00)/%.h $(PATH01)/%.h # Objs in folder/headers work. $(DO_CC) # Broken: $(BPATH)/%.o: $(PATH)/%.c $(PATH)/%.h $(COMMON_PATH)/%.h # Requires more before DO_CC? #%.o: %.c # Works but .o in source folder, fails without. #%.o: %.c ${HEADER} # Works but .o in source folder, fails without. $(BPATH)/%.o: %.c # Fails with missing header vars. #$(BPATH)/%.o: %.c ${HEADER} # Fails with missing header vars. $(DO_CC) ############ # LINK: ############ define DO_CC gcc $(OBJS) $(CFLAGS) -o $@ -c $< endef
Here is the working pattern for wildcard & modular compiles with multiple targets. NOTE: You will have to remove header includes or conflicting %.o: %o.c Rules needed for same folder objects. Otherwise it will cause lots of weird missing target errors that change when you alter the Rule order (which just wastes your time & is confusing). HOST_CODE := $(wildcard $(HOST_PATH)/*.c) HOST_OBJECTS = $(patsubst $(HOST_PATH)/%.c, $(HOST_BPATH)/%.o, $(HOST_CODE)) CLIENT_OBJECTS = $(patsubst $(HOST_PATH)/%.c, $(CLIENT_BPATH)/%.o, $(HOST_CODE)) # Or to append: HOST_CODE := $(wildcard $(HOST_PATH)/*.c) HOST_OBJECTS += $(patsubst $(HOST_PATH)/%.c, $(HOST_BPATH)/%.o, $(HOST_CODE)) CLIENT_OBJECTS += $(patsubst $(HOST_PATH)/%.c, $(CLIENT_BPATH)/%.o, $(HOST_CODE)) # Rules (includes/headers will break your compile): $(HOST_BPATH)/%.o: $(HOST_PATH)/%.c $(DO_HOST_CC) $(CLIENT_BPATH)/%.o: $(HOST_PATH)/%.c $(DO_CLIENT_CC) You won't need header include Rules. But if you want to test to see if your headers are working I recommend this non-conflicting pattern (many patterns easily conflict & break your Makefile, so you need to be VERY careful): INCLUDES = $(shell find . -name '*.d') include $(INCLUDES)
69,869,368
69,869,381
I cannot pass arguments to my class in c++
I’m trying to pass an argument to my class but it’s not working the #includes #include <iostream> #include <vector> #include <algorithm> #include <string> #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif the class Name and age are vectors Don’t mind the function called oldP class user{ public: vector<string>Name; vector<int>Age; void outP() { for (unsigned int i = 0; i < Name.size(); i++) { cout << Name[i] << " , "; } } user(vector<string> name, vector<int> age) { Name = name; Age = age; } }; This is the function that uses the name and age and tries to pass it into the class int holder() { string _name; int _age; int f = 0; while (true) { f++; cout << "enter name :"; cin>>_name; cout << endl; cout << "enter age :"; cin >> _age; if (f == 6) { break; } } user user1 = user(_name ,_age); return 0 } The program partially runs for when the function is called it breaks
Your constructor takes arguments of type vector<string> and vector<int> but you are trying to pass in values of type string and int. Since there is no implicit conversion from a given type T to a type vector<T>, you'll need to rectify that mismatch -- either change the types that constructor accepts, or change the types of the variables that you are passing to the constructor. Based on the names of the variables, my guess is you want to get rid of vector entirely... unless there is some reason why a given user should be allowed have multiple names and multiple ages?
69,869,523
69,869,560
[C++]Why Iterating over a std::string using std::stringstream gives an exception character?
I'm trying to implement a simple format function that fills in the corresponding content based on the given format character. I use std::stringstream to convert the given format string into a stream, and then take out the characters one by one. Then, based on the individual characters, fill in the relevant content into the output stream. The format string is given in std::string type. #include <iostream> #include <sstream> #include <string> int main() { std::string fmt = "[%t]%Y-%M-%D<%H:%m:%s>:%c"; std::stringstream s_res; std::stringstream s_fmt(fmt); while (s_fmt.good()) { char c = (char) s_fmt.get(); if (c == '\0') break; // I'm not sure this stagement is necessary. if (c == '%') { switch (s_fmt.peek()) { case 't': s_res << "Type"; break; case 'Y': s_res << "Year"; break; case 'M': s_res << "Month"; break; case 'D': s_res << "Day"; break; case 'H': s_res << "Hour"; break; case 'm': s_res << "min"; break; case 's': s_res << "sec"; break; case 'c': s_res << "content"; break; } s_fmt.get(); continue; } s_res << c; } std::cout << s_res.str(); return 0; } As expected, the program should output something like this: Expected output: [Type]Year-Month-Day<Hour:min:sec>:content But at the end of the expected output, there is a strange character: Actual Output:[Type]Year-Month-Day<Hour:min:sec>:content ========================================================^ I checked for a long time and was very troubled to find no credible explanation or concrete solution. Is this a problem caused by encoding? How can I solve this issue?
Let's say that the last character in the stream has just been processed. There's nothing left in the stream. while (s_fmt.good()) { This is perfectly fine. After all, why wouldn't it be? Everything worked swimmingly well, up until now. The entire string has been read. Everything is still good(). The while loop continues to run: char c = (char) s_fmt.get(); Unfortunately, the end of the string has already been reached. This fails, and when the end of the stream has been reached get() returns EOF and sets failbit and eofbit. The shown code does not check that, and blindly converts the returned EOF value to a char. That's your "strange character". And on the next iteration of the while loop, it will discover that things aren't good() any more (the previous get() failed), and bail out. Too late. To fix this it will be necessary to logically rearrange the sequence of events. First you get() the next character, and only then you can check if the stream is good(), and bail out otherwise. Or, alternatively, check for an explicit EOF return value, your preference.
69,869,577
69,870,505
How to dump my class(with stl container) out, make it fast to load next time?
I have a large container class to read file and save some data, it looks like: class MyData { public: void Load(const std::vector<string>& file_paths) { // this is a slow funuction, need to read a lot of files. for (const auto & f : file_paths) { // read file, and save the data in to stl containers } } private: std::vector<double> a; std::unordered_map<string, double>b; // there may be more containers. } everytime when i need to use this class, i need to: MyData mdata; std::vector<std::string> fs; // thousands of files need to read mdata.Load(fs); // very slow but the Mdata not update frequently, Can i dump it out, and use the dumped class, so make it faster? For example: MyData load_dump(const std::string& dump_file_path) { // help needed } const MyData& mdata = load_dump("dump.bin"); // load the dumped file, to speed up Can you help on this?
Sure you can. For vector<double> you can simply use ofstream::write(a.data(), a.size()). For things like maps you need to do some kind of serialization because their internal representation is more complex. You could use http://www.boost.org/libs/serialization/ for a somewhat generic solution or you could write the code yourself.
69,869,648
69,869,680
The last digit of entered value is always 7 or 5 when entering a big number
I'm trying to get the last digit of entered value in C++. Why the output is always 7 or 5 when I enter a big number e.g. 645177858745? #include <iostream> using namespace std; int main() { int a; cout << "Enter a number: "; cin >> a; a = a % 10; cout << "Last Number is " << a; return 0; } Output: Enter a number: 8698184618951 Last Number is 5
The largest value that an int (on most machines) can hold is 2147483647 You enter 8698184618951, which is bigger than 2147483647. Because an int can't hold 8698184618951, extraction will fail but a will now be the max value that it can hold. So a is now 2147483647. You should use a bigger type, like long long instead of int So your code should look like this: #include <iostream> // using namespace std; is bad int main() { long long a; std::cout << "Enter a number: "; std::cin >> a; a = a % 10; std::cout << "Last Number is " << a; return 0; }
69,869,830
69,869,886
Program won't display info in while loop
I am trying to teach myself C++ and I was working on a login system as a way to help better my understanding. I am facing an issue however, the program will not print out anything inside the while loop I made, there are no syntax errors showing when I try to run it and the program doesn't end, it just sits there until I terminate it. Here is the code: #include <iostream> #include <list> int main() { //existing users lists std::list<std::string> Username = {""}; std::list<std::string> Password = {""}; //create account std::string newUsername; std::string newPassword; //login info std::string existingUser; std::string existingPass; //put new info in account lists Username.push_back(newUsername); Password.push_back(newPassword); //creating account input std::cout << "Create a Username: "; std::cin >> newUsername; std::cout << "Create a Password: "; std::cin >> newPassword; //login account input std::cout << "Enter your Username: "; std::cin >> existingUser; std::cout << "Enter your Password: "; std::cin >> existingPass; //check if info is in database while (std::cin >> existingUser && std::find(std::begin(Username), std::end(Username), existingUser) == std::end(Username)) { //if password is in list continue if (std::cin >> existingPass && std::find(std::begin(Password), std::end(Password), existingPass) == std::end(Password)) { //Welcome message std::cout << "Welcome " << existingUser << ", Thank you for logging in !!\n"; break; } //if password isn't in list else (std::cin >> existingPass && std::find(std::begin(Password), std::end(Password), existingPass) != std::end(Password)); { // Try again message std::cout << "Incorrect username or password, Try Again.\n"; std::cout << "Username: "; std::cin >> existingUser; std::cout << "Password: "; std::cin >> existingPass; } } }
#include <iostream> #include <list> int main() { //existing users lists std::list<std::string> Username = {""}; std::list<std::string> Password = {""}; //create account std::string newUsername; std::string newPassword; //login info std::string existingUser; std::string existingPass; //creating account input std::cout << "Create a Username: "; std::cin >> newUsername; std::cout << "Create a Password: "; std::cin >> newPassword; //put new info in account lists Username.push_back(newUsername); Password.push_back(newPassword); //login account input std::cout << "Enter your Username: "; std::cin >> existingUser; std::cout << "Enter your Password: "; std::cin >> existingPass; //check if info is in database while (std::cin >> existingUser && std::find(std::begin(Username), std::end(Username), existingUser) == std::end(Username)) { //if password is in list continue if (std::cin >> existingPass && std::find(std::begin(Password), std::end(Password), existingPass) == std::end(Password)) { //Welcome message std::cout << "Welcome " << existingUser << ", Thank you for logging in !!\n"; break; } //if password isn't in list else (std::cin >> existingPass && std::find(std::begin(Password), std::end(Password), existingPass) != std::end(Password)); { // Try again message std::cout << "Incorrect username or password, Try Again.\n"; std::cout << "Username: "; std::cin >> existingUser; std::cout << "Password: "; std::cin >> existingPass; } } } You are assigning value to the newUsername after pushing them to the list. Try to swap the code as shown above
69,869,838
69,869,921
Convert from UTC date string to Unix timestamp and back
How to convert from string like “2021-11-15 12:10" in UTC to Unix timestamp? Then add two hours to timestamp (like timestamp += 60*60*2). Then convert resulting timestamp to string in the same format in UTC? Using <chrono>, <ctime>, or library, doesn’t really matter.
You could use the I/O manipulators std::get_time and std::put_time. Example: #include <ctime> #include <iomanip> #include <iostream> #include <sstream> int main() { std::istringstream in("2021-11-15 12:10"); // put the date in an istringstream std::tm t{}; t.tm_isdst = -1; // let std::mktime try to figure out if DST is in effect in >> std::get_time(&t, "%Y-%m-%d %H:%M"); // extract it into a std::tm std::time_t timestamp = std::mktime(&t); // get epoch timestamp += 2 * 60 *60; // add 2 hours std::tm utc = *std::gmtime(&timestamp); // make a UTC std::tm std::tm lt = *std::localtime(&timestamp); // make a localtime std::tm // print the results: std::cout << std::put_time(&utc, "%Y-%m-%d %H:%M") << '\n' << std::put_time(&lt, "%Y-%m-%d %H:%M") << '\n'; }
69,870,078
69,875,187
Visual Studio C++ has different comparison results for UINT16 and UINT32
I caught myself checking if the difference between two unsigned numbers was >= 0. I ran a test running Visual Studio 2022 Preview with the following code. In both cases the answer was true. That seems right to me as how could an unsigned number be considered negative? However, when I changed all the types from UINT32 to UINT16 or UINT8, the first comparison returned false. I suppose it is related to the native size. But shouldn't the result be the same regardless of size? (UINT64 seems to behave like UINT32.) #include <Windows.h> #include <iostream> using namespace std; int main() { UINT32 a = 5; UINT32 b = 10; UINT32 c = 0; if ((a - b) > 0) { cout << "\nTrue."; } else { cout << "\nFalse"; } c = a - b; if ((c) > 0) { cout << "\nTrue."; } else { cout << "\nFalse"; } }
The issue arises because, when a and b are UINT16 or UINT8 types, they have ranks less than that of the int type, so, by the "usual arithmetic conversion" rules, they are promoted to int before the a - b operation is performed, and the result of that operation is also of int type. From this draft C++17 Standard (bolding for emphasis is mine): 7.6 Integral promotions     [conv.prom] 1    A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (6.7.4) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int. However, on your platform, the UINT32 type has a rank that is the same as that of int; so, in that case, no promotion is performed, and the result of a - b is a UINT32 (which cannot be negative). If you have the relevant feature enabled (it is by default, IIRC), then the Visual Studio IDE will actually tell you what the issue is, if you declare an auto local variable and initialize it with a - b. The following shows the popup displayed, when hovering over the d variable, for the case when using the UINT32 type: However, when we change the type to UINT16, we see that the a - b expression is, indeed, evaluated as an int:
69,870,289
69,870,347
Am replacing the first occurrence of a string, how can I replace all occurrences?
I have already bulid the basic structure by using the loop + replace,In C++, the str.replace is only to replace single string, however, in some cases, we need to replace all the same string, My code can compile successfully and can output to the screen, but it seems that it does not replace successfully. Thanks in advance here's my code: #include <iostream> #include <fstream> #include <string> int main(void) { // initialize std::ofstream fout; std::ifstream fin; fout.open("cad.dat"); fout << "C is a Computer Programming Language which is used worldwide, Everyone should learn how to use C" << std::endl; fin.open("cad.dat"); std::string words; getline(fin,words); std::cout << words << std::endl; while(1) { std::string::size_type pos(0); if (pos = words.find("C") != std::string::npos && words[pos+1] != ' ') //the later one is used to detect the single word "C" { words.replace(pos, 1, "C++"); } else { break; } } std::cout << words; }
You need to save pos and use it for the following find operations but you currently initialize it to 0 every iteration in the while loop. You could replace the while while loop with this for example: for(std::string::size_type pos = 0; (pos = words.find("C", pos)) != std::string::npos; // start find at pos pos += 1) // skip last found "C" { if(pos + 1 == words.size() || words[pos + 1] == ' ') words.replace(pos, 1, "C++"); } Note: This will replace the C in words ending with C too, for example an acronym like C2C will become C2C++. Also, a sentence ending with C. would not be handled. To handle these cases you could add a check for the character before the found C too and add punctuation to the check. Example: #include <cctype> // isspace, ispunct #include <iostream> #include <string> int main() { std::string words = "C Computer C2C C. I like C, because it's C"; std::cout << words << '\n'; // a lambda to check for space or punctuation characters: auto checker = [](unsigned char ch) { return std::isspace(ch) || std::ispunct(ch); }; for(std::string::size_type pos = 0; (pos = words.find("C", pos)) != std::string::npos; pos += 1) { if( (pos == 0 || checker(words[pos - 1])) && (pos + 1 == words.size() || checker(words[pos + 1])) ) { words.replace(pos, 1, "C++"); } } std::cout << words << '\n'; } Output: C Computer C2C C. I like C, because it's C C++ Computer C2C C++. I like C++, because it's C++
69,870,439
69,870,580
Overloaded function and multiple conversion operators ambiguity in C++, compilers disagree
In the following program struct S provides two conversion operators: in double and in long long int. Then an object of type S is passed to a function f, overloaded for float and double: struct S { operator double() { return 3; } operator long long int() { return 4; } }; void f( double ) {} void f( float ) {} int main() { S s; f( s ); } MSVC compiler accepts the program fine, selecting f( double ) overload. However both GCC and Clang see an ambiguity in the calling of f, demo: https://gcc.godbolt.org/z/5csd5dfYz It seems that MSVC is right here, because the conversion: operator long long int() -> f( float ) is not a promotion. Is it wrong? There is a similar question Overload resolution with multiple functions and multiple conversion operators, but there is a promotion case in it and all compilers agree now, unlike the case in this question.
GCC and Clang are correct. The implicit conversion sequences (user-defined conversion sequences) are indistinguishable. [over.ics.rank]/3: (emphasis mine) Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies: ... (3.3) User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2. The user-defined conversion sequences involves two different user-defined conversion functions (operator double() and operator long long int()), so compilers can't select one; the 2nd standard conversion sequence won't be considered.
69,870,606
69,871,251
`bool n;` `n++;` is invalid but `n=n+1;` or `n=n+3` such things works what's the significance of this?
Code C++17 #include <iostream> int main() { bool n=-1; n++; // Not compiles n=n+3; // This compiles return 0; } Output ISO C++17 does not allow incrementing expression of type bool So I am not understanding the significance of allowing addition but not increment.
As you can see in section 5.3.2 of standard draft N4296, this capability has been deprecated The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated) Please note that the expression n=n+3; is not a unary statement, and it's not something that we could call deprecated. If we call it deprecated, the first problem is that there will be no implicit conversion from bool to int, for example. Since they don't know what you want to do with a not unary statement, it is reasonable that the below code gives you the output 2 for i(Deprecating this is not acceptable) bool b = true; int i = 1; i = i + b; In your example, what happens is implicit conversion from bool->int->bool bool n=-1; n++; // It's a unary statement(so based on the draft, it would not compile) n=n+3; // This compiles (type(n+3) is now int, and then int is converted to bool) Why unary increment is deprecated? I use Galik's comment for completing this answer: With ++b if you promote the bool b to int you end up with an r-value temporary. You can't increment r-values. So in order for ++b to have ever worked it must have been a bool operation, not a promotion to an arithmetic value. Now, that bool operation has been banned. But promotions remain legal so arithmetic that uses promoted values is fine.
69,870,746
69,871,293
arduino on / off NON momentary switch implementation assistance
I am new to programming and Arduino. Board - ESP8266 Nodemcu pinout as below, What I am trying to achieve is send a command based LOW/HIGH value from pin 0. A two leg switch's one leg is connected to D3 (GPIO0 and in program 0) and other to ground. The code I am trying is below, #include<BitsAndDroidsFlightConnector.h> BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector(); const byte exampleButtonA = 0; void setup() { Serial.begin(115200); pinMode(exampleButtonA, INPUT_PULLUP); } void loop() { byte exampleButtonAvalue = digitalRead(exampleButtonA); switch(exampleButtonAvalue) { case LOW: Serial.println("ON IT IS"); break; case HIGH: Serial.println("OFF IT IS"); break; default: Serial.println("error!"); break; } } Issue I am facing is, when I flash this program, Based on physical switch on or off It continually prints either "ON IT IS" or "OFF IT IS" The break is really not happening. I only want it to execute once. I also tried this with if else and face same problem of repeated printing. #include<BitsAndDroidsFlightConnector.h> BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector(); const byte exampleButtonA = 0; void setup() { Serial.begin(115200); pinMode(exampleButtonA, INPUT_PULLUP); } void loop() { if(digitalRead(exampleButtonA) == LOW){ Serial.println("ON"); delay(200); } else { Serial.println("OFF"); delay(200); } } Any assistance?
If you want to see message only once you need to write youre code in setup() section. All code in loop() section is repeated in loop. Replace you code with this: #include<BitsAndDroidsFlightConnector.h> BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector(); const byte exampleButtonA = 0; int exampleButtonAvalue = 0; int saved_exampleButtonAvalue = 0; void setup() { Serial.begin(115200); pinMode(exampleButtonA, INPUT_PULLUP); } void loop() { exampleButtonAvalue = digitalRead(exampleButtonA); if (exampleButtonAvalue != saved_exampleButtonAvalue){ if(exampleButtonAvalue == LOW){ Serial.println("ON"); } else { Serial.println("OFF"); } saved_exampleButtonAvalue = exampleButtonAvalue; } delay(200); }
69,870,759
69,870,793
Creating a 2D Array using dynamic memory allocation in C++
I am trying to implement a 2D array using dynamic memory allocation. Here is my code: #include <iostream> using namespace std; int main() { int r, c; cin >> r >> c; int** p = new int*[r]; for (int i = 0; i < r; i++) { p[i] = new int[c]; //this line here is the marked line } for (int i = 0; i < r; i++) { for (int j = 0;j <c; j++) { cin >> p[i][j]; } } for (int i = 0; i < r; i++) { for (int j = 0;j <c; j++) { cout << p[i][j]<<" "; } } cout<<"\n"; for (int i = 0; i < r; i++) { delete [] p[i]; } delete [] p; return 0; } I then compiled the same code by commenting the marked line in different compilers. VS Code with MinGW (MinGW.org GCC-6.3.0-1) -> Compiled successfully with all the wanted output. Jdoodle and other online compilers (tried in both c++14 and c++17 latest versions) -> The program gives segmentation fault after reading the second input for array element (reads the r, c and first 2 input for the array succesfully). Could someone please explain, IN VS CODE, how am I getting the correct output? Which memory, heap or stack is used if marked line is commented? What are the differences when the marked line is commented and when not commented? And what's the reason of Segmentation fault? Thanks.
In general the program has undefined behavior. In this for loop for (int i = 0; i < r; i++) { p[i] = new int[i + 1]; //this line here is the marked line } in each "row" of the array you allocated i + 1 elements. But in the next for loop (and in subsequent loops) for (int i = 0; i < r; i++) { for (int j = 0;j <c; j++) { cin >> p[i][j]; } } you are trying to access c elements in each row independent on how many elements actually were allocated. So if c is greater than 1 then at least in the first iteration of the loop there is an attempt to access a memory beyond the allocated array. Edit: If you commented this line p[i] = new int[c]; //this line here is the marked line as you wrote I then compiled the same code by commenting the marked line in different compilers. then again the program has undefined behavior. That is you are using uninitialized pointers. It means that anything can occur.
69,870,809
69,870,855
the correct use for auto &i range?
#include <iostream> #include <vector> class UserData { std::string status = "Active"; public: std::string first_name; std::string last_name; std::string get_status() //no colon { return status; } }; int main() { UserData user1; user1.first_name = "LaLaLa"; user1.last_name = "GGGG"; UserData user2; user2.first_name = "HaHaHa"; user2.last_name = "DDDDD"; std::vector<UserData> uservec; uservec.push_back(UserData()); for (auto& i : uservec) { std::cout << i << "\t"; }; } Complier keeps telling me that no operator "<<" matches these operands at line: for (auto& i : uservec) { std::cout << i << "\t"; };. If I create a function and make a for loop, it will be ok, but I don't know why I can't usefor (auto& i : uservec) to read the range ofuservec? Anyone can let me know why, please? Thanks in advance!
The compiler tells you already what is missing. Your class does not have an << operator. So, please add it and all problems are solved. Example: #include <iostream> #include <vector> class UserData { std::string status = "Active"; public: std::string first_name; std::string last_name; std::string get_status() //no colon { return status; } friend std::ostream& operator << (std::ostream& os, const UserData& ud) { return os << ud.first_name << ' ' << ud.last_name; } }; int main() { UserData user1; user1.first_name = "LaLaLa"; user1.last_name = "GGGG"; UserData user2; user2.first_name = "HaHaHa"; user2.last_name = "DDDDD"; std::vector<UserData> uservec; uservec.push_back(user1); uservec.push_back(user2); for (auto& i : uservec) { std::cout << i << '\n'; }; } In the for loop auto& i will return a reference to a UserData element in the vector. Means, in the first loop run "i" will be "user1" and in the next loop run "i" will be "user2". in the output part, you will then have first: std::cout << user1 << '\n'; and then std::cout << user2 << '\n'; At this time the operator << for your UserData will be called, because you tell the compiler to do so. So, you use the operator << for an output stream std::ostream (in this case std::cout) and "user1" of type UserData. Then the compiler knows that it needs to call this overloaded operator.
69,871,195
69,871,372
C++ conditional execution depending on the type
I have a template function that should execute different code, depends on the type. The simplified function looks like this: template<typename T> std::string test(T value) { std::string v; if(std::is_arithmetic<T>()) { v = std::to_string(value); } else { v = std::string(value); } return v; } Usage: test("Hello"); test(123); But I get this error: In instantiation of void test(T) [with T = const char*]: error: no matching function for call to to_string(const char*) note: candidate: std::string std::__cxx11::to_string(int) <near match> to_string(int __val) and the same for the following: to_string(unsigned __val) to_string(long __val) to_string(unsigned long __val) Ok, I understand that in case of, for example const char * the compilation will fail since there is no std::to_string(const char *). but how can I do the code works? Just have to note that in my real code I limit to c++11.
You can apply overloading with SFINAE. E.g. // for arithmetic types template<typename T> typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type test(T value) { std::string v; v = std::to_string(value); return v; } // for non-arithmetic types template<typename T> typename std::enable_if<!std::is_arithmetic<T>::value, std::string>::type test(T value) { std::string v; v = std::string(value); return v; }
69,871,552
69,871,645
strange behavior of C++ downcasting on object
i ran the code below to assign parent portion of objet to child object. but as described inline, c style downcast behaves something unexpected. what happen there? please refer to the comment below. struct A { public: int i{}; A() { std::cout<<"A constructor called\r\n"; } ~A() { std::cout<<"A destructor called\r\n"; } }; struct B : public A { B() { std::cout<<"B constructor called\r\n"; } ~B() { std::cout<<"B destructor called\r\n"; } }; A a{}; B b{}; a.i = 1; (A)b = a; // this code no effect and surprisingly the destructor of A is called. // there was no compiler warning (g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0) std::cout<<a.i<<std::endl; std::cout<<b.i<<std::endl; A& ra = b; ra = a; // A portion of B is initialized as expected std::cout<<b.i<<std::endl; this code prints as A constructor called A constructor called B constructor called A destructor called <-- please note here 1 0 1 B destructor called A destructor called A destructor called
magic is here: (A)b = a; what happend is: call A's copy constructor and create a new [class A object]. it's a temporary object, and it's destoryed after this statement. so print [A destructor called <-- please note here] call A's operator= on the temporary object. it's only effect the temporary object instead of original b;
69,871,605
69,871,701
how to understand const and pointer in C++ expression below?
I am reading application code developed in the IBM RSARTE C++ version. Here is a piece of C++ code: const char * const * av = RTMain::argStrings(); How to understand the left-hand side syntax when there are two const and two *?
const char * const * av = RTMain::argStrings(); is the same as char const * const * av = RTMain::argStrings(); const applies to what's left of const. So, av is a non-const pointer to a const* to const char. The returned pointer, av, is non-const and can be changed. The pointer av is pointing at is const and can not be changed. The char that pointer is pointing at is const and can not be changed.
69,871,723
69,871,835
C++ read data types string int and double using Vector Pair
The problem is that i have to read a file that includes: type count price bread 10 1.2 butter 6 3.5 bread 5 1.3 oil 20 3.3 butter 2 3.1 bread 3 1.1 I have to use Vector Pair to read the file and to multiply the count and price and the output should be : oil 66 butter 27.2 bread 21.8 Any idea would be highly appreciated!
If you only want to use std::pair and std::vector then you could use the following program as a starting point(reference): Version 1: Product names will be repeated #include <iostream> #include <fstream> #include <sstream> #include <vector> int main() { std::ifstream inputFile("input.txt"); //open the file std::string line; std::vector<std::pair<std::string, double>> vec; std::string name; double price, count; if(inputFile) { std::getline(inputFile, line, '\n');//read the first line and discard it while(std::getline(inputFile, line, '\n'))//read the remaining lines { std::istringstream ss(line); ss >> name; //read the name of the product into variable name ss >> count;//read the count of the product into variable count ss >> price;//read the price of the product into variable price vec.push_back(std::make_pair(name, count * price)); } } else { std::cout<<"File cannot be opened"<<std::endl; } inputFile.close(); //lets print out the details for(const std::pair<std::string, double> &elem: vec) { std::cout<< elem.first<< ": "<< elem.second<<std::endl; } return 0; } You can/should instead use a class or struct instead of using a std::pair. The output of the above program can be seen here. The input file is also attached in the above link. The output of the above version 1 is: bread: 12 butter: 21 bread: 6.5 oil: 66 butter: 6.2 bread: 3.3 As you can see in the output of version 1 the names of the product are repeated. If you don't want the repeated names and want the values correpsonding to the repeated keys summed up, check out the below given version 2: Version 2: Product names are not repeated #include <iostream> #include <fstream> #include <sstream> #include <vector> int findKey(const std::vector<std::pair<std::string, double>> &vec, const std::string &key) { int index = 0; for(const std::pair<std::string, double> &myPair: vec) { if(myPair.first == key) { return index; } ++index; } return -1;//this return value means the key was not already in the vector } int main() { std::ifstream inputFile("input.txt"); std::string line; std::vector<std::pair<std::string, double>> vec; std::string name; double price, count; if(inputFile) { std::getline(inputFile, line, '\n'); while(std::getline(inputFile, line, '\n')) { std::istringstream ss(line); ss >> name; ss >> count; ss >> price; int index = findKey(vec, name); if(index == -1) { vec.push_back(std::make_pair(name, count * price)); } else { vec.at(index).second += (count *price); } } } else { std::cout<<"File cannot be opened"<<std::endl; } inputFile.close(); //lets print out the details for(const std::pair<std::string, double> &elem: vec) { std::cout<< elem.first<< ": "<< elem.second<<std::endl; } return 0; } The output of version 2 is bread: 21.8 butter: 27.2 oil: 66 which can be seen here.
69,872,293
69,872,369
Why I am having a weird mistake while trying to read a file from the end to the middle, using fin2.seekg(-2 * sizeof(int), ios::cur); ? no string
Thanks for paying attention to my question. Recently, I've started working with c++ files and now I'm having a couple of questions about reading the file from the end to the middle. My task is to read my two files from the end to the middle and from the beginning to the middle with no arrays and string library used. After that, if the sum is positive, write that to the third file. I would appreciate if you could read my code and explain my mistake. Here's my code down below: void calculatingSum(const char* fname, const char* fname2, const char* fname3) { int size1 = returnSize(fname); int size2 = returnSize(fname2); int number = 0; ifstream fin1; ifstream fin2; ofstream fout3; fout3.open(fname3,ios::binary); if (size2 > size1) { fin1.open(fname,ios::binary); fin2.open(fname2, ios::binary); } else { swap(size1, size2); fin1.open(fname2, ios::binary); fin2.open(fname, ios::binary); } int posMedian1 = size1 / sizeof(int)/2; if (size1 % 2 == 1) { posMedian1 += 2; } int posMedian2 = size2 / sizeof(int) / 2; if (size2 % 2 == 1) { posMedian2 += 2; } fin1.seekg(-1* sizeof(int), ios::end); fin2.seekg(-1 *sizeof(int),ios::end); int a, b; bool flag = false; while (fin2.tellg() >= posMedian2) { fin2.read((char*)&a, sizeof(number)); fin2.seekg(-2 * sizeof(int), ios::cur); if (fin1.tellg() >= posMedian1) { fin1.read((char*)&b, sizeof(number)); fin1.seekg(-2 * sizeof(int), ios::cur); } else { if (flag == false) { flag = true; fin1.seekg(0); } if (fin1.tellg() == posMedian1) break; fin1.read((char*)&b, sizeof(number)); }int c = a + b; cout << "c" << c << endl; if (c > 0) fout3.write((char*)&c, sizeof(number)); fin1.seekg(0); fin2.seekg(0); int d, e; while (fin2.tellg() <= posMedian2) { fin2.read((char*)&d, sizeof(number)); fin2.seekg(2* sizeof(int), ios::cur); if (fin1.tellg() <= posMedian1) { fin1.read((char*)&e, sizeof(number)); fin1.seekg(2* sizeof(int), ios::cur); } else { if (flag == false) { flag = true; fin1.seekg(0,ios::end); } if (fin1.tellg() == posMedian1) break; fin1.read((char*)&e, sizeof(number)); }int f = e + d; cout << "f" << f << endl; if (f > 0) fout3.write((char*)&f, sizeof(number)); } } fin1.close(); fin2.close(); } the main purpose of fin2.seekg(-2 * sizeof(int), ios::cur); it's to read the element from the end,every time looking for the previous element, but i'm getting mistakes,when i'm trying to do this.. the image of an error list
Instead of fin2.seekg(-2 * sizeof(int), ios::cur); do fin2.seekg(-2 * static_cast<ifstream::off_type>(sizeof(int)), ios::cur); where off_type is the offset type of the stream. Otherwise, -2 will be cast to size_t, which is the type of sizeof, and which is unsigned - so the negative value -2 will become a very large value instead. This implicit conversion from int to size_t can be demostrated like this: #include <fstream> #include <iostream> int main() { size_t x = sizeof(int); std::cout << -2 * x << '\n'; // not what you'd expect // ... but this does the right thing: std::cout << -2 * static_cast<std::ifstream::off_type>(x) << '\n'; } Possible output: 18446744073709551608 -8 Since you do this operation a lot, a helper function would simplify it a bit: template<class T> T& seekg(T& stream, long steps, size_t obj_size) { stream.seekg(steps * static_cast<typename T::off_type>(obj_size), std::ios::cur); return stream; } Seeking would then simply be: seekg(fin2, -2, sizeof(int));
69,872,372
69,872,429
Easiest way to combine 3 std::vector into a temporary single std::vector?
I have seen this discussion (Concatenating two std::vectors) but it concerns combining (as in moving) two std::vector arrays. I have three std::vectors and I am using C++17: m_mapHist[m_eHistAssign][strName] m_mapScheduleHist[m_eHistAssign][strName] m_mapScheduleFutureHist[m_eHistAssign][strName] Each vector is of type std::vector<COleDateTime>. I don't want to change these vectors. Instead, I want to combine them (copy I guess) into a temporary single vector, so I can pass just the one vector to another class for processing. At the moment I am doing this manually through iteration: std::vector<COleDateTime> vecAssignmentDate; // Past items from the history database if (m_mapHist[m_eHistAssign].find(strName) != m_mapHist[m_eHistAssign].end()) { for (const auto& historyItemDate : m_mapHist[m_eHistAssign][strName]) { vecAssignmentDate.push_back(historyItemDate); } } // Past items on the active schedule if (m_mapScheduleHist[m_eHistAssign].find(strName) != m_mapScheduleHist[m_eHistAssign].end()) { for (const auto& historyItemDate : m_mapScheduleHist[m_eHistAssign][strName]) { vecAssignmentDate.push_back(historyItemDate); } } // Future items (both on the active schedule and in the history database) if (m_mapScheduleFutureHist[m_eHistAssign].find(strName) != m_mapScheduleFutureHist[m_eHistAssign].end()) { for(const auto &historyItemDate : m_mapScheduleFutureHist[m_eHistAssign][strName]) { vecAssignmentDate.push_back(historyItemDate); } } Is there an easier way to create this temporary vector?
You may use boost::join. Example: std::vector<COleDateTime> v1; std::vector<COleDateTime> v2; std::vector<COleDateTime> v3; std::vector<COleDateTime> result; result = boost::join(boost::join(v1, v2), v3); Since c++17 the standard also have a std::merge util function: std::vector<COleDateTime> v1; std::vector<COleDateTime> v2; std::vector<COleDateTime> v3; std::vector<COleDateTime> result; std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(result)); std::merge(v3.begin(), v3.end(), result.begin(), result.end(), std::back_inserter(result)); Differences between std::merge and std::copy from cplusplus.com/reference/algorithm/merge/ std::merge: Combines the elements in the sorted ranges [first1,last1) and [first2,last2), into a new range beginning at result with all its elements sorted. from cplusplus.com/reference/algorithm/copy/ std::copy: Copies the elements in the range [first,last) into the range beginning at result.. So it depends on what you want to achieve.
69,872,375
69,872,570
C++ STL stack vs forward_list
I have a use case where I need to store some amount of uint16_t variables in no particular order (although the actual type of variables is not relevant). I have decided to turn to the STL to look for a container that best suits my needs. The objects in the container may get taken out of it to be used and put back into the container. Sort of how mechanics might have a single box of screwdrivers instead of putting screwdrivers in their pockets. The container need not perform any sorting on the stored objects and it does not matter what was taken out - the only requirement is to know whether there is anything left in the container. My eyes turn to std::stack and std::forward_list. They both provide O(1) insertion (just alter the front element) and O(1) pop operation (again, just alter the front element and return the previous front). Problem is - I have no idea how they differ from each other conceptually. I know that std::stack is an adapter that just wraps an actual STL container (std::deque by default), thus it might have some unintended overhead, depending on the container being wrapped. I am inclined to use std::forward_list, but I'm looking for input from colleagues. If you have thoughts on the matter, please share them.
TLDR: If you only need to add / remove the last element, use vector or stack. This is the fastest option and has the lowest overhead. Long version: Look up comparisons between linked list and dynamic arrays, for example here: vector vs. list in STL Most of the discussion will be about std::list but the same principles apply to forward_list Short explanation on overhead and operation Vector data structure: 1 dynamically allocated array 1 integer giving the number of used elements 1 integer giving the number of available elements (preallocated size) (footnote: Actually not counters but pointers. Let's not worry about that). Appending an element to the end of the vector: Check if there is space available. If not, reallocate an array twice the current size. Because the vector grows to twice its size (exponential growth), this is very rare and does not affect performance much. Copy element to the index in the array Increment the counter Removing an element from the end of the vector: Decrement the counter. That's it (unless you have destructors) Memory overhead: 24 bytes for the pointer and counters. 8 byte for the dynamic allocation of the array. Worst case 50% unused elements. Forward list data structure: 1 pointer to first element 1 pointer to the last element In each element, 1 pointer to the next element Forward list insertion: Dynamically allocate a new element (expensive) Set pointers (cheap) Remove first element: Change pointer from first to second element Deallocate the element (expensive) The computational overhead of the dynamic allocation is much higher than anything vector uses. Memory overhead: 16 bytes for the two pointers in the base structure Per element 8 byte for the dynamic allocation, 8 byte for the pointer to the next element, 6 byte padding because allocators only work with multiples of 8 byte For every 2 bytes used payload, there are 22 byte overhead compared to the 2-for-2 worst case in vector!
69,872,689
69,872,763
I want to sort an array of structures using templatized qsort
I have an array containing pointers to objects. Each object has a data member called name of type string. I want to sort it using the templatized qsort function. Note again that each element in the array is a pointer to an object. However, I get the error: error C2227: left of '->name' must point to class/struct/union/generic type at this line: return strcmp(a->name, b->name); on compile time. Why I get this error? Here is the full code (I work with Visual Studio 2019): #include <cstdlib> #include <stdio.h> #include <string.h> //---------------------------------------------------------------------- class my_type { public: char name[10]; my_type(char* source) { strcpy(name, source); // assume data are valid } }; //---------------------------------------------------------------------- template <typename a_type> int compare(const void* pa, const void* pb) { a_type* a = (*(a_type**)pa); a_type* b = (*(a_type**)pb); return strcmp(a->name, b->name); } //---------------------------------------------------------------------- int main() { my_type**a; int n = 5; a = new my_type * [n]; // allocate the array. for (int i = 0; i < n; i++) { char buf[100]; _itoa(i, buf, 10); a[i] = new my_type(buf); // allocate each element of the array. } qsort(a, n - 1, sizeof(a[0]), compare<my_type*>); // sort them for (int i = 0; i < n; i++)// print the sorted elements printf("%s ", a[i]->name); for (int i = 0; i < n; i++) delete a[i]; // delete each element delete[] a; // delete array getchar(); } //----------------------------------------------------------------------
name is a c string. Is there any reason why you do not use c++ strings from stdlib ? You won't be able to compile a code with a template ? Or std::sort ? Anyway, the problem is that when you call the template, you define the type as a pointer. You end up with a pointer to pointer, which has no field "name".
69,872,960
69,872,984
Why is my method for finding all divisors for two numbers isn't working
So I made a while loop for finding all divisors for given numbers and it's the following int a,b; int temp =0; cout << "Enter the first number : "; cin >> a; cout << "Enter the second number : "; cin >> b; int smallestNum = a<b?a:b; while(true) { temp++; if(a%temp == 0 && b%temp == 0) cout << temp << ", "; if (temp == smallestNum) break; } cout << "are all the divisors for both numbers"; and it worked like expected but when i tried to do the same in a for loop it didn't go as planned int a,b; int temp; cout << "Enter the first number : "; cin >> a; cout << "Enter the second number : "; cin >> b; temp = a<b?a:b; for (int i; i == temp; i++) { if(a%i==0 && b%i==0) cout << i << ", "; } cout << "are all the divisors for both numbers"; I can't even find the problem in my code to fix it, how can I fix it????
for loop will iterate as long as condition is true, your condition is i == temp which is (in general) false, you should change it to i != temp