question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,285,611
71,286,009
Working with threads in c/c++, across many different platforms
In my understanding, if you use C, then you are bound to use POSIX Threads. These are OS dependent, and if you use Linux, you have to use <pthread.h>, while if you use Windows, you have to go with <windows.h>. These things are transferable to C++ as well. However, if you use C++ and specifically a version after C++11, then you can skip the POSIX threads method, and use #include <thread> and you are off to go. Is this a correct understanding? Is there something i miss?
Since C11, there is a support of threads directly in the standard C language (using threads.h). Note that mainstream compilers (Clang, GCC, ICC, MSVC) support OpenMP which can be used to parallelize computing codes using multiple threads (typically numerical codes). OpenMP is available in both C and C++ (as well as FORTRAN). Note also that PThreads is supported on Windows as a wrapping library. In pre-C++11, note that there is many portable threading libraries. One famous library is the Intel Threading Building Blocks (aka TBB). Related question: Multi-Threading support in c11
71,285,757
71,285,881
Why isn't my brute-force string match algorithm display an output?
Here is the source code of the bfSM algorithm. The program should display the starting index of the part where a total match with the pattern is found, or -1 if there are no matches in the given text. I tried including all the libraries i've used thus far while programming but when I debug the program nothing is displayed on the console except for "(process 15936) exited with code 0". I'm not sure what exactly am I missing here an would appreciate some help. #include <iostream> #include <string> #include <vector> #include <algorithm> #include <iomanip> #include<stdio.h> #include<string.h> using namespace std; int bruteForceSM(string p, string t) { for (int i = 0; i < (t.size() - p.size()); i++) { int j = 0; while(j < p.size() && p[j] == t[i + j]) { j++; } if (j == p.size()) { return i; } } return -1; } int main(){ string text = "sally sells seashells by the seashore"; string pattern = "shell"; bruteForceSM(pattern, text); return 0; }
You never print the result, which is the reason you cannot see any result. In the main function, replace bruteForceSM(pattern, text); with cout << "Index at which pattern is found: " << bruteForceSM(pattern, text) << endl; This will print Index at which pattern is found: 15 As an additional general advice: never use using namespace std; (see Why is "using namespace std;" considered bad practice? for more information on why).
71,286,002
71,286,186
std::ranges::remove still not suported / broken on clang trunk when using libstdc++?
Works fine on gcc trunk, but not on clang trunk, both with libstd++. Or am I missing something exceedingly obvious? Godbolt #include <algorithm> #include <iostream> #include <ostream> #include <vector> std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) { for (auto&& e: v) os << e << " "; return os; } int main() { auto ints = std::vector<int>{1,2,3,4,5}; std::cout << ints << "\n"; auto [first, last] = std::ranges::remove(ints, 3); ints.erase(first, last); std::cout << ints << "\n"; } gcc is clean. clang gives a WALL OF ERRORS, complaining about missing "__begin". UPDATE: If I use -stdlib=libc++ then clang says "never heard of it", so I guess they are just not there yet. new Godbolt
This seems to be a Clang bug, affecting ranges when using libstdc++, see this issue with the underlying cause which is still open and other issues linked to it as duplicates with examples how it affects ranges with libstdc++. There seems to have been some work on it about two weeks ago. In libc++ std::ranges::remove does not seem to be implemented yet as you noticed and as stated on its status page for ranges implementation.
71,286,053
71,286,155
google::protobuf::io::GzipOutputStream does not write anything if the file handle is closed at the end
The following code writes to file as expected int ofd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777); google::protobuf::io::FileOutputStream outp(ofd); google::protobuf::io::GzipOutputStream fout(&outp); MyMessage msg; ConstructMessage(&msg); CHECK(google::protobuf::util::SerializeDelimitedToZeroCopyStream(msg, &fout)); fout.Close(); // close(ofd); However if I uncomment the last line // close(ofd);, I get empty file. Why is that? Also if I skip using the Gzip wrapper, the last line causes no problem. Does this look like a bug?
You should close things in the opposite order of opening: int ofd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777); google::protobuf::io::FileOutputStream outp(ofd); google::protobuf::io::GzipOutputStream fout(&outp); ... fout.Close(); outp.Close(); close(ofd); With the missing outp.Close();, some data may remain buffered in it. The destructor will eventually flush it out, but at that point the ofd is already closed so there is nothing to write to.
71,286,460
71,286,709
C++ implement class constructs instance of another classes depending on string it consumes
I need to implement one abstract class, three its concrete subclasses, class which goal to create one of this three classes instances and last class executor of three classes. Requirements are c++98, and not to use if/elseif/else to construct class instance, like i did in a Maker class method make Form. What mechanism i need to avoid if / elseif / else? For example: test.h #ifndef TEST_H #define TEST_H #include <iostream> class Executor { private: const std::string name; public: Executor(const std::string &name = "") {}; const std::string getname() const {return name;} }; class BForm { private: const std::string _name; public: BForm(const std::string &name = "") : _name(name) {}; virtual ~BForm() {}; virtual void execute(const Executor &src) = 0; const std::string getname() {return _name;} virtual const std::string gettarget() = 0; }; class Form1 : public BForm{ private: std::string _target; public: Form1(const std::string &target = "") : BForm("form1"), _target(target) {}; virtual ~Form1() {}; virtual void execute(const Executor &src) { std::cout << src.getname() << " exec form1 target:" << _target << std::endl; } virtual const std::string gettarget() {return _target;} }; class Form2 : public BForm { private: std::string _target; public: Form2(const std::string &target = "") : BForm("form2"), _target(target) {}; virtual ~Form2() {}; virtual void execute(const Executor &src) { std::cout << src.getname() << " exec form2 target:" << _target << std::endl; }; virtual const std::string gettarget() {return _target;} }; class Form3 : public BForm { private: std::string _target; public: Form3(const std::string &target = "") : BForm("form3"), _target(target) {}; virtual ~Form3() {}; virtual void execute(const Executor &src) { std::cout << src.getname() << " exec form3 target:" << _target << std::endl; }; virtual const std::string gettarget() {return _target;} }; class Maker { public: BForm *makeForm(const std::string &name, const std::string &target) { /* need to avoid */ if (name == "form1") return new Form1(target); else if (name == "form2") return new Form2(target); else return new Form3(target); } }; #endif main.cpp #include "test.h" int main() { Maker maker; BForm *form; Executor exec("executor"); form = maker.makeForm("form1", "A"); std::cout << form->getname() << " " << form->gettarget() << std::endl; form->execute(exec); delete form; return (0); }
You could typedef a pointer to function and then use a map from string to this type (pointer to function). And then use your parameter with indexer syntax to access the correct pointer to function. Here is an example: #include <iostream> #include <map> // The class definitions with a virtual function hello() common to all class Base { public: virtual void hello() = 0; }; class Derived1 : public Base { public: void hello() { std::cout << "Derived1"; } }; class Derived2 : public Base { public: void hello() { std::cout << "Derived2"; } }; // The object making functions Base* Maker1() { return new Derived1; } Base* Maker2() { return new Derived2; } int main() { // In C++98, without auto, it's worthwhile to typedef complicated types. // The first one is a function type returning a pointer to Base... typedef Base* MakerT(); // ... the second one is a map type projecting strings to such function pointers typedef std::map<std::string, MakerT*> StrToMakerT; /// The actual map projecting strings to maker function pointers StrToMakerT strToMaker; // Fill the map strToMaker["D1"] = &Maker1; strToMaker["D2"] = &Maker2; // user input std::string choice; // as long as output works, input works, and the user didn't say "Q": while (std::cout << "Please input 'D1' or 'D2' or 'Q' for quit: " && std::cin >> choice && choice != "Q") { // Prevent adding new entries to the map foir unknown strings if (strToMaker.find(choice) != strToMaker.end()) { // Simply look the function up again, the iterator type is too // cumbersome to write in C++98 Base* b = (*strToMaker[choice])(); b->hello(); std::cout << '\n'; delete b; } else { std::cout << "Didn't find your choice, try again.\n"; } } std::cout << "Thank you, good bye\n"; }
71,286,510
71,286,536
Why do we return *this in asignment operator and generally (and not &this) when we want to return a reference to the object?
I'm learning C++ and pointers and I thought I understood pointers until I saw this. On one side the asterix(*) operator is dereferecing, which means it returns the value in the address the value is pointing to, and that the ampersand (&) operator is the opposite, and returns the address of where the value is stored in memory. Reading now about assignment overloading, it says "we return *this because we want to return a reference to the object". Though from what I read *this actually returns the value of this, and actually &this logically should be returned if we want to return a reference to the object. How does this add up? I guess I'm missing something here because I didn't find this question asked elsewhere, but the explanation seems like the complete opposite of what should be, regarding the logic of * to dereference, & get a reference. For example here: struct A { A& operator=(const A&) { cout << "A::operator=(const A&)" << endl; return *this; } };
this is a pointer that keeps the address of the current object. So dereferencing the pointer like *this you will get the lvalue of the current object itself. And the return type of the copy assignment operator of the presented class is A&. So returning the expression *this you are returning a reference to the current object. According to the C++ 17 Standard (8.1.2 This) 1 The keyword this names a pointer to the object for which a non-static member function (12.2.2.1) is invoked or a non-static data member’s initializer (12.2) is evaluated. Consider the following code snippet as an simplified example. int x = 10; int *this_x = &x; Now to return a reference to the object you need to use the expression *this_x as for example std::cout << *this_x << '\n';
71,286,633
71,286,756
I need to print element of a struct that is itself in a map in c++
I have in c++ an include like that: struct my_struct { time_t time; double a, b, c, d; } typedef std::map<std::string, std::vector<my_struct> Data; In my code (for debugging issue) I want to print some of the values in Data for specific key. I don't remember the syntax and keep having errors. Here the kind of syntax I tried without success: for (const auto& [key, value] : inputData) { if (key=="mytest") { std::cout << '[' << key << "] = " << value.a << endl; } } I also tried: for(const auto& elem : inputData) { if (elem.first=="mytest") { cout<<elem.second.a>>endl; } } Thanks for your help
Look at the following line properly: typedef std::map<std::string, std::vector<my_struct> Data; As you can see the second element of the std::map is a list of my_struct. Now here: for (const auto& [key, value] : inputData) { if (key == "mytest") { std::cout << '[' << key << "] = " << value.a << std::endl; } } ..value.a makes no sense because std::vector<my_struct>::a is not a thing. So replace value.a with: value[0].a; // Replace 0 with the index of element you want to access Or print every element in value: for (const auto& [key, value] : inputData) { if (key == "mytest") { std::cout << '[' << key << "] = "; for (auto& i : value) { std::cout << i.a << " : "; } std::cout << std::endl; } } You can use any one of the 2 options as per your choice.
71,286,704
71,287,103
Invalid use of incomplete type for named template argument
I have the following class template: template<typename T=class idType, typename U=class uType> class f { std::unordered_map<T::Type, float> id_; // error! } I am using the dependency injection framework boost::di and I therefore need to name my template argument to be able to bind those templates to actual types. I am surprised that I get an error when I try to declare a hashmap using the underlying type of the template idType. Yes, I would imagine an error if the template argument I use did not have defined a Type, but I certainly do in my case. They are defined after I include the file containing the example above. The error is: error: invalid use of incomplete type ‘class idType’ 14 | std::unordered_map<typename T::Type, float> rpc; | ^~~ example.hpp:9:29: note: forward declaration of ‘class idType’ 9 | template<typename T = class idType, typename U = class uType>
They are defined after I include the file containing the example above Yeah, that's not gonna work. While templates and class definitions do have some specific leeway in that they can sometimes reference things declared/defined after them, these are very specific cases. The bodies of class member functions can reference other elements of their own class that have not at that point been declared (essentially, the compiler moves the member function definition to just after the class definition). And templates can reference as-of-yet undefined names... so long as those names are dependent on a template parameter. The code you've presented uses idType, which is not a template parameter name. The parameter is T; idType is merely the default value of that parameter. If the user provides a different type, your use of idType will ignore it. Therefore, the compiler must search for idType at the point of use within the template, not at instantiation time. Indeed, the fact that you use idType as a default value at all also imposes the requirement that type needs to exist at the location of the template definition. You named it, after all; it needs to exist if you name it.
71,287,571
71,287,618
Access violation when writing to location inside of 2d array
Hi im doing some assignment that has to do with reading information from a file to write to a 2d int array. When accessing the index of the array to change the data at the point, it throws an exception that says access violation. The arrays has been pre declared in the global scope. int ImportMapDataFromFile(const char *FileName) { FILE* fp; // file stream fopen_s(&fp,FileName, "r"); // opens the file stream according to the file name provided. if (fp) { fscanf_s(fp, "Width %i\n", &BINARY_MAP_WIDTH); // scans for the width fscanf_s(fp, "Height %i\n", &BINARY_MAP_HEIGHT);// scans for the height MapData = new int* [BINARY_MAP_HEIGHT]; // allocates the rows of the map data array BinaryCollisionArray = new int* [BINARY_MAP_HEIGHT];// allocates the rows of the binary collision data array // This for loop initializes and allocates memory for the for (int i{0}; i < BINARY_MAP_HEIGHT; i++) { MapData[i] = new int[BINARY_MAP_WIDTH]; // allocates the columns of the map data array BinaryCollisionArray[i] = new int[BINARY_MAP_WIDTH];// allocates the columns of the binary collision data array } // Nested for loop to initialize the binary mapping and the collision data //from the input file that is provided. for (int row{0}; row < BINARY_MAP_HEIGHT; row++) { for (int col{0}; col < BINARY_MAP_WIDTH; col++) { int in; fscanf_s(fp,"%i", &in);// scans the file for the data for the allocated space in the array MapData[col][row] = in; // **access violation happens here** (in > 1) ? BinaryCollisionArray[col][row] = 0 : // inputs the binary collision data BinaryCollisionArray[col][row] = in; } } fclose(fp); // close the file stream return 1; // returns if successful } else return 0; // returns if unsuccessful }
MapData[col][row] If you go back and review how this matrix was allocated, it looks like the indexes are reversed. The first dimension is the row, the 2nd one is the column. Either that, or change the dimensions' allocations: MapData = new int* [BINARY_MAP_HEIGHT]; // allocates the rows of the map data array These look like rows to me, and it's the 1st dimension.
71,288,178
71,288,211
Unqualified name lookup does not look in local namespace after using declaration
namespace A { int overloaded_f(float some_float); enum class Enum { Value }; } namespace B { int overloaded_f(A::Enum some_enum); int f(A::Enum some_enum){ using A::overloaded_f; // using B::overloaded_f; // return B::overloaded_f(some_enum) + overloaded_f(0.0f); return overloaded_f(some_enum) + overloaded_f(0.0f); /* error: cannot convert 'A::Enum' to 'float' 14 | return overloaded_f(some_enum) + overloaded_f(0.0f); | ^~~~~~~~~ | | | A::Enum */ } } int main(){ A::Enum a = A::Enum::Value; return B::f(a); } Link to Godbolt. Uncommenting the (//) code lines would remove the error. From basic.lookup.unqual: §6.4.1 Unqualified name lookup [basic.lookup.unqual] In all the cases listed in [basic.lookup.unqual], the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-formed. The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see [namespace.udir]. For the purpose of the unqualified name lookup rules described in [basic.lookup.unqual], the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace. Does the code snippet fail to compile because name lookup ends as soon as a declaration is found for the name?
Does the code snippet fail to compile because name lookup ends as soon as a declaration is found for the name? You're correct. The lookup of overloaded_f in the expression overloaded_f(some_enum) has two components: The unqualified component: this stops searching outward as soon as it finds a declaration, which in this case means it stops at using A::overloaded_f. The argument-dependent component: this only looks inside the namespace associated with its argument type. In this case, the associated namespace is A (the namespace in which the enum type is declared). It does not find anything that is inside namespace B.
71,288,948
71,367,355
Using VCPKG with cmake and Qt 6 for Windows ARM64
Qt 6.2 introduced Windows on Arm support (https://bugreports.qt.io/browse/QTBUG-85820). I tried to create a new cmake project set up using Qt Creator and everything works fine. Then I wanted to add some external packages to my project using vcpkg. The standard way to use vcpkg with cmake is using the CMAKE_TOOLCHAIN_FILE variable (as mentioned here. However, when I clicked on project settings in Qt Creator (Projects > Build) it seems that Qt Creator has already set up the CMAKE_TOOLCHAIN_FILE variable to another file Presumably, this is done so that it is possible to cross-compile an ARM64 binary from a x64 machine. However, this prevents me from setting up vcpkg within my Qt project. Is there a way to get around this issue? Does CMake support multiple toolchain files or is there an alternative setup for my scenario?
I found out that VCPKG provides a way to achieve this as explained here: To use an external toolchain file with a project using vcpkg, you can set the cmake variable VCPKG_CHAINLOAD_TOOLCHAIN_FILE on the configure line: cmake ../my/project \ -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake \ -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=../my/project/compiler-settings-toolchain.cmake So in my case, I can just qt toolchain file using VCPKG_CHAINLOAD_TOOLCHAIN_FILE option.
71,289,256
71,289,370
no known conversion for argument 1 from 'int' to 'gnu_cxx::normal_iterator<int*, std::vector<int>>&&'. I'm unable to find a way to get my code working
I am trying to carry out a binary search to find the index of a specific element within the vector. I tried getting the first and last element and passing them to the variable high and low. I am getting some sort of conversion error. The error is below inside the BinarySearchVector funtion. #include <iostream> #include <vector> #include <algorithm> using namespace std; int limit=10; vector <int> elements; void AddValueToVector(){ cout<<"Hello World:"<<endl; for (int i = 0; i < limit; i++) { int a; cin>>a; elements.push_back(a); } } void printContents(){ cout<<"Vector elements:"<<endl; for (int j = 0; j < limit; j++) { cout<<elements[j]<<endl; } } int binarySearchVector(vector<int>&elements,int searchval){ sort(elements.begin(),elements.end()); auto low= elements.begin(); auto high= elements.end(); while (low <= high) { int mid = low + (high - low) / 2; if (elements[mid] == searchval) return mid; if (elements[mid] < searchval) low = mid + 1; else high = mid - 1; } return -1; } void search(){ int searchval; cout<<"Enter value to search:"<<endl; cin>>searchval; int result= binarySearchVector(elements,searchval); if (result==-1) { cout<<"Not Found"<<endl; }else{ cout<<"Element is found at index"<<result<<endl; } } int main() { AddValueToVector(); printContents(); search(); return 0; } Any recommendations will be greatly appreciated.
Since your binarySearchVector function is supposed to return the index of the found element (not an iterator) you should probably not use begin() and end() (that return iterators, not indices). Example: int binarySearchVector(std::vector<int>& elements, int searchval) { std::sort(elements.begin(), elements.end()); int low = 0; // index of first element int high = elements.size() - 1; // index of last element while (low <= high) { int mid = low + (high - low) / 2; if (elements[mid] < searchval) low = mid + 1; else if (elements[mid] > searchval) high = mid - 1; else return mid; } return -1; }
71,289,454
71,289,476
GCC throws "pure virtual method called", but not when optimizations are on
I have an abstract base class, ITracer, with pure virtual method logMessage. ITracer also has a virtual destructor. I have a derived class, NullTracer, which implements logMessage. I have a class, TestClass, whose constructor optionally takes a const-ref ITracer. If no ITracer is provided, a NullTracer is instantiated. TestClass has a method, test, which calls its ITracer's logMessage. With GCC 11.2, "pure virtual method called" is thrown and "hello" is printed to stdout. With GCC 11.2 and -O2, no exceptions are thrown and both "hello" and "test" are printed to stdout. First, in the non-optimized case, what am I doing wrong? I don't understand which pure virtual functions I calling, NullTracer clearly has an implementation. Second, in the optimized case, why is there no longer an exception and why does it execute the way I am expecting it to? Edit: Can't believed I missed the dangling reference. Thanks #include <iostream> class ITracer { public: virtual ~ITracer() = default; virtual void logMessage() const = 0; }; class NullTracer : public ITracer { public: void logMessage() const override { std::cout << "test" << std::endl; }; }; class TestClass { public: TestClass(const ITracer& tracer = NullTracer()) : m_tracer(tracer) {} void test() { std::cout << "hello" << std::endl; m_tracer.logMessage(); } private: const ITracer& m_tracer; }; int main() { TestClass test; test.test(); } https://godbolt.org/z/br6WxacKo
When the TestClass constructor creates a temporary NullTracer object, the const-reference parameter tracer ensures that the object lives only for the lifetime of the constructor call. When the constructor exits, the temporary object gets destroyed. Even though the m_tracer class member is also a const-reference, it DOES NOT extend the lifetime of the temporary NullTracer object any further. And so, you end up calling logMessage() via a dangling reference to an invalid object, which is undefined behavior. You need to explicitly extend the lifetime of the NullTracer object, either by: copying the object by value into another class member, and then set m_tracer to refer to that member instead set m_tracer to refer to a static NullTracer object use pointers instead of references, and then create the NullTracer object dynamically
71,289,523
71,289,560
How can I alloc member value with "Get" function?
Here's a simple code. class Sub { ... public: Sub() { ... } } class Main { private: Sub* m_pSub public: Main() { // I don't want construct "Sub" here m_pSub = nullptr; } Sub* GetSub() { return m_pSub; } } ///////////////////// // in source Main* pMain; pMain->GetSub() = new Sub() Of course, pMain->GetSub() = new Sub() does not work because the left value of '=' in the above code must be a correctable value. Therefore, please teach me various ways to implement similarly (which can be used as short as possible). Thank you !
The simplest way to make your code work is to have GetSub() return a reference, eg: class Main { private: Sub* m_pSub = nullptr; public: Main() = default; Sub*& GetSub() { return m_pSub; } }; However, this isn't very good class design. Another option is to have GetSub() create the object on its first call, eg: class Main { private: Sub* m_pSub = nullptr; public: Main() = default; Sub* GetSub() { if (!m_pSub) m_pSub = new Sub; return m_pSub; } }; Otherwise, use an explicit setter method, eg: class Main { private: Sub* m_pSub = nullptr; public: Main() = default; Sub* GetSub() { return m_pSub; } void SetSub(Sub* newSub) { m_pSub = new Sub; } }; ... pMain->SetSub(new Sub); Either way, you really should be using smart pointers, either std::unique_ptr or std::shared_ptr, to make it clear who owns the Sub object and is responsible for destroying it. A raw pointer does not convey that information.
71,289,536
71,297,979
Add or modify a nullptr Vector from a partially filled flatbuffer?
This builds off of the monster schema example. If I partially fill a flatbuffer such as in the official test.cpp. Relevant lines also copied below // Create a mostly empty FlatBuffer. flatbuffers::FlatBufferBuilder nested_builder; auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0, nested_builder.CreateString("NestedMonster")); FinishMonsterBuffer(nested_builder, nmloc); How can I modify the inventory part of the schema from nested_builder after already calling FinishMonsterBuffer(nested_builder, nmloc);? Things I've tried (related to test.cpp): std::string bfbsfile; bool found = flatbuffers::LoadFile( "./monster_schema.bfbs", true, &bfbsfile ); const reflection::Schema& schema = *reflection::GetSchema( bfbsfile.c_str() ); auto root_table = schema.root_table(); auto fields = root_table->fields(); // The above works fine I've tested the fields and verified the schema. // I'm unsure of the code below. // First we put the FlatBuffer inside an std::vector. std::vector<uint8_t> resizingbuf( nested_builder.GetBufferPointer(), nested_builder.GetBufferPointer() + nested_builder.GetSize()); // Get the root. // This time we wrap the result from GetAnyRoot in a smartpointer that // will keep rroot valid as resizingbuf resizes. auto rroot = flatbuffers::piv(flatbuffers::GetAnyRoot(resizingbuf.data()), resizingbuf); // Now lets try to extend a vector by 100 elements (0 -> 110). auto &inventory_field = *fields->LookupByKey("inventory"); // I don't think this works either if it doesn't already exist. auto rinventory = flatbuffers::piv( flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf); // This line silently fails probably because *rinventory is probably a nullptr // but I don't know how to set it after having already // called FinishMonsterBuffer(nested_builder, nmloc);. flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory, &resizingbuf); // Try to print it but prints nothing. // printf("%hhu", rinventory->Get(10)); Apologies in advance for the title I'm not quite sure how to phrase the exact problem or question. Let me know if more context is needed or part of the question doesn't make sense.
Disclaimer: Flatbuffers doesn't generally allow mutating a vector after the buffer has been finished. However, we do have some advanced APIs in the reflection API for doing such mutations, but are generally slow and not recommended. We don't support the case of resizing a null vector. We store null within the vtable and there is no data/size information in the buffer related to a null vector. Therefore there is nothing to resize. You may try inserting a empty vector instead, as that should place the necessary data/size information into the buffer that can be later resized.
71,289,600
71,289,712
C++ 20 concept to accept a random access container but reject std::list
std::vector is known to meet the requirement of a RandomAccessContainer, so using the [] operator is constant time. However, std::list only meets the weaker requirements of a Container and ReversibleContainer, and hence retrieving an element is O(N), moreover the [] operator doesn't exist. I would like to constrain a template so that I can get a nice compile-time error whenever the [] operator doesn't exist or is not O(1). How can I achieve this? Currently, on g++ 11.2.0, I cannot get a clean error message when instantiating the following templates with a std::list: template<typename RandomAccessContainer> void foo(RandomAccessContainer const & x); template<typename ContiguousContainer> void foo(ContiguousContainer const & x); template<typename T> requires ContiguousContainer<T> void foo(T const & x);
You could start with a type trait to check if the type supports subscripting: template<class T> struct has_subscript { static std::false_type test(...); template<class U> static auto test(const U& t) -> decltype(t[0], std::true_type{}); static constexpr bool value = decltype(test(std::declval<T>()))::value; }; template <class T> inline constexpr bool has_subscript_v = has_subscript<T>::value; Then add concepts: template <class T> concept subscriptable = has_subscript_v<T>; template <class T> concept subscript_and_cont_iterator = std::contiguous_iterator<decltype(std::begin(std::declval<T>()))> && subscriptable<T>; Demo If you don't need the type trait, just make subscriptable using a requires clause: template <class T> concept subscriptable = requires(const T& c) { c[0]; }; Demo
71,289,825
71,289,930
How to count characters in a C_String in C++?
I'm a new Computer Science student, and I have a homework question that is as follows: Write a Function that passes in a C-String and using a pointer determine the number of chars in the string. Here is my code: #include <iostream> #include <string.h> using namespace std; const int SIZE = 40; int function(const char* , int, int); int main() { char thing[SIZE]; int chars = 0; cout << "enter string. max " << SIZE - 1 << " characters" << endl; cin.getline(thing, SIZE); int y = function(thing, chars, SIZE); cout << y; } int function(const char *ptr, int a, int b){ a = 0; for (int i = 0; i < b; i++){ while (*ptr != '\0'){ a++; } } return a; }
First of all welcome to stackoverflow ye0123! I think you are trying to rewrite the strlen() function here. Try giving the following link a look Find the size of a string pointed by a pointer. The short answer is that you can use the strlen() function to find the length of your string. The code for your function will look something like this: int function(const char *ptr) { size_t length = strlen(ptr); return length; } You should also only need this function and main. Edit: Maybe I misunderstood your question and you are supposed to reinvent strlen() after all. In that case, you can do it like so: unsigned int my_strlen(const char *p) { unsigned int count = 0; while(*p != '\0') { count++; p++; } return count; } Here I am comparing *p from '\0' as '\0' is the null termination character. This was taken from https://overiq.com/c-programming-101/the-strlen-function-in-c/
71,289,889
71,289,926
Simplifying a code snippet - vector rotation in a circle
Given the following code pattern, wherein I am trying to state a vector direction in increments of 45 degrees over the integers int x and int y, inside of a circle positioned at the origin // x == 0 && y == 0 case is already taken cared of if(x > 1) { if(y == 0) { // horizontal right m_rotation = 0; }else if(y < 1) { // diagonal down right m_rotation = 315; } else if(y > 1) { // diagonal up right m_rotation = 45; } } else if(x == 0) { if(y < 1) { // vertical down m_rotation = 270; } else if(y > 1) { // vertical up m_rotation = 90; } } else if(x < 1){ if(y == 0) { // horizontal left m_rotation = 180; }else if(y < 1) { // diagonal down left m_rotation = 225; } else if(y > 1) { // diagonal up left m_rotation = 135; } } I am looking for an elegant way to make this compact. I know there's the spaceship operator <=>, but I need to restrict myself to C++17. Things I have tried Nesting ternary operators with m_rotation = x > 1? (y < 1? (y == 0? 0: 315): 45): (x == 0? (y < 1? 270: 90): (y < 1? (y == 0? 180: 225): 135));, but this looks weird I tried putting the x == 0 case inside x < 1 case and transform the later into else, but that does not simplify enough the code Using absolute values to compare x and y, but I quickly get lost Nothing else really, I don't know what else to try
Something like constexpr int rotation[3][3] = { {225, 180, 135}, {270, 0, 90}, {315, 0, 45}, }; if (x != 0 || y != 0) // if (!(x == 0 && y == 0)) m_rotation = rotation[1 + sign(x)][1 + sign(y)];
71,290,175
71,290,241
Combine multiple boost::asio::const_buffer into a single buffer
My program receives data in the form of std::vector<boost::asio::const_buffer> buf_vect. I need to combine the const_buffer in the vector into a single buffer which will then be converted to a std::string for further processing. First attempt: size_t total_size = 0; for (auto e : buf_vect) { total_size += e.size(); } char* char_buf = new char[total_size]; for (auto e : buf_vect) { strncpy(char_buf, static_cast<const char*>(e.data()), e.size()); } std::string data(char_buf, total_size); delete char_buf; // process data string This attempt yields nonsense in the data string. Is this the correct approach or am I totally misunderstanding the behavior of buffers...?
std::vector<boost::asio::const_buffer> buf_vect That satisfies the criteria for a ConstBufferSequence [I need to combine the const_buffer in the vector into a single buffer which will then be converted to] a std::string [for further processing] Let's skip the middle man? std::string const for_further_processing(asio::buffers_begin(buf_vect), asio::buffers_end(buf_vect)); Live Demo #include <boost/asio.hpp> #include <iomanip> #include <iostream> #include <string> namespace asio = boost::asio; int main() { float f[]{42057036, 1.9603e-19, 1.9348831e-19, 1.7440063e+28, 10268.8545, 10.027938, 2.7560551e+12, 10265.352, 9.592293e-39}; int ints[]{1819043144, 1867980911, 174353522}; // "Hello World\n" char arr[]{" aaaaaa bbbbb ccccc ddddd "}; std::string_view msg{"Earth To Mars Do You Read\n"}; std::vector<asio::const_buffer> buf_vect{ asio::buffer(ints), asio::buffer(arr), asio::buffer(msg), asio::buffer(f), }; std::string const for_further_processing(asio::buffers_begin(buf_vect), asio::buffers_end(buf_vect)); std::cout << std::quoted(for_further_processing) << "\n"; } Prints "Hello World aaaaaa bbbbb ccccc ddddd Earth To Mars Do You Read So Long And Thanks For All The Fish"
71,290,245
71,315,566
How can I set a stack panel's border color programmatically in C++ in WinUI3?
I am working on a project using WinUI 3 in C++, and I want to change the border color of a XAML control(e.g. stackpanel) according to some condition. I have tried search it online, but most of answers are in c#, and some in C++ I have tried but got no luck. For example: ("StackPanel" is defined in the xaml ) StackPanel().BorderBrush(SolidColorBrush(ColorHelper::FromArgb(255, 255, 255, 255))); Then the error would come up: no instance of overloaded function matches the argument list argument types are: (winrt::Windows::UI::Xaml::Media::SolidColorBrush) object type is: winrt::Microsoft::UI::Xaml::Controls::StackPanel And another one I tried in .cpp file: StackPanel().BorderBrushProperty(SolidColorBrush(Colors::Black())); the error is: too many arguments in function call. Why are these errors happening? Could anyone help me on this? Or any suggestions? Sample code would be great! PS : I am still very new to WinUI 3 especially in C++ (there are not so much study material for C++) I would be grateful for any help.
From what I'm seeing the actual error (as best as i can replicate what you're doing) is Severity Code Description Project File Line Suppression State Error C2664 'void Windows::UI::Xaml::Controls::StackPanel::BorderBrush::set(Windows::UI::Xaml::Media::Brush ^)': cannot convert argument 1 from 'Windows::UI::Xaml::Media::SolidColorBrush' to 'Windows::UI::Xaml::Media::Brush ^' App1 c:\repos\App1\MainPage.xaml.cpp 29 If you create your brush like this auto brush = ref new SolidColorBrush(...); And pass it to the stackpanel like this stackpanel->BorderBrush = brush; Your error should go away. Obviously how you are getting your stack panel might be different from how i did, but the point is you should be able to just set it to the value as long as you have the value in the correct form a ref new object in this case, it would seem.
71,290,448
71,290,471
C++ Left Shift Operation Bit Manipulation
I am not able to get why it is giving negative after certain point. Also I am using long long to prevent overflow. Code #include <iostream> using namespace std; int main() { for(long long i=0;i<64;i++){ cout << 1LL*(1<<i) << " "; } return 0; } Output 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648
1 << i ..in the above line, 1 is an int and i is a long long. So to fix your issue you can cast to a long long as such: #include <iostream> using namespace std; int main() { for (long long i = 0; i < 64; i++) { cout << 1LL * (static_cast<long long>(1) << i) << " "; } return 0; } This will allow you to go to higher values. You can also use 1LL (1 long long) instead of casting: cout << 1LL * (1LL << i) << " "; ..with this you can remove 1LL *: cout << (1LL << i) << " "; // Brakcets are required
71,290,668
71,302,645
Time Complexity Analysis of a function
What is the time complexity of this following function? I am confused between O(log n) and O(sqrt(n)). map<long long int,long long int> mp; void PrimeFactorization(long long n) { while(n%2==0) { n/=2; mp[2]++; } for(long long int i=3;i<=sqrt(n)+1;i+=2) { while(n%i==0) { n/=i; mp[i]++; } } if(n>2) { mp[n]++; } }
This runs in O(sqrt(n)). Technically, it's O(sqrt(n) + log(n)log(log(n))), but that log factor isn't really that big of a deal (and you can get rid of it by using an unordered map). Think of the worst case: If n is prime, then the loop from 3 up to sqrt(n) will just spin all the way up to its limit. This isn't even much of an edge case, since primes are fairly common. Really, the loop is just searching for all the prime factors of n anyway, so it will have to go up to sqrt(n) because that's the limit of the prime factors. There are other, much faster prime factorization algorithms. Check out https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes and https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
71,291,961
71,291,980
Iterate through optional vector in C++
I have an optional vector like optional<std::vector<string>> vec = {"aa", "bb"}; How can I iterate through the vector? Doing the following: for (string v : vec) { cout<<v<<endl; } gives the error: error: no matching function for call to ‘begin(std::optional<std::vector<std::__cxx11::basic_string<char> > >&)’ for (string v : vec) { ^~~~~~~~~~~~~~~~~~~~~~~ How can I iterate though the optional vector?
Use the dereference operator on vec. for (string v : *vec) { cout<<v<<endl; } Note that your program will exhibit undefined behavior with this if vec.has_value() == false. So... check for that first.
71,292,311
71,292,494
how to solve a violation Error using a method
I am getting such a weird violation error by using the getAt() method. I use the method in this order: OdDbBlockTablePtr w_kOdBlockTablePtr ; bool lbCreateDefaults = false; OdDb::MeasurementValue lkMeasurement = OdDb::kEnglish; OdDbDatabasePtr pDb; // Datenbank initialisieren pDb = g_ExSystemServices.createDatabase(lbCreateDefaults, lkMeasurement); // TABLE - Hold Ptr w_kOdBlockTablePtr = pDb->getBlockTableId().openObject(OdDb::kForWrite); const wchar_t AcadBlockModelSpace[] = L "*MODEL_SPACE"; wstring lsModelSpace(AcadBlockModelSpace); w_kOdModelSpaceBlockRecPtr = GetTableRecordIdFromName(lsModelSpace, (OdDbSymbolTablePtr&)w_kOdBlockTablePtr).safeOpenObject(OdDb::kForWrite); OdDbObjectId K_TeighaClass::GetTableRecordIdFromName(wstring& psName, OdDbSymbolTablePtr& pkTablePtr) { OdDbObjectId lkId; try { OdString lsOdName = psName.c_str(); lkId = pkTablePtr->getAt(lsOdName); } catch (OdError& err) { DoOdError(err, NULL, NULL); } return lkId; } I would really appreciate if someone could help me. Thanks in advance
That's not weird at all. If you hover your mouse over pkTablePtr, you will almost certainly find that it is nullptr (or the debugger might report this as 0). There's not enough information in your question to say why this might be, but since you are already running under the debugger you can walk through your code and find out. try ... catch won't catch a hard error like this, by the way. For that, you need __try ... __except (supported on Windows only).
71,292,498
71,301,452
Vulkan hpp header bloating compile times, looking for a workaround
I used clang's ftime-trace to profile the compilation of time of my program. Turns out that about 90% of the time is spent parsing the massive vulkan.hpp header provided by the khronos group. This in turn means that if I minimize the inclusion of this header on header files and put it only on cpp files my compile times should be drastically better. I face the following problem however. There's a few objects in the header that I need pretty much everywhere. There's a few error code enumerators, a few enums of other kinds, and a couple of object types, such as vk::Buffer, vk::Image etc... These ones make less than a fraction of a percent of the total header, but I cannot include them without including the entire header. What can I do to cherry pick only the types that I actually use and avoid including the entire header every time I need my code to interface with an image?
There are some ways to mitigate the issue on your side. vulkan_handles.hpp exists First, there are several headers now (there did not used to be, this was a huge complaint in virtually every vulkan survey). This does not completely mitigate the issues you have (the headers are still massive) but you don't have to include vulkan.hpp, which itself includes every single available header, just to get access to vk::Image and vk::Buffer. Handles are now found in vulkan_handles.hpp ( though it is still 13000 lines long). Forward declaration You talk about not having classes because of the way vulkan works. Hypothetically, you can avoid having Vulkan.hpp in your header files in a lot of cases. vk::Buffer, vk::Image can both be forward declared, eliminating the need to include that header, as long as you follow forward declaration rules Stack PIMPLE wrapping You say that you can't use classes etc... That doesn't really make sense. vk::Buffer and vk::Image are both classes. You could hypothetically create wrapper classes for only the types you need doing this, however, in order to eliminate the overhead you'd have to allocate enough space for those types before hand. Now in a big enterprise library with enterprise defined types, you normally don't do this, because the size of types could change at any moment. However, for vulkan.hpp, the size and declaration of the types vulkan.hpp is using and size of their wrappers is really well defined, and not going to change, as that would cause other incompatibilities on their side. So you can assume the size of these types and create something like : struct BufferWrapper{ // vulkan.hpp buffer only wraps buffer directly, does not inherit from anything, it's size should match it exactly std::array<std::byte, sizeof(VkBuffer)> vk_data; } in cpp file.... BufferWrapper(...){ auto buffer_ptr = new vk_data vk::Buffer(...); } vk::Buffer* getBuffer(){ //technically undefined behavior IIRC, return reinterpret_cast<vk::Buffer*>(&vk_data); } of course since it only wraps buffer, you could actually just use VkBuffer directly and reinterpret cast it. Then you could make buffer wrapper automatically convert to vk::Buffer with non explicit conversion operators, making it hypothetically pretty seamless. However this is a lot of work to do if it's more than a couple of types. If you're willing to put in that much work then you might as well... Use Vulkan.hpp/s generator to just generate cpp/hpp instead of header only So if you're really serious about changing things this far, you might as well change the source code. To start off, Vulkan hpp is not directly written. vulkan.hpp is generated. Inside of the vulan-hpp repo there's the VulkanHppGenerator.hpp and .cpp. Modifying these you make the generator generate source files. You can find prototypes for each generator you need (ie generateHandle). You could hypothetically alter the output to account for a source file. Doing this however is outside the scope of the question, I only bring it up as the nuclear option.
71,292,698
71,294,890
Minimal working example Ctypes and cmakes: function not found
I'm trying to create a minimal working example to run c++ code in python, while using Cmake and Ctypes. These are my files: get_five.cpp extern "C" { int get_five(){ return 5; } } get_five.py import ctypes import os dir_path = os.path.dirname(os.path.realpath(__file__)) dll_file = os.path.join(dir_path,'get_five.dll') lib = ctypes.CDLL(dll_file) print(lib.get_five()) CmakeLists.txt CMAKE_MINIMUM_REQUIRED( VERSION 3.3 ) PROJECT( Test ) add_library(get_five SHARED get_five.cpp) To compile and run this code, i use the following commands: mkdir build cd build cmake .. cmake --build . Then, i copy the file build/debug/test.dll to the root directory and run get_five.py. This gives the following error: AttributeError: function 'get_five' not found Compiling with g++ with the command g++ get_five.cpp -shared -o get_five.dll works fine, so I am assuming I'm making a mistake with the Cmake part. Any suggestions how to make this MWE work correctly?
The function get_five was not exported. The following MWE works correctly: get_five.cpp extern "C" { __declspec(dllexport) int __cdecl get_five(){ return 5; } } get_five.py import ctypes import os dir_path = os.path.dirname(os.path.realpath(__file__)) dll_file = os.path.join(dir_path,'get_five.dll') lib = ctypes.CDLL(dll_file) print(lib.get_five()) CmakeLists.txt CMAKE_MINIMUM_REQUIRED( VERSION 3.3 ) PROJECT( Test ) add_library(get_five SHARED get_five.cpp) To compile and run this code, i use the following commands: mkdir build cd build cmake .. cmake --build . Then, i copy the file build/debug/test.dll to the root directory and run get_five.py.
71,292,753
71,292,838
What's the difference between std::vector and dynamic allocated array?
I have wrote two functions to compare the time cost of std::vector and dynamic allocated array #include <iostream> #include <vector> #include <chrono> void A() { auto t1 = std::chrono::high_resolution_clock::now(); std::vector<float> data(5000000); auto t2 = std::chrono::high_resolution_clock::now(); float *p = data.data(); for (int i = 0; i < 5000000; ++i) { p[i] = 0.0f; } auto t3 = std::chrono::high_resolution_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " us\n"; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() << " us\n"; } void B() { auto t1 = std::chrono::high_resolution_clock::now(); auto* data = new float [5000000]; auto t2 = std::chrono::high_resolution_clock::now(); float *ptr = data; for (int i = 0; i < 5000000; ++i) { ptr[i] = 0.0f; } auto t3 = std::chrono::high_resolution_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " us\n"; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() << " us\n"; } int main(int argc, char** argv) { A(); B(); return 0; } A() cost about 6000 us to initialize the vector, then 1400 us to fill zeros. B() cost less than 10 us to allocate memory, then 5800 us to fill zeros. Why their time costs have such a large difference? compiler: g++=9.3.0 flags: -O3 -DNDEBUG
First, note that the std::vector<float> constructor already zeros the vector. There are many plausible system-level explanations for the behavior you observe: One very plausible is caching: When you allocate the array using new, the memory referenced by the returned pointer is not in the cache. When you create a vector, the constructor will zero the allocated memory area under the hood thereby bringing the memory to the cache. Subsequent zeroing will hit in the cache thus. Other reasons might include compiler optimizations. A compiler might realize that your zeroing is unneccesary with std::vector. Given the figures you obtained I would discount this here though.
71,293,303
71,293,723
GNU gettext ignores set locale
I'm trying to use GNU gettext in a C++ program running on MS Windows. I manage to set the locale as for instance char *locale = setlocale(LC_ALL, "French_France.1252"); I check the returned string so I know it took. Then I set the environment as textdomain("Test"); bindtextdomain("Test", "C:\\develop\\test\\executablesdebug\\Language\\"); Then I do an experimental translation, like char *test = gettext("Hello world"); And the translated string gets the Swedish translation (the operating system setting) and not the French string I wanted.
As far as I can remember in Windows you also have to set the thread locale using SetThreadLocale (you will have to map to the locale ID, take a look at this webpage). Finally, take into consideration that in Windows each thread has its own locale; set it for all threads using translations.
71,293,665
71,294,882
Implementing strdup() in c++ exercise from Bjarne's Book, copying char* to another char* then print out gets nothing
I'm learning c++ using the book:Programming Principles and Practice using C++ by Bjarne Stroustrup. In Chapter 19, exercise 1 implement strdup() functions which will copy a c strings into another using only de-referencing method (not subscripting). My copying doesn't print anything I've been look for answers for days. Please anyone can help me? Below is the entire code:- #include <iostream> using namespace std; char* strdup(const char* q) { // count the size int n {0}; while(q[n]) { ++n; } // allocate memory char* p = new char[n+1]; // copy q into p while(*q) { *p++ = *q++; } // terminator at the end p[n] = 0; return p; } int main() { const char* p = "welcome"; cout << "p:" << p << endl; const char* q = strdup(p); cout << "q:" << q << endl; // check to see if q get new address cout << "&p:" << &p << endl; cout << "&q:" << &q << endl; return 0; }
using only de-referencing method (not subscripting) So this is already wrong, because is uses the subscript operator []: // count the size int n {0}; while(q[n]) { ++n; } I just don't know how to turn the pointer back to the first char. Well, there are two basic approaches: stop damaging your original pointer in the first place. You can introduce new variables, remember? char* p_begin = new char[n+1]; char* p_end = p_begin + n + 1; // copy the terminator too for (char *tmp = p_begin; tmp != p_end; *tmp++ = *q++) ; return p_begin; you know exactly how far to move p to get back to the original value, because you already calculated how long the string is! while(*q) { *p++ = *q++; } *p = 0; // you already moved p and aren't supposed to be subscripting anyway return p - n; Finally, you can get the size without subscripting using exactly the same technique: either you use a temporary variable to find the terminator, or if you advance q as you go, then subtract n from it again at the end. Oh, and if you're having trouble visualizing the values of all your variables - learn to use a debugger (or just add lots of print statements). You need to understand how your state changes over time, and watching it is much more helpful than just observing the result of a black box and trying to guess what happened inside.
71,294,659
71,331,228
How to get mac address
i'm working on a uwp app runing on hololens2, i want get the wifi mac address. according to this documents: Windows.Networking, i wrote this code. // part of includes at pch.h #include <winrt/Windows.ApplicationModel.Activation.h> #include <winrt/Windows.ApplicationModel.Core.h> #include <winrt/Windows.Foundation.h> #include <winrt/Windows.Foundation.Collections.h> #include <winrt/Windows.Foundation.Metadata.h> #include <winrt/Windows.Data.Xml.Dom.h> #include <winrt/Windows.Devices.h> #include <winrt/Windows.Devices.WiFi.h> #include <winrt/Windows.Devices.WiFiDirect.h> #include <winrt/Windows.Devices.Sms.h> #include <winrt/Windows.Networking.h> #include <winrt/Windows.Networking.BackgroundTransfer.h> #include <winrt/Windows.Networking.Connectivity.h> #include <winrt/Windows.Networking.NetworkOperators.h> #include <winrt/Windows.Networking.Proximity.h> #include <winrt/Windows.Networking.PushNotifications.h> #include <winrt/Windows.Networking.ServiceDiscovery.Dnssd.h> #include <winrt/Windows.Networking.Sockets.h> #include <winrt/Windows.Networking.Vpn.h> // some cpp function void MainPage::ClickLoginHandler(IInspectable const&, RoutedEventArgs const&) { using namespace winrt::Windows::Foundation::Collections; using namespace winrt::Windows::Networking; using namespace winrt::Windows::Networking::Connectivity; using namespace winrt::Windows::Networking::NetworkOperators; ConnectionProfile profile = NetworkInformation::GetInternetConnectionProfile(); NetworkOperatorTetheringManager manager = NetworkOperatorTetheringManager::CreateFromConnectionProfile(profile); // error on the line IVectorView<NetworkOperatorTetheringClient> clients = manager.GetTetheringClients(); for (NetworkOperatorTetheringClient client : clients) { OutputDebugString(client.MacAddress().c_str()); OutputDebugString(L"\r\n"); } } but it reports an error: WinRT originate error - 0x8007007F : 'The specified procedure could not be found.'。 it seems missing dll, and i can not found out which one, or two? if you know that please let me know. if you know other way to get mac address, please let me know. Thanks
How to get mac address for hololens2. For this scenario, you could use GetAdaptersAddresses method to approach. The document has simple code that you could refer.
71,295,094
71,295,807
How can I implement a custom iNode on linux?
So every directory, file, queue or whatever in Linux creates it's own inodes that can be accessed in one way or another. How would I go about implementing my own inode type that doesn't quite fit any of the existing descriptions? A custom something that is visible in the file system but isn't a file? Do I have to extend the kernel or is there some simpler approach?
So every directory, file, queue or whatever in Linux creates it's own inodes that can be accessed in one way or another. False. Directories, files etc. do not create their own inodes. They are stored with use of inodes belonging to the filesystem on which they are stored. The inodes are not even created specifically for particular files -- all inodes are created as part of filesystem creation, before there are any files stored on it.* How would I go about implementing my own inode type that doesn't quite fit any of the existing descriptions? It's unclear why you think you need a custom inode type, but if you do, then you need a whole custom filesystem. You will need to write either kernel drivers or FUSE drivers implementing it, plus all the needed utilities for formatting a device with that FS, mounting and unmounting it, checking it for errors, etc. A custom something that is visible in the file system but isn't a file? Do I have to extend the kernel or is there some simpler approach? Everything is a file. This is one of the principles of UNIX. But perhaps you mean something that isn't a regular file. Unfortunately for you, even a custom file system and inode wouldn't be enough to give you a custom file type. The partition of filesystem entries regular files, directories, character and block special files, etc. is deeply ingrained in the kernel and the standard file management APIs and utilities. You would not only have to extend the kernel (beyond writing filesystem drivers), but also modify the C standard library, several standard utilities, and probably a bunch of other libraries and utilities affected by those changes. In the end, you basically have your own whole operating system. But maybe your premise is wrong. UNIX has been going along just fine with pretty much its current file model for a very long time. It's unclear why you want what you say you want, but there are at least two simpler options that might suit you: Write a kernel driver for a character or block device with a filesystem interface, and use the system's existing facilities to link one or more device instances to the filesystem as a character or block special file. Embed what you want to do in regular files / directories / etc. *More or less. I ignore special administrative actions that may in some cases be able to expand a filesystem and add inodes to it in the process.
71,295,342
71,393,074
C++ function in DLL called through Excel / VBA generates exception when passing double argument
I'm trying to use a C / C++ static function in Excel / VBA through a DLL. I'm getting an exception when debugging in VS17, and I suspect it's an issue with the way the argument is passed (it's a double) Exception thrown at 0x00007FFA28BBA14F (kernel32.dll) in EXCEL.EXE: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. here's my C code: test.h extern "C" __declspec(dllexport) double get_sum_cpp(double x); test.cpp double WINAPI get_sum_cpp(double x) { double res = x + x; return res; } declaration in VBA: Declare PtrSafe Function get_sum_cpp Lib "C:\Users\bbi\source\repos\Test\x64\Debug\Test.dll" (ByVal my_var As Double) As Double test code in VBA: Sub testSum() Dim A As Double Dim Asum As Double A = 5 Asum = get_sum_cpp(A) end sub I'm running 64 bits excel, and the dll is compiled in debug mode 64 bits. I have many more issues with the overall development (for example any function with more than one argument will crash excel entirely), but this is the smallest "unit test" I could get too. I feel it's an issue with the way the VBA double argument is passed to the DLL function, (stack misalignment ?), but I can't figure out how to set it right. When debugging in VS17, the exception occurs before I reach the line "double res = x + x", so I suspect it's happening at the function declaration, so when the double argument is passed - so an issue with casting - again maybe stack misalignment ? my exports seem OK - checked with dumpbin / EXPORTS. The function is found and eventually returns. Any idea ?
I have successfully ran your code exactly without any problem on my computer. My VBA script: Private Declare PtrSafe Function get_sum_cpp Lib "D:\Codes\VC\TestVBA\x64\Debug\Dll2.dll" (ByVal my_var As Double) As Double Sub testSum() Dim A As Double Dim Asum As Double A = 5 Asum = get_sum_cpp(A) MsgBox "Val is: " & Asum End Sub and your C++ code. I have tested both with your code and using __declspec(dllexport) and definition file. Both works. I also have tested with/without DLL runtime library. Still works. I have used VS2019, Excel 2019. If they are not same version, make sure you are using /MT not /MTd for non-DLL runtime libraries though.
71,295,439
71,295,690
GCC 11.x vexing-parse + inconsistent error (redeclaration as different symbol type), is it a GCC bug?
The following code compiles with no problems from GCC 4.7.1 up to but not including GCC 11.1: constexpr int SomeValue = 0; void test () { void (SomeValue) (); } On GCC 11.x it fails with: <source>:4:23: error: 'void SomeValue()' redeclared as different kind of entity 4 | void (SomeValue) (); | ^ <source>:1:15: note: previous declaration 'constexpr const int SomeValue' 1 | constexpr int SomeValue = 0; | ^~~~~~~~~ But the error "redeclared as different kind of entity" seems strange to me: Ambiguous parsing possibilities aside, the scope is different. Also, these tests all compile on all versions of GCC since 4.7.1 (including 11.x), even though AFAIK each one is redeclaring SomeValue as "a different type of entity": constexpr int SomeValue = 0; void test1 () { typedef void (SomeValue) (); } void test2 () { double SomeValue; } void test3 () { using SomeValue = char *; } void test4 () { void (* SomeValue) (); } void test5 () { struct SomeValue { }; } void test6 () { enum class SomeValue { }; } As a relatively less nonsensical example, this code also fails from 11.x on in a similar fashion: constexpr int SomeValue = 0; struct SomeClass { explicit SomeClass (int) { } void operator () () { } }; void test () { SomeClass(SomeValue)(); } Although in this case it's preceded by a vexing-parse warning that also isn't present before 11.x (the fact that the warning is here but not in the above makes sense, the fact that the warning doesn't appear pre-11.x is the interesting bit): <source>: In function 'void test()': <source>:9:25: warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse] 9 | SomeClass(SomeValue)(); | ^~ <source>: At global scope: <source>:9:26: error: 'SomeClass SomeValue()' redeclared as different kind of entity 9 | SomeClass(SomeValue)(); | ^ <source>:1:15: note: previous declaration 'constexpr const int SomeValue' 1 | constexpr int SomeValue = 0; | ^~~~~~~~~ Compiler returned: 1 But wait! There's more! This code -- which I would have expected to fail on 11.x due to the same parsing ambiguities as above -- compiles just fine on all those versions of GCC (including 11.x): constexpr int SomeValue = 0; auto closure = [] (int) { return [] () { }; }; void test () { closure(SomeValue)(); // <-- doesn't cause any problems } No warnings or anything there. So... What's going on here? Why is it only a problem for SomeValue to be "redeclared as a different kind of entity" in those specific cases, and only since GCC 11.1, and why doesn't closure(SomeValue)() suffer the same problem as SomeClass(SomeValue)()? Also what changed? Is GCC correct here? Is it a new bug introduced in GCC 11.x? Or perhaps an old bug that was finally fixed in 11.x? Or not a bug at all and something else changed? I'm struggling to come up with a consistent explanation.
The difference is that your first snippet declares a function that exists globally; all your other declarations are of local entities. (Note that even if the declaration were valid, you couldn't call that function, since it can't exist.) In the last snippet, closure is not a type, so it can't be a declaration.
71,295,518
71,854,368
Change QDateEdits behaviour on select all
I am learning Qt (in C++) and I have a question regarding the QDateEdit. I want to be able to type after selecting the text in my QDateEdit. By default you cannot type if you select the whole date. I am sure there is an easy way to do that. How can I change the behaviour to start at the beginning of my QDateEdit instead of doing nothing? Thanks in advance
In case anyone else has the same problem, the solution is rather simple. Currently I am using the QDateTimeEdit. You can override the "keyPressed" method, check for "ctrl+a" and use the "setSelectedSection" method with "sectionAt(0)" which allows the user to start typing at the beginning of the QDateTimeEdit.
71,295,538
71,295,789
Passing a non-static method or std::function<void(...)> as a void (*) argument
I'm trying to define a function/method (void MyClass::myDispatcher(int, int, void *) or std::function<void(int, int, void *)> myDispatcher) which would be a member of a host class. However, I also need to pass this function to through an external library which takes as argument: void (*dispatcher) (int, int, void *). Is there a way I can convert a non-static function to the required void (*)(int, int, void *) type ? My first attempt with the candidate void MyClass::myDispatcher(int, int, void *) was using the std::bind() in order to bind MyClass::myDispatcher with this. Although I could not convert the return type of std::bind to match the void (*). The second attempt was done using std::function<void(int, int, void *)> myDispatcher for which I tried to use the reinterpret_cast<void (*)(int, int, void *)>(&myDispatcher) to fit in the requested argument. It did compile but I ultimatly ended up in a segfault within the external library. I could summarized my two attempts with this example: class MyClass{ MyClass() = default; void myDispatcher(int, int, void *){ // do something } void init(){ myFct = [this](int, int, void*){ // do something }; external_function(reinterpret_cast<void (*)(int, int, void *)>(&myFct)); // or the non-compiling // external_function(std::bind(&MyClass::myDispatcher, this)); } private: std::function<void(int, int, void*)> myFct; }; Edit: As some of you pointed out: this C-style external_function has an extra void * argumement which is passed as the last arg to the provided function! To summarise: there is no way to do such a thing since there is a fundamental difference between a function pointer and non-static member functions. However, C-style library usually provides a workaround which performs a callback to the provided static function: void external_function(void (*dispatcher) (int, int, void *), void* info){ // a bunch of instructions (meaningless for this example) int a,b; dispatcher(a,b,info); } Once we know that, one can cast back the info pointer to the class we want.
As stated, this is not possible since there is no way to meaningfully construct a plain function pointer from a (non static) method, a closure, or a std::function object. Roughly speaking, each of the constructs above are logically formed by two parts: some fixed code (a pointer to a fixed, statically known function), and variable data (the object at hand, or the captures for a closure). We can not simply throw away the second part. That being said, I would recommend to check if the library will call the dispatcher passing a user-defined pointer for its void * argument. It's somewhat common to see C style library functions like void register_callback(void (*dispatcher)(int,int,void *), void *user_data); This is a trick to allow to simulate closures in C, passing the two "parts" of the closure separately. If that's the case, instead of // not working, just for example std::function<void(int, int)> f; register_callback(f); You can write // Make sure f will live long enough. // I'm using new to stress the point, but you can use anything // else provided that the pointer will be valid when f is // called. std::function<void(int, int)> *pf = new ...; register_callback(call_the_function, pf); provided you have defined // fixed function, independent from the std::function object void call_the_function(int x, int y, void *p) { std::function<void(int,int)> *pf = (std::function<void(int,int)>*) p; (*pf)(x,y); } If you used new to keep the pointer valid long enough, remember to delete it when the callback is no longer needed.
71,296,091
71,298,269
Question regarding time complexity of nested for loops
Let n be a power of 2. int sum = 0; for (int i = 1; i < n; i *= 2) for (int j = 0; j < n; j++) sum += 1 Is the time complexity O(N) or O(nlogn). Thanks!
So first of all, it isn't necessary to know what kind of number is n is, since the asymptotic complexity is dependent of any arbitrary n(as long it is a positive integer). We also know that the inner loop will do n iterations, hence we can denote the inner loop the time complexity of O(n). About the outer loop. We know that at each iteration we double the values of i. Since i isn't zero at the initialization, it will for sure be increased by it doubling it. Since we are actually doubling i at each iteration we know that we reach n with exponentially increasingly larger iteration steps(for i=1, 2, 4, 8, 16, 32, 64, 128...). Hence the number of steps to reach n will become smaller while we get closer to it. Now knowing this we see that we are doing at most log(n) iterations to reach n. Why? -> Well this might be mathematically informal, but I hope this is fine. In order to compute the number of iterations, one has to solve this equation: 2^x = n, where x is the number of iteration. We can see this basically by the explanation above. At each iteration step we double i until we reach n. The solution for x is than: x < log_2(n) Hence the time complexity of the outer loop is O(log(n)). Know this, one can simply multiply the complexities to O(log(n)n).
71,296,302
71,296,975
‘numeric_limits’ is not a member of ‘std’
I am trying to compile an application from source, FlyWithLua, which includes the sol2 library. I am following the instructions but when I run cmake --build ./build I get the following error: In file included from /home/jon/src/FlyWithLua/src/FloatingWindows /FLWIntegration.cpp:10: /home/jon/src/FlyWithLua/src/third_party/sol2/./upstream/sol.hpp: In lambda function: /home/jon/src/FlyWithLua/src/third_party/sol2/./upstream/sol.hpp:7194:59: error: ‘numeric_limits’ is not a member of ‘std’ 7194 | std::size_t space = (std::numeric_limits<std::size_t>::max)(); There are several other errors on the same line after this, but I guess they might just go away if I can solve this one. there are several similar issues with the solution to add the following includes to the .hpp file #include <stdexcept> #include <limits> the sol.hpp file includes the following imports: #include <stddef.h> #include <limits.h> https://sol2.readthedocs.io/en/latest/errors.html gives some hints about the why the compiler might not recognize these includes: Compiler Errors / Warnings A myriad of compiler errors can occur when something goes wrong. Here is some basic advice about working with these types: If there are a myriad of errors relating to std::index_sequence, type traits, and other std:: members, it is likely you have not turned on your C++14 switch for your compiler. Visual Studio 2015 turns these on by default, but g++ and clang++ do not have them as defaults and you should pass the flag --std=c++1y or --std=c++14, or similar for your compiler. the src/CMakeList.txt file has the following line: set(CMAKE_CXX_STANDARD 17) I'm only faintly familiar with C/C++ and this all seems very complicated to me, but I'm hoping that there might be an easily recognizable cause and solution to this to someone more skilled. cat /etc/*-release gives DISTRIB_RELEASE=21.10 DISTRIB_CODENAME=impish DISTRIB_DESCRIPTION="Ubuntu 21.10" $ g++ --version g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0
/home/jon/src/FlyWithLua/src/third_party/sol2/./upstream/sol.hpp:7194:59: error: ‘numeric_limits’ is not a member of ‘std’ 7194 | std::size_t space = (std::numeric_limits<std::size_t>::max)(); This error message implies that src/third_party/sol2/./upstream/sol.hpp header uses std::numeric_limits, but also that std::numeric_limits hasn't been defined. The simplest explanation for that is that the header that defines std::numeric_limits hasn't been included. In such case, the solution is to include the header that defines std::numeric_limits. the sol.hpp file includes the following imports: #include <stddef.h> #include <limits.h> This confirms the problem. Neither of those headers define std::numeric_limits. https://sol2.readthedocs.io/en/latest/errors.html gives some hints about the why the compiler might not recognize these includes: Those hints may apply to some other cases, but not this one. std::numeric_limits has been part of the C++ standard since the beginning, so language version has no effect on its existence. Conclusion: According to the quoted error message, sol.hpp uses std::numeric_limits which is defined in the header <limits>, but according to you, it doesn't include that header. If this is the case, then this is a bug in the sol.hpp file. Correct solution would be to fix the sol.hpp file by including <limits> in that file before using std::numeric_limits.
71,296,412
71,296,727
C++ reading a file which contains nulls
I'm reading a file a RSA encrypted binary file which contains nulls. The file is encrypted and saved in python, then read in c++. Python treats it fine, reading and writing it just displays the nulls as ...\x94\x00\xbf... However, in my C++ it terminates it early. FILE* fpy = fopen("test.txt", "rb"); unsigned char* signPy = (unsigned char*)malloc(256); fread(signPy, 1, 256, fpy); fclose(fpy); cout << signPy << endl; The file is exactly 256 bytes so I know I'm allocating enough memory. Using fread it terminates at the first null. Any help would be appreciated.
Continuing the code: FILE* fpy = fopen("test.txt", "rb"); unsigned char* signPy = (unsigned char*)malloc(256); int const count = fread(signPy, 1, 256, fpy); fclose(fpy); // cout << signPy << endl; for (int i = 0; i < count; ++i) putchar(signPy[i]); Problem was that cout will treat signPy as null terminated char buffer, so it will stop printing more characters once null is encountered. You can print the data in binary format as well, as suggested in comments.
71,297,185
71,298,757
Adding xml-comments to boost::property_tree
I am using boost::property_tree::xml_parser to create an xml-file. Now I also need to add comments to the xml-file. I've done some research and found out that comments are not allowed in JSON, and thus also not supported by the boost::property_tree::json_parser... Furthermore I found out, that there is a no_comments flag for skipping xml-comments when reading an xml-file... But what about adding xml-comments to a file?
If comments are not disabled with the mentioned flag, they get represented as nodes named <xmlcomment> (just like attributes are under nodes named <xmlattr>): Live On Coliru #include <boost/property_tree/xml_parser.hpp> #include <iostream> int main() { boost::property_tree::ptree pt; pt.put("some.node.<xmlattr>.attr1", "value1"); pt.put("some.node.<xmlcomment>", "\nEhffvna Jnefuvc\nTb Shpx Lbhefrys\n"); write_xml(std::cout, pt); } Which prints <?xml version="1.0" encoding="utf-8"?> <some><node attr1="value1"><!-- Ehffvna Jnefuvc Tb Shpx Lbhefrys --></node></some>
71,297,314
71,297,446
Is uncaught exception message guaranteed
Is the following code #include <stdexcept> int main() { throw std::runtime_error("foobar"); } guaranteed to produce the following outout? terminate called after throwing an instance of 'std::runtime_error' what(): foobar fish: Job 1, './a.out' terminated by signal SIGABRT (Abort) Can I rely on this exact output on every compiler? Can I rely on that what method will be called and error message will be printed will be printed?
No it is not guaranteed, it unspecified whether there is any message. From cppreference: If an exception is thrown and not caught, including exceptions that escape the initial function of std::thread, the main function, and the constructor or destructor of any static or thread-local objects, then std::terminate is called. It is implementation-defined whether any stack unwinding takes place for uncaught exceptions. The case that is relevant here is "exceptions that escape [...] the main function". The call to std::terminate is guaranteed though. And you can install a std::terminate_handler to print a custom message if you like.
71,297,521
71,297,552
Why character need 1 byte and not 4?
Character have an ASCII code which is a number(integer). Then why it only takes 1 byte and not 4 bytes "like an int value" to store it in the memory.
ASCII is a 7 bit encoding. Most modern CPU have an 8 bit byte. On a system with 8 bit byte, a single byte is sufficient to represent a character of a 7 bit encoding. There is no need to use more bytes than one.
71,297,640
71,300,469
Do changes in GCC mangling affect ABI compatability?
Documentation for -fabi-version says this[only part here]: [...] Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors. Version 12, which first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. Version 13, which first appeared in G++ 8.2, fixes the accidental change in version 12. Version 14, which first appeared in G++ 10, corrects the mangling of the nullptr expression. Version 15, which first appeared in G++ 11, changes the mangling of __ alignof __ to be distinct from that of alignof, and dependent operator names. My question is do this mangling changes(so not for example calling conventions change, but changes in Version14 and Version15) affect ABI compatability, of will during link time linker just pick one and everything will be great? note: presume I am using those things, although I doubt that most people use those in API boundaries.
Yes, each ABI version is incompatible, but most of the changes affect only rare cases, and hopefully certain versions like 12 are rare because they were fixed quickly. The reason such changes are made at all is usually that certain things mangle to the same name, which breaks even if only one component uses it rather than needing two to be incompatible.
71,298,056
71,298,171
Undefined symbols: "BankAccount::BankAccount( ... "
i'm new to c++ and am learning from a course. I trying to write a program using classes to store bank info. This is how my class is set up. #include <iostream> using namespace std; class BankAccount { private: double balance = 0; int acountNumber = 0; string ownerName; double interestRate = 0; public: double getBalance() { return balance; } void deposit(double userINPUT) { balance = balance + userINPUT; } void withdraw(double userINPUT) { balance = balance - userINPUT; } void addInterest() { balance = balance * (1 + interestRate); } BankAccount(); BankAccount(double balance, double interestRate, int acountNumber, string ownerName); void displayAccountSummary() { cout << "Account Number : " << acountNumber; cout << "\nOwner’s Name : " << ownerName; cout << "\nBalance : " << balance; cout << "\nInterest rate : " << interestRate << "%" <<endl; } }; i am trying to run the following commands into my main(), but one the first line - BankAccount myAcount(1000.50, 0.05, 1111, "John Williams"); ..I get the error that I don't understand. Undefined symbols: "BankAccount::BankAccount(double, double, int, std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator >) this is what I'm trying to call BankAccount myAcount(1000.50, 0.05, 1111, "John Williams"); //error here myAcount.deposit(500); myAcount.withdraw(200); myAcount.addInterest(); myAcount.displayAccountSummary(); return 0; any idea what I need to fix?
Implement your constructors as such: BankAccount() {} BankAccount(double balance, double interestRate, int acountNumber, string ownerName) : balance(balance), interestRate(interestRate), acountNumber(acountNumber), ownerName(ownerName) {} Using an unimplemented function causes linker issues.
71,298,203
72,319,524
How to use GstReferenceTimestampMeta properly
My goal is to attach timestamps to GstBuffer which is independent of GST time. I found GstReferenceTimestampMeta, which looks exactly what I am after. However I have some issues when trying to utilize it. Maybe I have misundestood the usage of the GstMeta structure. Brief overview of pipeline: server: appsrc -> h265enc -> rtp -> udpsink client: udpsrc -> h265decode -> appsink What I am doing in the server is to attach the GstMeta to a GstBuffer before pushing the buffer into the appsrc, as such: auto buffer = gst_buffer_new_allocate(NULL, buffer_size, NULL); // ------------------------- GstReferenceTimestampMeta START GstCaps *caps = gst_caps_from_string("timestamp/x-test-stream"); gst_buffer_add_reference_timestamp_meta( buffer, caps, timestamp.nanoseconds(), GST_CLOCK_TIME_NONE ); // ------------------------- GstReferenceTimestampMeta END GstMapInfo info; gst_buffer_map(buffer, &info, GST_MAP_READ); std::memcpy(info.data, image.data, buffer_size); gst_buffer_unmap(buffer, &info); gst_app_src_push_buffer(GST_APP_SRC(appsrc_), buffer); Similarly, what I do at the client side is: GstSample *sample = gst_app_sink_try_pull_sample(GST_APP_SINK(appsink_), 10000000); GstBuffer *buffer = gst_sample_get_buffer(sample); // ------------------------- GstReferenceTimestampMeta START GstReferenceTimestampMeta *meta; GstCaps *reference = gst_caps_from_string("timestamp/x-test-stream"); meta = gst_buffer_get_reference_timestamp_meta(buffer, reference); if (meta == NULL){ std::cout << "daim" << std::endl; break; } else { std::cout << meta->timestamp << std::endl; } // ------------------------- GstReferenceTimestampMeta END MapInfo buffer_mapping; gst_buffer_map(buffer, &buffer_mapping, GST_MAP_READ); GstCaps *caps = gst_sample_get_caps(sample); GstStructure *properties = gst_caps_get_structure(caps, 0); int width, height; gst_structure_get_int(properties, "width", &width); gst_structure_get_int(properties, "height", &height); std::string format = gst_structure_get_string(properties, "format"); int numChannels = (format == "BGR") ? 3 : 1; renderTracks(buffer_mapping.data, width, height, numChannels); loadBufferOnDevice(width, height, numChannels, buffer_mapping.data); gst_buffer_unmap(buffer, &buffer_mapping); gst_sample_unref(sample); The result here is "daim" printed to cout as the GstMeta with reference caps "timestamp/x-test-stream" is not found, and thus the variable meta == NULL. I might have misundestood the usage of the GstMeta structure. Hopefully someone can point me in the right direction. If there are other methods of attaching "custom" timestamp to a buffer, please let me know!
as far as I know, GstMeta data is intra-pipeline only. If you need an inter-pipeline solution, you need to implement it in the coded (H.264, H.265, ...) or in the RTP header. Cheers,
71,298,250
71,298,335
Passing parameter to a constructor
I created a class vector in C++ and then tried to use an vector object in a different class called abc. What I want to do is define a object in class abc of type vector Something like this: #include <iostream> using namespace std; class vector{ public: double icomponent=1; double jcomponent=1; double kcomponent=1; vector(double conI, double conJ, double conK){ //constructor icomponent = conI; jcomponent = conJ; kcomponent = conK; } }; class abc{ double i,j,k; vector velocity(i,j,k); }; However this code doesn't compile and throws this error: member "abc::i" is not a type name I don't understand what is causing the problem. Can anyone figure it out? I tried searching online, but the closest I could find is-this , but that one was caused by some header file reference issues, and not related to this one.
You cannot do what you are trying to do in the way you've defined. Essentially, you cannot pass the variables i, j, and k to the constructor for velocity in such a manner. You need a constructor. Example: class abc { double i, j, k; vector velocity; public: abc( double i, double j, double k ) : i{i}, j{j}, k{k}, velocity{ i, j, k } {} }; This uses the member initializer list to initialize the three double variables, as well as the velocity variable. Alternatively, as user17732522 mentions in the comments below, if your variables are public, you can do what you were trying with a slight modification: class abc { public: double i, j, k; vector velocity = vector{ i, j, k }; }; In order to use this method, you must initialize the i, j and k during construction of the object (either through a constructor, or through an aggregate initialization as shown below), otherwise, you will get undefined behaviour by utilizing uninitialized variables in the creation of the velocity object. int main() { abc a{ 1, 2, 3 }; std::cout << a.velocity.icomponent << '\n'; // print 1 std::cout << a.velocity.jcomponent << '\n'; // print 2 std::cout << a.velocity.kcomponent << '\n'; // print 3 } The problem with vector velocity( i, j, k ); that you were trying, is that the C++ compiler interprets this as a function called velocity which returns a vector, then i, j and k are expected to be types (which of course they are not).
71,298,728
71,298,836
Metafunction as member function parameter
Currently my code has this form: template <typename T> class A { private: T data; public: void apply_process(A<T> obj, std::function<T(A<T>&)> process) { data = process(obj); } // ... }; This works with runtime lambdas; yet, while obj will be only known on runtime,process will be known at compile time. Can I rewrite this somehow so that process is a metafunction to be passed as a compile-time parameter? A C++14 solution is preferable.
It is not clear what you want, but by combining up the keywords you are throwing, I think you want this: template <typename T> class A { private: T data; public: template<class UnaryFunction> void apply_process(A<T> obj, UnaryFunction process) { data = process(obj); } // ... }; to be a bit more pedantic use perfect forwarding (from comment): void apply_process(A<T> obj, UnaryFunction&& process) { data = std::forward<UnaryFunction>(process)(obj); }
71,299,167
71,299,417
c++ format unordered map with fmt::join
I'm trying to create a libfmt formatter for a std::unordered_map<std::string, Foo> using fmt::join but I can't seem to get it to work: #include <fmt/core.h> #include <fmt/format.h> #include <unordered_map> struct Foo{ int a; }; using FooPair = std::pair<std::string, Foo>; using FooMap = std::unordered_map<std::string, Foo>; namespace fmt{ template <> struct formatter<Foo> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const Foo& f, FormatContext& ctx) { return format_to(ctx.out(), "\n {}", f.a); } }; template <> struct formatter<FooPair> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const FooPair& fp, FormatContext& ctx) { return format_to(ctx.out(), "\n {}{}", fp.first, fp.second); } }; template <> struct formatter<FooMap> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const FooMap& fm, FormatContext& ctx) { return format_to(ctx.out(), "{}", fmt::join(fm.begin(), fm.end(), "")); } }; } int main(){ FooMap foomap; fmt::print("Foo Map: {}", foomap); } It looks like I'm missing a formatter for an iterator, but I tried defining that as well as one for a const_iterator to no avail. Minimum example here: https://godbolt.org/z/q4615csG6 I'm sure I'm just leaving something stupid out, I just can't see it at the moment.
Here is fixed version: https://godbolt.org/z/r6dGfzesz using FooMap = std::unordered_map<std::string, Foo>; using FooPair = FooMap::value_type; Problem is this: using FooPair = std::pair<std::string, Foo>;. Note documentation of unordered_map: std::unordered_map - cppreference.com value_type std::pair<const Key, T> So problems is not matching types: one pair contains const for key (first) other is not. So other way to fix it: using FooPair = std::pair<const std::string, Foo>; https://godbolt.org/z/9KT9j6h1b
71,299,247
71,299,304
Inserting an element in given positions (more than one) of a vector
I am trying to add a certain value in loop to a given position of a certain vector. For example: the value is 11 and hence local_index = 11 The vector of position I have in input is neigh = {5,7} The starting vector is Col={0,1,2,3,4,5,6,7,8,9,10} I want to have as output Col={0,1,2,3,4,5,11,6,7,11,8,9,10}. This is my first try: vector<long> neigh = {5,7}; long local_index = 11; auto pos_col = Col.begin(); for (const auto& elem: neigh) { Col.insert(pos_col+elem,local_index); I keep getting for the second value of neigh a segmentation fault. So my questions are: Is this because the insert return a pointer that cannot be re-assigned? If the answer to the first question is yes, how can I achieve my goal?
Per the vector::insert() documentation on cppreference.com: Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated. Which means that, after your 1st call to insert(), your pos_col iterator is now invalid for subsequent calls to insert(), as it refers to an element before the insertion point. Try using this instead: auto pos_col = Col.begin(); for (const auto& elem: neigh) { Col.insert(pos_col+elem,local_index); pos_col = Col.begin(); } Or simply: Col.insert(Col.begin()+elem,local_index);
71,299,545
71,299,622
How Should I Define an Array of Pointers to Functions in C++?
I'm trying to make an array of functions so I can call functions from the array with an index. I can't seem to figure out the parentheses, asterisks and brackets to create this array of functions. Here is what I have: void Game::getPawnMoves(int position, bool color, Move ** moveList) { ... } typedef void (*GetMoveFunction) (int, bool, Move **); void Game::getLegalMoves(Move ** moveList) { GetMoveFunction functions[] = { getPawnMoves, getKnightMoves, getBishopMoves, getRookMoves, getQueenMoves, getKingMoves }; ... } All of the getPawnMoves, getKnightMoves, and the rest all have the same arguments and all return void. Move is just a struct with two chars and an enum. In this case, if you'd like to try compiling it, you could replace Move ** with int **. The error I'm getting when I compile is: Game.cpp:443:5: error: cannot convert ‘Game::getPawnMoves’ from type ‘void (Game::)(int, bool, Move**) {aka void (Game::)(int, bool, Move_t**)}’ to type ‘GetMoveFunction {aka void (*)(int, bool, Move_t**)}’ So for some reason the compiler thinks that GetMoveFunction is void * instead of void, but if I change the typedef to typedef void (GetMoveFunction) (int, bool, Move **); I get the error: Game.cpp:435:28: error: declaration of ‘functions’ as array of functions GetMoveFunction functions[] = I'm honestly super stuck on this one. Thanks so much for your help!
How Should I Define an Array of Pointers to Functions in C++? typedef void (*GetMoveFunction) (int, bool, Move **); This is a pointer to function. GetMoveFunction functions[] = { // ... }; This is an array of pointers to functions. You've achieved what you asked for in the title of the question. Game.cpp:443:5: error: cannot convert ‘Game::getPawnMoves’ from type ‘void (Game::)(int, bool, Move**) {aka void (Game::)(int, bool, Move_t**)}’ to type ‘GetMoveFunction {aka void (*)(int, bool, Move_t**)}’ The problem here is that you are trying to initialise the function pointers using non-static member functions. Function pointers cannot point to non-static member functions. What you probably need is an array of pointers to member functions of Game instead. Another option is an array of type erasing function wrappers (std::function).
71,300,057
71,300,112
Initializing a pointer with 'this' keyword. Does it create new instance? Using it make my program thread-safe or not?
Here is a singleton design pattern. I am trying to make the given code thread safe, using thread_local. First of all, I need to know how the given instantiation of the pointer with 'this' works. File : Myclass.h class Student { public: Student(); int x; private: static Student *globalStudent; }; File : Myclass.cpp Student *Student::globalStudent = NULL; Student::Student() { assert(globalStudent == NULL); globalStudent = this; // How this works? Does it creates an instance? } And after making it thread-safe, File : Myclass.h class Student { public: Student(); int x; }; File : Myclass.cpp thread_local Student *globalStudent = nullptr; Student::Student() { assert(globalStudent == NULL); globalStudent = this; } Does it make my program thread-safe? If not, then what should I do?
globalStudent = this; // How this works? this is a special expression that yields a pointer to the object whose member function is being called. This assignment makes the assigned pointer point to the object whose member function is being called. Does it creates an instance? No, assigning a pointer doesn't create an instance. DOES IT MAKE MY PROGRAM THREAD-SAFE? A singular change cannot make an entire program thread safe. But, the change does make it safe to call Student::Student() from multiple threads without synchronisation. It's important however to consider that each thread will point to a different instance. Hence this is by definition not a singleton. This is an unnecessarily complicated way to implement the singleton pattern. (And singleton is sometimes an anti-pattern, so consider carefully whether it's appropriate).
71,300,163
71,310,291
How to create a window with CreateWindowEx but ignoring the scale settings on Windows
When I create a window with CreateWindowEx it will follow the resolution but also use the scale settings from the display settings. So, in 1920 x 1080 if I try to create the window, the size is actually 1200 something when scale is at 150%. Is there a way to get around this limitation? If I just set the size manually to 1920 x 1080 I get a cropped window. Thanks. auto activeWindow = GetActiveWindow(); HMONITOR monitor = MonitorFromWindow(activeWindow, MONITOR_DEFAULTTONEAREST); // // Get the logical width and height of the monitor MONITORINFOEX monitorInfoEx; monitorInfoEx.cbSize = sizeof(monitorInfoEx); GetMonitorInfo(monitor, &monitorInfoEx); auto cxLogical = monitorInfoEx.rcMonitor.right - monitorInfoEx.rcMonitor.left; auto cyLogical = monitorInfoEx.rcMonitor.bottom - monitorInfoEx.rcMonitor.top; vScreenSize = { cxLogical, cyLogical }; WNDCLASS wc; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.hInstance = GetModuleHandle(nullptr); wc.lpfnWndProc = olc_WindowEvent; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.lpszMenuName = nullptr; wc.hbrBackground = nullptr; wc.lpszClassName = olcT("Wusik SQ480 Engine"); RegisterClass(&wc); DWORD dwExStyle = 0; DWORD dwStyle = WS_VISIBLE | WS_POPUP; olc::vi2d vTopLeft = vWindowPos; // Keep client size as requested RECT rWndRect = { 0, 0, vWindowSize.x, vWindowSize.y }; AdjustWindowRectEx(&rWndRect, dwStyle, FALSE, dwExStyle); int width = rWndRect.right - rWndRect.left; int height = rWndRect.bottom - rWndRect.top; olc_hWnd = CreateWindowEx(dwExStyle, olcT("Wusik SQ480 Engine"), olcT(""), dwStyle, vTopLeft.x, vTopLeft.y, width, height, NULL, NULL, GetModuleHandle(nullptr), this);
Thanks to Remy Lebeau it was as simple as adding the following call to the main initialization of the app. Now I always get a window with the physical resolution and not a logic scaled resolution. SetProcessDPIAware();
71,300,438
71,300,481
How to initialize private variables in a different file and make it so it holds the value for other functions?
I just need to know how to have size, index, and counter keep their values when they are called in another function. Right now they are just being given random values when they are called instead of the values I'm initializing them with in the constructor. How can I fix this? The objective for this code is to make a program that Captures a string of words from a user of the program (via the keyboard) and adds the entered words to a dynamic array of strings. This is the array.cpp file #include "array.h" using namespace std; Array::Array() { int size = 100; int index = 0; int counter = 0; counter ++; index++; string *ptr = new string[size]; } Array::~Array() { delete ptr; ptr = nullptr; } void Array::populate() { string word; cout << "Enter word to add to array: "; cin >> word; ptr[index] = word; } void Array::printContent() { cout << "Number of words in array: " << counter << endl; cout << "Array size: " << size << endl; cout << "Words in array: " << endl; for (int i = 0; i < counter; i++) { cout << ptr[i] << endl; } } void Array::displayMenu() const { cout << "[1] Add Word\n" << "[2] Print Array Information\n" << "[3] Quit Program\n" << "Enter Choice: "; } int Array::getChoice(int & choice1) { cin >> choice1; while (choice1 < 1 || choice1 > 3) { cout << endl; cout << "Invalid Entry!!" << endl; cout << "Enter Choice: "; cin >> choice1; } return choice1; } int Array::endProgram(int & start2) { start2 = 0; cout << "\n\n\t\tThank you for using this system!!\n\n"; return start2; } This is the array.h file #include <iostream> #include <string> using namespace std; class Array { public: Array(); ~Array(); void populate(); void printContent(); void displayMenu() const; int getChoice(int & choice1); int endProgram(int & start2); private: int size; int index; int counter; string *ptr; }; Lastly this is the main.cpp file #include <iostream> #include "array.h" using namespace std; int main() { int choice = 0; int start = 1; Array theArray; while(choice != 3) { theArray.displayMenu(); theArray.getChoice(choice); if(choice == 1) { theArray.populate(); } if(choice == 2) { theArray.printContent(); } if (choice == 3) { theArray.endProgram(start); } } }
You are defining new local variables inside of your Array constructor and shadowing the member variables of the same name -- which is why the value isn't being preserved. You only need to specify the type when defining new variables, but not when assigning to existing ones. To assign to the member variables, this should be: Array::Array() { size = 100; index = 0; counter = 0; ptr = new string[size]; ... } Additionally, in constructors its more correct to use constructor initializer lists to initialize the values: Array::Array() : size{100}, index{0}, counter{0}, ptr{new string[size]} { ... }
71,301,202
71,301,534
Why do I keep needing to rebuild solution in Visual Studio?
I'm new to Visual Studio, so I haven't gotten used to things yet. I've been using it for weeks with no problem, but today I've noticed that I have to click rebuild solution every time I make any changes to my code, otherwise it'll run an old version of the code. Is this a common thing? I've never had to do it until today, then all of a sudden I have to do it every time.
C++ has multiple stages, the compile stage to the link stage. If code changes, VS has to build (compile) and then link those changes into the app. If a library changes, then VS needs to link in the library changes. If you are having to rebuild everytime, then VS is detecting some type of change to either a C++ file or a linked in library. Finding what is changing will tell you why you have to rebuild to keep the exe (app) current. On a side note, if you are debugging and the debugger seems to step into comments/places it shouldn't be...then your code is in need of being (re)-compiled and linked. For the pdb (debug) files are out of sync with the textual code files that were changed and that is why the debugger is behaving as such.
71,301,568
71,301,669
Unable to trigger a duel to play out c++
Working on an assignment to have a duel play out amongst three players with varying accuracy and needs them to shoot in order. Aaron has an accuracy of 1/3, Bob has an accuracy of 1/2, and Charlie never misses. A duel should loop until one is left standing. Here is my code so far and it only ever causes the first two players to miss and Charlie wins even when the random number generator should constitute a hit. #include <iostream> #include <ctime> #include <cstdlib> using std::cin; using std::cout; using std::endl; void shoot(bool & targetAlive, double accuracy); int startDuel(); int main() { srand(time(NULL)); startDuel(); return 0; } void shoot(bool &targetAlive, double accuracy) { double x; x = (((float)rand()/(float)(RAND_MAX))*1.0); if (x < accuracy) { cout << "target is hit!" << endl; targetAlive = false; } else cout << "missed!" << endl; cout << x << endl; targetAlive = true; } int startDuel() { int a = 0, b = 0, c = 0; bool aaronAlive, bobAlive, charlieAlive; shoot(charlieAlive, 1.0/3); if (charlieAlive) { cout << "Aaron missed Charlie!" << endl; shoot(charlieAlive, 0.5); if (charlieAlive) { cout << "Bob missed Charlie so Charlie throws back!" << endl; cout << "Bob has been hit by Charlie!" << endl; bobAlive = false; shoot (charlieAlive, 1.0/3); if (charlieAlive) { cout << "Aaron missed Charlie, so Charlie throws back!" << endl; aaronAlive = false; cout << "The duel is over and Charlie wiped them all out" << endl; return (c++); } } } else if (!charlieAlive) { cout << "Aaron hit Charlie" << endl; do { shoot(aaronAlive, 0.5); shoot(bobAlive, 1.0/3); if (!aaronAlive) { cout << "Bob won!" << endl; return (b++); } else if (!bobAlive) { cout << "Aaron won!" << endl; return (a++); } } while((aaronAlive)&&(bobAlive)); } }
look at the last line of shoot void shoot(bool& targetAlive, double accuracy) { double x; x = (((float)rand() / (float)(RAND_MAX)) * 1.0); if (x < accuracy) { cout << "target is hit!" << endl; targetAlive = false; } else cout << "missed!" << endl; cout << x << endl; targetAlive = true; <<<<==== } no matter what happens before you reset alive to true before exiting just remove that line also move srand to main, you should only call it once.
71,301,988
71,302,465
Shorten variadic parameter pack to N types
I would like to write a class that takes a size N (> 0) and a variable number of arguments (>= N). It should have a constructor that takes N arguments and a member std::tuple which has the same type: template <size_t N, typename... Args> struct Example { // A constructor taking N parameters of type Args[N], initializing the member tuple // (e.g. param 1 has type Args[0], param 2 has type Args[1], ..., // param N has type Args[N-1]) // A tuple with N elements, each corresponding to Args[N] // (e.g. std::tuple<Args[0], ..., Args[N-1]>) //For instance Example<3, int, float, int, bool> should result in constexpr Example(int a, float b, int c): t(a, b, c) {} std::tuple<int, float, int> t; } In general: Is this possible? If not are there viable alternatives? Why does/ doesn't this work? I'm using C++20.
To the extent I understand the question, it simply seems to be asking how to produce a tuple from arguments. Which, using Boost.Mp11, is a short one-liner (as always): template <size_t N, typename... Args> using Example = mp_take_c<N, std::tuple<Args...>>; Rather than Example<3, int, float, int, bool> being some type that has a member tuple<int, float, int> with one constructor, it actually is tuple<int, float int>. If you, for some reason, specifically need exactly a member tuple and exactly the constructor specified, we can do easily enough: template <typename... Ts> struct ExampleImpl { std::tuple<Ts...> t; constexpr ExampleImpl(Ts... ts) : t(ts...) { } }; template <size_t N, typename... Args> using Example = mp_take_c<N, ExampleImpl<Args...>>;
71,302,065
71,302,143
Is there a way to modify another object's member directly from within one object's function?
all! This is my first post, so please be gentle. My code is meant to simulate a rudimentary version of transferring money from one bank account to another. My code is as follows: #include <cstdio> struct Account { virtual ~Account() {} virtual double get_balance() = 0; virtual double set_balance(double amount) = 0; virtual Account* transfer_balance(Account* to, double amount) = 0; long account_id; double balance; unsigned int privileges; }; struct UserAccount : Account { UserAccount(long account_id): account_id{account_id} { printf("Account %ld initialized at %p\n", account_id, this); }; double get_balance() override { return balance; } double set_balance(double amount) override { this->balance = amount; return balance; } Account* transfer_balance(Account* to, double amount) override { to->set_balance(to->get_balance() + amount); this->set_balance(this->get_balance() - amount); return to; } long account_id; double balance { 0 }; unsigned int privileges; }; int main() { UserAccount test_acct_one(23); UserAccount test_acct_two(98); test_acct_one.transfer_balance(&test_acct_two, 200); printf("Balance of Account %ld: %lG\n", test_acct_one.account_id, test_acct_one.get_balance()); printf("Balance of Account %ld: %lG\n", test_acct_two.account_id, test_acct_two.get_balance()); } Output: Account 23 initialized at 0x7fff8e927a40 Account 98 initialized at 0x7fff8e927a00 Balance of Account 23: -200 Balance of Account 98: 200 While this code works, it feels a bit finicky to transfer the values like this: to->set_balance(to->get_balance() + amount); this->set_balance(this->get_balance() - amount); However, when I try to do this: to->balance += amount; balance -= amount; The output turns into: Account 23 initialized at 0x7ffc37b91a40 Account 98 initialized at 0x7ffc37b91a00 Balance of Account 23: -200 Balance of Account 98: 0 As you can see, while Account 23's (the first one's) balance is properly set to -200, Account 98's (the second one's) balance neither increases nor decreases, and I can't understand why. Some explanation of this behavior would be much appreciated.
You've duplicated all your member variables in both types. When you attempt to modify balance directly, it's trying to modify Account::balance, but set_balance and get_balance will use UserAccount::balance since that's available in the scope where the virtual is implemented.
71,302,120
71,302,182
Why does my code ignore a large chunk of itself?
hey I've just started on a school project but can't figure out why the code just ignores a large chunk of itself. (also the code is part of a function inside of "math.h") ill paste the whole segment here so that debugging it is easier. #include <iostream> #include <chrono> #include <thread> #include <algorithm> using namespace std; using namespace chrono; using namespace this_thread; class math { private: unsigned short pts; public: unsigned short questAmount; char diff; short arrEasy[4] = {1, 2, 5, 10}, secondVar, ans, studAns; void questProc() { start: cout << "How hard do you want the questtions to be?" << endl; cout << "(The harder you choose, the larger the numbers you'll have to calculate)" << endl; cout << "1) EASY" << endl; cout << "2) MEDIUM" << endl; cout << "3) HARD" << endl; cout << "4) CALCULATOR MODE LOL" << endl << "~> "; cin >> diff; switch (diff) { case '1': system("cls"); cout << "EASY MODE ACTIVATED" << endl; break; case '2': system("cls"); cout << "MEDIUM MODE ACTIVATED" << endl; break; case '3': system("cls"); cout << "HARD MODE ACTIVATED" << endl; break; case '4': system("cls"); cout << "CALCULATOR MODE ACTIVATED" << endl; break; default: system("cls"); cout << "INPUTED VAL IS EITHER NOT AN INT OR ISN'T IN THE LIST"; //checks only the starting int ignores the rest... sleep_for(0.5s); cout << "."; sleep_for(0.5s); cout << "."; sleep_for(0.5s); cout << "."; sleep_for(0.5s); break; if (diff != 1 && diff != 2 && diff != 3 && diff != 4) { goto start; } } // The following creates the question according to the set difficulty. srand(time(NULL)); // Initializing random seed. switch (diff) { case 1: // Easy Mode: system("cls"); random_shuffle(&arrEasy[0], &arrEasy[4]); // For first var. secondVar = rand() % 10 + 1; // Rand number from 1 to 10 (for second var). ans = arrEasy[0] * secondVar; cout << arrEasy[0] << " * " << secondVar << " = ?" << endl << "~> "; cin >> studAns; break; default: break; } // The following checks if ans is correct. if (studAns == ans) { cout << "WELL DONE!"; } else { cout << "WRONG, CORRECT ANSWER WAS:" << ans; } } }; I wanted it to continue on to actually calculate the question and to then check if I was right or not... here's what I got instead: How hard do you want the questtions to be? (The harder you choose, the larger the numbers you'll have to calculate) 1) EASY 2) MEDIUM 3) HARD 4) CALCULATOR MODE LOL ~> 1 and then: EASY MODE ACTIVATED WELL DONE! that's all it says, despite all the other things its also supposed to do... ps. tell me if you need any more info.
Because of type mismatch! you defined "diff" as a char and use it as such in your switch statement. However, in your second switch statement, you remove the quotes and use it as a number. That causes a char to int conversion according to the ascii table. Look at the decimal field, the number 1 as an int corresponds to a non-printable character that you will rarely see in real life. The character '1' corresponds to 49. Solution: switch(diff){ case '1': //notice the quotations //rest of code break; }
71,302,334
71,302,480
Convert vector<string> to char** for use in execvp
I have a vector named tokens that holds the command in tokens[0] and args as the rest of the vector. I am trying to convert the vector so I can make the call to execvp(args[0], args); Currently args[0] and args just print as memory addresses. char **args = (char**)malloc(tokens.size() * sizeof(string)); char *arg; int i; for(i = 0; i < tokens.size(); i++) { arg = &tokens[i][0]; args[i] = arg; }
I found that the answer lies with adding the NULL terminator to the end of the vector so that execvp knows where to end pvec.data(); This is thanks to Fatih above. std::vector<char*> pvec(tokens.size()); std::transform(tokens.begin(), tokens.end(), pvec.begin(), [](auto& str) { return &str[0]; }); pvec.push_back(NULL); pvec.data(); pid = fork(); // if we enter child process if (pid == 0) { if (execvp(pvec.data()[0], pvec.data()) == -1) { printf("right here officer\n"); } exit(EXIT_FAILURE); }```
71,302,765
71,302,894
Create struct array by a function C++
I want to create a function that creates an array of structures. What I have done is the following: struct Student { char studentNames[128]; unsigned int FN; short selectiveDisciplinesList[10]; unsigned short countOfSelectiveDisciplines; bool hasTakenExams; }; void fillInStudentInfo(Student &student) {...} Student createStudentsArray() { unsigned int countOfStudents; std::cout << "Enter the number of students You are going to write down: " << std::endl; std::cin >> countOfStudents; Student studentsArray[countOfStudents]; for (int i = 0; i < countOfStudents; ++i) { fillInStudentInfo(studentsArray[i]); } return *studentsArray; } However, when in main(), I assign: Student studentArray = createStudentsArray(); I can not access the members of each different struct (f.e. studentArray[i].something). Where does the issue come from? If I do it like this: Student * createStudentsArray() { ... return studentsArray; } with Student * studentArray = createStudentsArray(); My IDE warns me: Address of stack memory associated with local variable returned But I do seem to be able to access the members of each struct. Is that a bad thing?
You really cannot do what you are trying to do in that way: Student createStudentsArray() { ... Student studentsArray[countOfStudents]; ... return *studentsArray; } Firstly, this is using a variable length array, which strictly speaking is invalid C++. My compiler, for example, doesn't allow it. Second, it will only return one Student. Even if it returned them all, its very inefficient because it would have to copy them all, but it doesn't. You tried this: Student *createStudentsArray() { ... Student studentsArray[countOfStudents]; ... return studentsArray; } This is even worse. The memory allocated to that array is released once the function ends. This is what the compiler warned you about. Things seemed to work afterwards, but Very Bad Things(tm) will happen very soon afterwards. Most experienced C++ devs will do this: std::vector<Student> createStudentsArray() { ... std::vector<Student> students(countOfStudents); ... return students; } If you "are not allowed to use vector" (StackOverflow sees that all the time), then do: Student *createStudentsArray() { ... Student *studentsArray = new Student[countOfStudents]; ... return studentsArray; } But you must then delete[] that array once you are finished using it. Footnote - for extra info, if you are really interested. In fact, the experienced devs would do this: std::vector<std::shared_ptr<Student>> createStudentsArray() { ... std::vector<std::shared_ptr<Student> students(countOfStudents); for (int......) { students.push_back(std::make_shared<Student>()); ... } return students; } Now, the vector contains a bunch of smart pointers rather than the actual objects, that is the most efficient way to make arrays (or other containers) of largish objects. std::vector and std::shared_ptr will clean up all the memory for you automatically.
71,303,379
71,305,495
How to assign an enum for a switch case from UserInput string in C++
I'm writing this code that takes in a char userinput and uses the switch statement do execute the respective command. However because C++ switch statements can only read ints and enums, I'm not sure how to incorporate this. The user input must be a char. any ideas? I know charInput >> enumInput doesn't work but I'm not sure what to do. int main(int argc, char** argv) { enum charCommand { i, d, s, n, r, a, m, t, p, l, q }; charCommand enumInput; while (mainLoop) { cout << "enter valid input" endl; char charInput; printf("Enter a command: "); cin >> charInput; charInput >> enumInput; switch (charInput) { case i: { printf("This is case i"); exit(0); } //case i default: { cout << "invalid command, try again!\n"; } } }; }
There's no need for an enum here. switch works with char because char is convertible to int. So if we define a char as such: char c = 'a'; ..and then switch on it: switch (c) This works because 'a' can be converted to int (ASCII value). So this can also be written as: switch (int(c)) // Same as switch (c) Example: #include <iostream> int main(int argc, char** argv) { char input; std::cin >> input; switch (input) { case 'a': std::cout << 'a' << std::endl; break; case 'b': std::cout << 'b' << std::endl; break; case 'c': std::cout << 'c' << std::endl; break; default: std::cout << "Some other key" << std::endl; break; } } The above example works. For your case, I would rewrite your program as: #include <iostream> int main(int argc, char** argv) { while (true) { std::cout << "enter valid input" << std::endl; char charInput; printf("Enter a command: "); std::cin >> charInput; switch (charInput) { case 'i': printf("This is case i"); exit(0); //case i default: std::cout << "invalid command, try again!\n"; break; } }; } Also, consider not using the following in your code: using namespace std; ..as it's considered as a bad practice. For more info on this, look up why is "using namespace std" considered as a bad practice.
71,303,497
71,303,633
My attempt at Row-major order of array is showing correct values but indexing incorrect values
I have made a class called matrix that stores values in a 1D array, but outputs it as a 2D array. I have included print statements to show the exact values supposedly being put into the array however when I use the print function to index it, it shows incorrect value on the second row last index. not entirely sure what I'm doing wrong. #include <iostream> class Matrix { private: int rows{}, cols{}; double *newArr; public: Matrix(int row, int col) { rows = row; cols = col; newArr = new double[rows * cols]; } void setValue(int row, int col, double value) { std::cout << value << std::endl; newArr[row * row + col] = value; } double getValue(int row, int col) { return newArr[row * row + col]; } int getRows() { return rows; } int getCols() { return cols; } void print() { for (int i{}; i < rows; ++i){ for (int j{}; j < cols; ++j){ std::cout << newArr[i * i + j] << " "; } std::cout << std::endl; } } ~Matrix() { delete[] newArr; } }; int main() { Matrix x(3, 4); for (int i{}; i < x.getRows(); i++){ for (int j{}; j < x.getCols(); j++){ x.setValue(i, j, (j+i)/2.0); } std::cout << std::endl; } std::cout << std::endl; x.print(); return 0; }
I changed your indexing logic and it seems okay. Still not getting why you use row * row + col instead of row * cols + col. Dynamic allocated the size of the matrix and layout the 2d matrix into 1d. Then you should use the length to fill the array, not (row index)^2. Live Demo #include <iostream> class Matrix { private: int rows{}, cols{}; double *newArr; public: Matrix(int row, int col) { rows = row; cols = col; newArr = new double[rows * cols]; } void setValue(int row, int col, double value) { std::cout << value << std::endl; newArr[row * cols + col] = value; } double getValue(int row, int col) { return newArr[row * cols + col]; } int getRows() { return rows; } int getCols() { return cols; } void print() { for (int i{}; i < rows; ++i){ for (int j{}; j < cols; ++j){ std::cout << newArr[i * cols + j] << " "; } std::cout << std::endl; } } ~Matrix() { delete[] newArr; } }; int main() { Matrix x(3, 4); for (int i{}; i < x.getRows(); i++){ for (int j{}; j < x.getCols(); j++){ x.setValue(i, j, (j+i)/2.0); } std::cout << std::endl; } std::cout << std::endl; x.print(); return 0; }
71,303,617
71,304,324
c++ testing if one file is older than a set of files
I am creating a cache for some data, but of course I want the cache to become invalid if any of the source files from which the cache is made is modified. TO that effect I made this function: bool CacheIsValid( const std::string& cache_shader_path, const std::vector<std::string>& shader_paths) { // This is really messy because of the std stuff, the short of it is: // Find the youngest file in the shader paths, then check it against the // timestamp of the cached file. std::time_t youngest_file_ts = std::time(nullptr); for(auto file : shader_paths) { std::time_t current_timestamp = std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(fs::last_write_time(file))); double time_diff = difftime(youngest_file_ts, current_timestamp); if(time_diff > 0) youngest_file_ts = current_timestamp; } // All this is doing is comparing the youngest file time stamp with the cache. return fs::exists(cache_shader_path) && (difftime(youngest_file_ts, std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(fs::last_write_time(cache_shader_path)))) < 0); } I don't know what I did wrong but that is always returning true even when the input files are modified. I am checking the timestamps using stat and the files on disk are objectively younger than the cache file, I also tested that the inputs to this function are correct, and they are.
due to you want to find youngest_file_ts -> find most recently timestamp (greater number) of a changing file however double time_diff = difftime(youngest_file_ts, current_timestamp); if(time_diff > 0) youngest_file_ts = current_timestamp; // find greater number one after the for loop youngest_file_ts is oldest timestamp of a changing file therefor (difftime(youngest_file_ts, std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(fs::last_write_time(cache_shader_path)))) < 0) alway true. it should be change like if (shader_paths.empty()) { return false } else { //initialize youngest_file_ts as last_write_time of first element in shader_paths std::time_t youngest_file_ts = std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(fs::last_write_time(shader_paths.at(0))); for (auto file : shader_paths) { std::time_t current_timestamp = std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(fs::last_write_time(file))); double time_diff = difftime(youngest_file_ts, current_timestamp); if (time_diff < 0) youngest_file_ts = current_timestamp; } // All this is doing is comparing the youngest file time stamp with the cache. return fs::exists(cache_shader_path) && (difftime(youngest_file_ts, std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(fs::last_write_time(cache_shader_path)))) < 0); }
71,303,668
71,303,962
Missing type despite forward declaration
I'm trying to create a basic factory function that returns a pointer to a forward-declared class, as follows below: #ifndef EQUATION_PLUGIN_HPP #define EQUATION_PLUGIN_HPP //! \file equation_plugin.hpp // \brief Definition of EquationPlugin #include <string> #include <shared_library.hpp> class Equation; class PluginManager; //! ... class EquationPlugin { friend class PluginManager; private: ... PluginManager *manager; protected: const int nvars; public: EquationPlugin(int n) : nvars(n) {} virtual ~EquationPlugin() = default; virtual Equation* CreateEquation() = 0; }; #endif As you can see, there are two forward declarations: one for Equation, and one for PluginManager. This seems like a pretty basic thing to me, but for some reason I keep getting the following error from g++: error: ‘Equation’ does not name a type 31 | virtual Equation* CreateEquation() = 0; I'm not sure why I'm getting an error with Equation but not with PluginManager. Sometimes these kinds of issues are caused by circular dependencies, but equation_plugin.hpp only has two includes: string, which comes from the STL, and shared_library.hpp, which is a wrapper around shared library functions that depend only on dlfcn.h and string. The header file for PluginManager does forward declare EquationPlugin, but it doesn't make any reference to Equation, and the header file for Equation is independent of both. Therefore, circular dependencies shouldn't be an issue. I'm sort of at a loss for what the issue is at this point. Do any of you have any advice for what might be going on?
The issue is resolved. The error occurs here in a completely independent source file: ... #include <plugin_manager.hpp> #include <plugin.hpp> #include <equation_plugin.hpp> ... The plugin.hpp header, which is included before equation_plugin.hpp (where Equation is forward-declared), defines an enumerator, PluginType, which happens to have an element that was called Equation. I didn't think about it at the time because the EquationPlugin class, prior to refactoring, handled the functionality now present in the Equation class. The compiler made it clear that Equation was not a type, but it didn't really clarify what Equation was, nor did it see anything wrong with me trying to forward declare a class with the same name as an enumerator element. Some things that can be done in the future to avoid these sorts of issues: Pick consistent style conventions that will minimize name clashes between different components of your code; i.e., don't use camel case for your enumerators if you're already using camel case for class names. Don't pollute the global namespace with non-class names if you can avoid it. Hide your non-class functions and enumerators inside namespaces where reasonable. TL;DR: these sorts of errors can occur if the name of a class clashes with an enumerator or variable elsewhere, and the compiler might not always explain what that name is already reserved for.
71,303,671
71,304,458
How to call Python from C++?
From the docs : cppyy is an automatic, run-time, Python-C++ bindings generator, for calling C++ from Python and Python from C++. (Emphasis mine) I don't see any instructions for doing the same, however, so is it possible to call Python via C++ using cppyy?
As a qualifier, since I don't know from where you obtained cppyy, the main code that was at the time the reason for typing that sentence does not exist in cppyy master, but does exist in its historic home of PyROOT. This so-called "class generator" plugin allows Cling to "see" Python classes as C++ classes, for straightforward callbacks and even inheritance of C++ classes from Python ones. See this publication (page 3) for some examples: https://www.researchgate.net/publication/288021806_Python_in_the_Cling_World This code was not ported over to cppyy standalone b/c the class generator relies on interactive use (specifically, dynamic scopes), so only works from Cling, not compiled code, and there is no way (yet) to drop into the Cling prompt from Python (vice versa works). The reason why that sentence is still there even without the class generator, is that cppyy has since grown a multitude of other ways to call Python from C++ (these have been backported into PyROOT). Examples include C-style function pointers, C++ std::function<> objects, lambdas, and cross-language inheritance. Moreover, these can all be used by importing cppyy into embedded Python (and thus be used from compiled C++). See e.g. these examples in the documentation: callbacks and cross-inheritance. Cross-inheritance is probably the easiest to use: just define an abstract interface, implement it in Python, pass the pointer to C++ and use it like you would with any pointer-to-interface in C++. For callbacks, declare an extern function pointer (or std::function object) in a header, pass that in a cppyy.include in embedded Python, assign a Python function to that pointer, then call it in C++ as desired. Callbacks can be made quite sophisticated, assuming that the C++ side can handle it. For example, by providing annotations on the Python side, Python functions can instantiate C++ function pointer templates. Take the completely generic callback in C++ below, which accepts any arguments and producing any result: >>> import cppyy >>> cppyy.cppdef("""\ ... template<typename R, typename... U, typename... A> ... R callT(R(*f)(U...), A&&... a) { ... return f(a...); ... }""") True >>> def f(a: 'int') -> 'double': ... return 3.1415*a ... >>> cppyy.gbl.callT(f, 2) 6.283 >>> def f(a: 'int', b: 'int') -> 'int': ... return 3*a*b ... >>> cppyy.gbl.callT(f, 6, 7) 126 >>> The final way of calling from C++ into Python is indeed not documented b/c it is (still) only available for CPython/cppyy, not PyPy/_cppyy and the naming is implementation-specific as well: CPyCppyy/API.h. This header is meant to be included in C++ code, allowing the boxing and unboxing of cppyy-bound instances from C++, custom converters and executors, memory management, and parameter packing for stub functions. There are also a couple of convenience functions for dealing with one-offs. For example: import cppyy def pyfunc(): return 42 cppyy.cppdef("""\ #include "CPyCppyy/API.h" int cppfunc() { return (int)CPyCppyy::Eval("pyfunc()"); }""") print(cppyy.gbl.cppfunc()) (although the example here is run from Python for convenience, this can all be called from embedded Python in compiled C++ as well).
71,303,695
71,304,819
How to make a QTimer as Idle timer in qt using CPP
I am new to Qt programming, I want to make the timer an idle timer. The question is whether just setting the timer->start(0) will make the timer an idle timer? How can I know it's an idle timer.
I'd like to repeat the concerns of @Jeremy Friesner: On a general-purpose/multitasking OS (such as Qt usually runs under) you want to minimize your app's CPU usage so that any other programs that may be running can use those leftover CPU cycles (or in the case of a battery-powered device, so that the battery can be conserved). An app that is constantly using CPU cycles while idle would be considered buggy. An application with timeout 0 occupies (more than) one core permanently and causes a high currency consumption. Here we go: a QTimer with interval 0: #include <QtWidgets> // main application int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // setup GUI QWidget qWinMain; qWinMain.setWindowTitle("QTimer - timeout 0"); QVBoxLayout qVBox; QLabel qLblText("Attention!\nThis may cause ventilation noise."); qVBox.addWidget(&qLblText); QLabel qLblI; qVBox.addWidget(&qLblI); qWinMain.setLayout(&qVBox); qWinMain.show(); QTimer qTimer; qTimer.setInterval(0); ushort i = 0; // install signal handlers QObject::connect(&qTimer, &QTimer::timeout, [&]() { ++i; if (i) qLblI.setText(QString("i: %1").arg(i)); else app.quit(); }); // runtime loop qTimer.start(); return app.exec(); } Output: The interval 0 makes the timer immediately due. This means that a timeout event is appended to the event queue. Thus, I expect the queue permanently filled with timeout and paint events (for update of qLblI) until the application exits. I once used such an idle event in the past (before I started to use Qt). I intended to combine the UI event loop with polling "events" from a different source (and lacking any idea about a better alternative). Thereby, the polling function provided itself a time-out option. Thus, the call of the poll function suspended itself the process until either an event came in or the timeout was reached. The most intricate thing was to achieve somehow a load balancing as I tried to distribute the available time equally between the UI and the processing of the other event source. (This was important for the situation where UI events were approaching in high frequency concurrently with the other event source.) However, I doubt that such a fiddling would be still necessary in Qt. For such a concurrency, there are better options e.g. to run a blocking function in a separate thread.
71,303,725
71,304,078
Poco installed with vcpkg is missing ssl related header files
I use the command to install Poco. vcpkg.exe install openssl:x64-windows And openssl x64 is installed. When i use visual studio 2022, it show me that it can't found the file Poco/Net/SSLManager.h, and Other libraries related to ssl. Why is this happening? #include "Poco/StreamCopier.h" #include "Poco/URI.h" #include "Poco/Exception.h" #include "Poco/SharedPtr.h" #include "Poco/Net/SSLManager.h" #include "Poco/Net/KeyConsoleHandler.h" #include "Poco/Net/ConsoleCertificateHandler.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/Net/HTTPRequest.h" #include "Poco/Net/HTTPResponse.h" #include <memory> #include <iostream>
Ok guys, i get the answer. when you install poco, just add this: vcpkg install poco[netssl]
71,304,093
71,304,357
Can I default class member functions and specify extra specifiers?
I have a problem where if I use my class as the element type in a vector it doesn't move it but rather constructs it and tries to copy assign it (I believe because the compiler sees certain functions as throwing exceptions). I don't want to redefine my own move constructor every time this happens, can I default the move constructor but specify that it's noexcept? struct QueueSubmission { QueueSubmission(VulkanFence is_completed_fence) : is_completed_fence(is_completed_fence) {} QueueSubmission(QueueSubmission&& other) noexcept = default; QueueSubmission& operator=(QueueSubmission&& other) noexcept = default; /* CommandBufferUniquePointer cannot be copied, but only moved */ std::vector<CommandBufferUniquePointer> command_buffers_submitted; };
Yes, if functions are defaulted on their first declaration without noexcept specifier, then they will be noexcept(true) if and only if they don't contain anything potentially throwing. But if you add a noexcept specifier this will override it. Note my comments under your question though.
71,304,161
71,304,244
Why SFINAE report error in function overloading
Follwing code can't compile,I just want testing SFINAE,why it can't compile? #include <type_traits> template<typename T> class TestVoid { template<std::enable_if_t<std::is_void_v<T>> * = nullptr> void func() { std::cout << "void\n"; } template<std::enable_if_t<!std::is_void_v<T>> * = nullptr> void func() { std::cout << "none void\n"; } }; int main() { TestVoid<void> t; return 0; }
When you instantiate the class template, all of the member function declarations must be valid. In your case, one of them won't be. Instead, you can delegate func to another function template. live link template<typename T, std::enable_if_t<std::is_void_v<T>> * = nullptr> void func() { std::cout << "void\n"; } template<typename T, std::enable_if_t<!std::is_void_v<T>> * = nullptr> void func() { std::cout << "none void\n"; } template<typename T> class TestVoid { public: void func_member() { func<T>(); } }; Or, if you want to keep the actual implementation of func as a member function: live link template<typename T> class TestVoid { public: void func_member() { func<T>(); } private: template<typename U, std::enable_if_t<std::is_void_v<U>> * = nullptr> void func() { std::cout << "void\n"; } template<typename U, std::enable_if_t<!std::is_void_v<U>> * = nullptr> void func() { std::cout << "none void\n"; } };
71,304,262
71,304,836
dynamic allcocation object and int c++
hello I have a doubt how does the code below works?? #include <iostream> using namespace std; int main() { int* arr = new int; arr[0] = 94; arr[1] = 4; cout << arr[0] << endl; } and why does this shows me a error what should I do #include <iostream> using namespace std; struct test { int data; }; int main() { test* arr = new test; arr[0] -> data= 4; arr[1] -> data= 42; cout << arr[0]->data << endl; }
In your code: #include <iostream> using namespace std; int main() { int* arr = new int; arr[0] = 94; // This will work arr[1] = 4; // This will cause undefined behaviour cout << arr[0] << endl; } Int the above code, arr is a pointer to a single int, so you can access that one int using either: arr[0] *arr ..but arr1 won't work as there is not enough memory allocated for the array. To fix this, you must allocate more memory for arr: int* arr = new int[2]; ..and to change the size of arr: int arr_size = 2; int* arr = new int[arr_size]; // size of arr = 2 arr[0] = 12; arr[1] = 13; int* new_arr = new int[arr_size + 1]; for (int i = 0; i < arr_size; i++) { new_arr[i] = arr[i]; } delete[] arr; arr = new_arr; // size of arr = 3 But all of this gets computationally expensive and time-consuming when arr has a huge number of elements. So I recommend using C++'s std::vector: Your 2'nd program using std::vector: #include <iostream> #include <vector> struct test { int data; }; int main() { std::vector<test> vec{ test(4), test(42) }; std::cout << vec[0].data << std::endl; } For more info on std::vector, click here. Also, consider not using the following line in your code: using namespace std; ..as it's considered as bad practice. For more info on this, look up to why is "using namespace std" considered as bad practice.
71,305,813
71,305,920
Is it undefined behavior to compare a character array char u[10] with a string literal "abc"
I came across this question on SO, and this answer to the question. The code is as follows: int main() { char u[10]; cout<<"Enter shape name "; cin>>u; if(u=="tri") //IS THIS UNDEFINED BEHAVIOR because the two decayed pointers both point to unrelated objects? { cout<<"everything is fine"; } else { cout<<"Not fine"; } return 0; } I have read in the mentioned answer that, both u and "tri" decay to pointers to their first element. My question is that, now is comparing these two decayed pointers undefined behavior because these pointers point to unrelated objects? Or the program is fine/valid(no UB) and because the pointers have different values, the else branch will be executed?
Standard says: [expr.eq] The == (equal to) and the != (not equal to) operators group left-to-right. The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the operands... Hence, we are comparing pointers to the respective arrays. If at least one of the operands is a pointer, ... Comparing pointers is defined as follows: If one pointer represents the address of a complete object, and another pointer represents the address one past the last element of a different complete object,72 the result of the comparison is unspecified. [does not apply since neither pointer is past last element] Otherwise, if the pointers are both null, both point to the same function, or both represent the same address, they compare equal. [does not apply since neither is null, neither point to functions, nor represent same address] Otherwise, the pointers compare unequal. [applies] The behaviour is defined and else branch will be unconditionally executed. Unconditionally unconditional if-statements imply that there is probably a bug; most likely the author was trying to compare the content of the arrays, which the operator does not do. "warning: comparison with string literal results in unspecified behavior" I believe that this warning message is slightly misleading. Comparison with two string literals would be unspecified: if ("tri" == "tri") It's unspecified whether this conditional is true or false.
71,306,043
71,306,334
verifyExists function is throwing a crazy amount of errrors
I'm making a wordle program for a class assignment and the basic concept is to load all 5 letter words in the English language from a text file into an array, then pick one randomly to be the correct one, and I have that part correct (probably isn't that efficient but it works for now). I need to verify the user input that the 5 letter word they entered is actually in that array. For example they enter "djghd", which isn't a word that would be in that array. here is the code that I used: #include <string> #include <fstream> #include <ctime> using namespace std; bool verifyExists(string word, string verifyArr) { for (int i = 0; i < 2315; i++) { if (word == verifyArr[i]) { return true; } else { return false; } } } void playGame(string word, string arr) { string guessWord; cout << "Ok. I am thinking of a word with 5 letters." << endl; cout << "What word would you like to guess?" << endl; getline(cin, guessWord); verifyExists(guessWord, arr[2315]); cout << guessWord << endl; } int main() { string word; int loop = 0; string wordArray[2315]; ifstream myfile ("proj1_data.txt"); cout << "Welcome to UMBC Wordle" << endl; if (myfile.is_open()) { cout << "Your file was imported!" << endl; cout << "2315 Words imported" << endl; while (! myfile.eof()) { getline(myfile, word); wordArray[loop] = word; loop++; } myfile.close(); } int max; max = 2315; srand(time(0)); string chosenWord = wordArray[rand() % max]; playGame(chosenWord, wordArray[2315]); return 0; } When I try to compile it, it throws a ton of errors (Which might just be the compiler I'm using) and i need to use infinite scroll to get through them all so I cant add them here. They only show up after I added the verifyExists function so I know that's the source of the error I just don't know what is causing it. I'm also not allowed to use pointers so that makes it difficult. Any help is greatly appreciated, thank you.
Your code has a lot of problems in it: 1.Your includes are wrong and some of them are missing: #include <string> #include <fstream> #include <ctime> // There's no need of this. Just #include <iostream> and you should be good Here are the correct includes: #include <iostream> #include <string> #include <stream> 2.Max can be defined globally as const int: #include <fstream> const int max = 2315; 3.You're comparing std::string with char: word == verifyArr[i] ..so change your function definition to: bool verifyExists(std::string word, std::string verifyArr[max]) Same goes for playGame(): void playGame(std::string word, std::string arr[max]) 4.Your file accessing can be way better: std::string word; int loop = 0; // I have defined these variables here so that they get destroyed after the code inside `if (myfile.is_open())` ends. while (std::getline(myfile, word)) { wordArray[loop++] = word; } 5.Return value of verifyExists() ignored verifyExists(guessWord, arr); Replace it with: if (verifyExists(guessWord, arr)) { // Word exists std::cout << guessWord << std::endl; } else { // Word does not exist } 6.using namespace std is considered as bad practice Click here to know why. So after all of these fixes, here is the correct code: Final Code: #include <iostream> #include <string> #include <fstream> const int max = 2315; bool verifyExists(std::string word, std::string verifyArr[max]) { for (int i = 0; i < max; i++) { if (word == verifyArr[i]) { return true; } } return false; } void playGame(std::string word, std::string arr[max]) { std::string guessWord; std::cout << "Ok. I am thinking of a word with 5 letters." << std::endl; std::cout << "What word would you like to guess?" << std::endl; std::getline(std::cin, guessWord); if (verifyExists(guessWord, arr)) { // Word exists std::cout << guessWord << std::endl; } else { // Word does not exist } } int main() { std::string wordArray[max]; std::ifstream myfile("proj1_data.txt"); std::cout << "Welcome to UMBC Wordle" << std::endl; if (myfile.is_open()) { std::string word; int loop = 0; while (std::getline(myfile, word)) { wordArray[loop++] = word; } std::cout << "Your file was imported!" << std::endl; std::cout << "2315 Words imported" << std::endl; myfile.close(); } srand(time(0)); std::string chosenWord = wordArray[rand() % max]; playGame(chosenWord, wordArray); return 0; }
71,306,261
71,313,745
Correct way to access functions defined in .exe from .dll
I have a VS solution with an executable and a DLL. In the executable (MAIN): __declspec(dllexport) void testExe() { printf("Hello from EXE"); } __declspec(dllimport) void DoStuff(); int main() { DoStuff(); } while in the .dll (DLL) __declspec(dllimport) void testExe(); __declspec(dllexport) void testDll() { printf("Hello from Dll"); } __declspec(dllexport) void DoStuff() { testExe(); testDll(); } I linked Dll.lib in MAIN.exe, but I still get a linking error: error LNK2019: unresolved external symbol "__declspec(dllimport) void __cdecl testExe(void)" referenced in function "void __cdecl DoStuff(void)" How can I achieve this?
Use GetModuleHandleW(NULL) to get the module handle of the executing EXE. Then use GetProcAddress to get the address of the function. Watch out for C++ name mangling and calling conventions (using __stdcall will add something like @4) changing the function name. To avoid the function name changing, use extern "C" before exporting it. Example: In main.cpp for the EXE: //Want to use extern "C" so that the function name doesn't get mangled using C++ mangling rules extern "C" { __declspec(dllexport) int DoStuff(int param1, int param2); } In the DLL that imports from the EXE: //Declare a function pointer type named "DoStuff_FUNC", this makes it a lot easier to import functions typedef (int DoStuff_FUNC)(int param1, int param2); int DoStuff_WithinDll(int param1, int param2) { //Get the module handle from the executing EXE HMODULE module = GetModuleHandleW(NULL); //Type-cast "FARPROC" to our desired function type DoStuff_FUNC DoStuff = (DoStuff_FUNC)GetProcAddress(module, "DoStuff"); if (DoStuff != NULL) { return DoStuff(param1, param2); } return -1; }
71,306,268
71,306,446
Why is the return type of std::rand() not an unsigned int?
std::rand said, int rand(); Returns a pseudo-random integral value between ​0​ and RAND_MAX (​0​ and RAND_MAX included). Since it is guaranteed that a non-negative integer will be returned, why the return type is signed? I am not talking about if we should use it here. Is it a historical issue or some bad design?
There is much debate about unsigned. Without going too much into subjective territory, consider the following: What matters is not whether the value returned from rand() cannot be negative. What matters is that rand() returns a value of a certain type and that type determines what you can do with that value. rand() never returns a negative value, but does it make sense to apply operations on the value that make the value negative? Certainly yes. For example you might want to do: auto x = rand() % 6 - 3; If rand() would return an unsigned then this would lead to confusing bugs in code that looks ok. Using unsigned for example for indices is a different story. An index is always positive. If you want to apply operations to it that turn the value negative then it is not an index anymore. rand() % 6 -3 on the other hand is a random number, be it positive or not. A type is more than the range of values it can represent. Signed and unsigned integers have different semantics. Note that C++20 introduced std::ssize. It's the size of a container, it can only be positive. Nevertheless it is signed. That's one example for positive values that are signed merely to allow signed arithmetics. Also it was not an option to change std::size to return a signed, because that would break existing code. And as a sidenote consider that Java has no unsigned integer type at all, because unsigned arithmetics were considered too confusing.
71,306,988
71,307,308
Use AllocateAndGetTcpExTableFromStack function in c#
How can I use that function in c# I need to use windows IP helper, to get specific process connections cause it wouldn't work like this [DllImport("Iphlpapi.dll", CharSet = CharSet.Ansi)] public static extern int AllocateAndGetTcpExTableFromStack(); Cause I get the err: System.EntryPointNotFoundException: 'Unable to find an entry point named 'AllocateAndGetTcpExTableFromStack' in DLL 'Iphlpapi.dll'.'
According to the documentation, this function is 'no longer available'. The linked page suggests alternatives, you should use one of those. This function is no longer available for use as of Windows Vista. Instead, use the GetTcpTable or GetExtendedTcpTable function to retrieve the TCP connection table.
71,307,199
71,349,841
SFML square's off set
I am new to sfml/c++. I am trying to display a yellow square on a chess board at piece's first and last location. I succeed in that but my square isn't completely overlapped on the chess board's square. It's look kind an unnatural. here's my texture class and main function(with photo). main function: #include <SFML/Graphics.hpp> #include <SFML/Graphics/RectangleShape.hpp> #include "TEXTURE.h" #include "SOUND.h" using namespace sf; int main() { TEXTURE tex; SOUND sou; RenderWindow Window(VideoMode(850,850),"JIMMY CHESS",Style::Titlebar|Style::Close); Window.setVerticalSyncEnabled(true); Window.setFramerateLimit(60); tex.setimages(); tex.setpieces(); while(Window.isOpen()) { Event e; Vector2i POS = Mouse::getPosition(Window); while(Window.pollEvent(e)) { if(e.type==Event::Closed) { Window.close(); } tex.liftpiece(e,POS); } tex.droppiece(POS); Window.clear(); Window.draw(tex.s1); Window.draw(tex.yellown); Window.draw(tex.yellowo); for(int i=0; i<32; i++) { Window.draw(tex.s2[i]); } //layer 1 : chess board Window.display(); } return 0; } texture.h :(not full texture.h) Texture board,piece,yellow1,yellow2; Sprite s1; Sprite s2[32]; Sprite yellown,yellowo; texture's function : void TEXTURE::setimages() { board.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\DAIICT\\CODE BLOCKS PROJECT\\CHESS\\images\\chessboard.png"); piece.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\DAIICT\\CODE BLOCKS PROJECT\\CHESS\\images\\chesspiece.png"); yellow1.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\DAIICT\\CODE BLOCKS PROJECT\\CHESS\\images\\OLDsquare.png"); yellow2.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\DAIICT\\CODE BLOCKS PROJECT\\CHESS\\images\\OLDsquare.png"); s1.setTexture(board); s1.setOrigin(425,425); s1.setPosition(425,425); yellown.setTexture(yellow1); yellowo.setTexture(yellow2); yellown.setTextureRect(IntRect(10,10,106,106)); yellowo.setTextureRect(IntRect(10,10,106,106)); piece.setSmooth(true); for(int i=0; i<32; i++) { s2[i].setTexture(piece); } } this is the square looks like : this yellow square isn't fitting into the chess board's square so please give an suggestion on that!thank you for help and sorry for bad inglish ;)
First, you don't need to load 4 texture files, since you are loading twice the same one (OLDsquare.png). You can just use setTexture() with the same sf::Texture for the two Sprites yellown and yellowo.(You can even make it only one file to load by putting all your textures in one file and telling the Sprites where to get their textures in the file with sprite.setTextureRect(), which you already do for the yellown and yellowo sprites) Secondly I recommend that you do not use sf::Sprite but sf::RectangleShape instead, since there is basically no difference except that RectangleShape are lighter and more easy to use (especially when it comes to setting size). Third, I think your code organization is a little bit weird. You probably should have a Chessboard class and a piece class, with their own methods instead of having a "TEXTURE" class with everything in it. Lastly, I do not seem to see where you set the position of the pieces and the yellown, maybe it's in the setPieces() method ? Beause the problem is likely coming from here.
71,307,295
71,307,513
Code using core issue 2118: why doesn't Clang see the function definition?
Sample code (taken from here [uses core issue 2118], slightly modified): #include <type_traits> template<int N> struct tag{}; template<typename T, int N> struct loophole_t { friend auto loophole(tag<N>) { return T{}; }; }; auto loophole(tag<0>); struct detector { template <typename T, int = sizeof(loophole_t<T, 0>)> operator T(); }; template <typename T, int = sizeof(T{detector{}})> constexpr auto get_type() { return loophole(tag<0>{}); } typedef double T; struct test { T x; }; int main(void) { static_assert( std::is_same<T, decltype(get_type<test>())>::value, "xxx" ); return 0; } Invocations: $ gcc t0.cpp -std=c++14 -pedantic -Wall -Wextra <nothing> $ icc t0.cpp -std=c++14 -pedantic -Wall -Wextra <nothing> $ clang t0.cpp -std=c++14 -pedantic -Wall -Wextra <source>:22:12: error: function 'loophole' with deduced return type cannot be used before it is defined return loophole(tag<0>{}); ^ <source>:11:6: note: 'loophole' declared here auto loophole(tag<0>); $ cl t0.cpp /std:c++14 /Za <nothing> Why doesn't Clang see the function definition? What the standard says?
In your code return loophole(tag<0>{}); is not dependent on a template parameter. I am unsure at the moment whether the standard requires that the type of loophole(tag<0>{}) be deduced at the point of the template definition, which would make the program ill-formed, but even if it doesn't, this is ill-formed, no diagnostic required. [temp.res.general]/8.4 requires that a hypothetical instantiation of the template get_type immediately after its definition shall not be ill-formed due to a non-dependent construct. However, as mentioned above, the call to loophole(tag<0>{}) is non-dependent and could be ill-formed at this point due to the missing definition of loophole required to deduce the placeholder return type, if the default template argument is not used.
71,307,728
71,307,765
Loop does not continue correctly
I have been programming in C++ for the past 3 years, and I have always used the continue keyword in loops with success. But right now, a simple code of mine with continue is not working properly. Here is the code that is showing the problem: int main() { int num = 2, result = 0; while (num > 1 && num < 50) { if (num % 2 != 0) { result += num; } else { continue; } num++; } cout << "The result is: " << result << endl; return 0; } As stated above, this does not print anything on the console. When I remove the else statement with continue in it, it successfully calculates the result and prints the said result. Does anyone have any idea why the given code is not working correctly (or why the loop in it does not break)? Any sound answer would be much appreciated.
Loop is indeed continuing (continue works properly) correctly Initially, num = 2, so if condition fails and goes to else. So it will call continue. Then again the loop starts from the beginning with num = 2. This continues forever. In short, num value is not changing and if condition always fails.
71,307,892
71,310,222
What is the difference between non-export declarations and declarations in private module fragment?
On cppreference.com about modules it says about export: Module interface units can export declarations and definitions, which can be imported by other translation units. [ … ] All declarations and definitions exported in the module interface units of the given named module will be available in the translation unit using the import declaration. Guessing from that, I'd export everything that users of the module want or need to use it. Everything not exported is an implementation detail of the module and none of the importers’ concern. It also tells me that a private module fragment [ … ] allows a module to be represented as a single translation unit without making all of the contents of the module reachable to importers. What is the difference between putting something in the private module fragment than to just not exporting it? I guess there’s a difference between “available in the translation unit using the import declaration” and “reachable to importers”. But what is that difference from a practical point of view? As a guideline, when would I put something in the private module fragment and when just not exporting it? (Highlight inside quotes by me.)
What is the difference between putting something in the private module fragment than to just not exporting it The principle difference in terms of implementation is that non-exported definitions that are in a module interface can be imported by other pieces of code that are part of the same module (implementation units and other interface units of the module). They will have access to those declarations even though you don't export them. As such, those declarations must live (to some degree) in whatever file the compiler uses for that module. By contrast, private module fragment code doesn't contribute to any accessible interface of the module. It acts like a module implementation unit. But here's the thing: you wouldn't be able to tell the difference. Why? If the primary module interface has a private module fragment, there cannot be any other files that are part of the same module. That's expressly forbidden. The private module fragment as a tool exists to support cases where you want to ship a complete module as a single file. There's nothing that a private module fragment can do which a module implementation unit cannot. So if there's a possibility of a private module fragment (ie: it's a single-file module), code that imports the module cannot see the unexported declarations. The main purpose behind the private module fragment is that it is impossible to export things from within it. This keeps you from accidentally doing that in your single-file implementation.
71,308,047
71,309,240
Gmock: save a pointer of a passed argument or compare by address in expected call
Suppose I have a method void Mock::foo(const A& obj); and I want to check that it was called exactly with the object obj rather than its copy: A obj; EXPECT_CALL(mock, foo(obj)); mock->foo(obj); How can I check this? I found Address(m) matcher here. But I cannot find it in ::testing, i.e. it does not compile.
As mentioned in comments, ::testing::Address() matcher was introduced in GoogleTest 1.11. You can use instead ::testing::Ref() matcher, which does the same thing underneath (comparing addresses) and is available since at least GoogleTest 1.8 (see it online): #include <gmock/gmock.h> struct Data {}; struct Mock { MOCK_METHOD(void, foo, (const Data& d), ()); }; struct ClassUnderTest { Mock* dependency; void methodUnderTest(const Data& d) { dependency->foo(d); } void methodThatCopies(const Data& d) { Data copy = d; dependency->foo(copy); } }; TEST(X, Correct) { Mock m; Data d; ClassUnderTest uut {&m}; EXPECT_CALL(m, foo(::testing::Ref(d))); uut.methodUnderTest(d); } TEST(X, Fail) { Mock m; Data d; ClassUnderTest uut {&m}; EXPECT_CALL(m, foo(::testing::Ref(d))); uut.methodThatCopies(d); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
71,308,403
71,308,495
How to replace characters of a string in c++ with a recursive function?
Hello I'm a beginner in cpp programming. I was reading some examples of cpp programs and i see this question but i couldn't solve it : There's an algorithm below starting from 0 as each step that goes forward you should replace all 0's with 01 and 1's 10. The input is the number of stage and the output is the number that generates solve this with recursive function. Here is the example: 1)0 2)01 3)0110 ... Input:3 Output:0110 I tried this: string generate(string &algorithm, int n) { if (n <= 0) return algorithm; //confused? } int main() { string algorithm = "0"; string new_algorithm; long long int n, k; cin >> n >> k; new_algorithm = generate(algorithm, n); return 0; } It should be in recursive form but I can't do it straight too! Any help would be appreciated!
The number of recusions is given so the function will look something like this: std::string replace_recursive(const std::string& in, int n) { if (n <= 0) return in; std::string next = replace(in); return replace_recursive(next,n-1); } It has a stop condition, it executes a single step (by calling replace) and it has the recursive call. All you need to add is going from in to next. For this it is easiest to use a range based loop and construct the new string by appending. I am trying to not give away the whole solution: std::string replace(const std::string& in) { std::string result; for (const auto& c : in) { if (c == ....) result += " ... "; else if (c = ....) result += " .... "; } return result; }
71,308,817
71,309,245
Capturing lambda and move assignable
I am confused by why a capturing lambda is not move assignable, but its manual definition (as struct with operator()) is. Consider the following simplified code: struct Environment { Environment(std::unique_ptr<int>&& p): ptr(std::move(p)) {} std::unique_ptr<int> ptr; }; class LambdaCPPInsights { public: inline /*constexpr */ void operator()() const { } private: std::shared_ptr<Environment> env; public: LambdaCPPInsights(const std::shared_ptr<Environment> & _env) : env{_env} {} }; constexpr const char* btos(bool b) { return b ? "true" : "false"; } int main() { auto env = std::make_shared<Environment>(std::make_unique<int>(4)); std::cout << "True lambda is move-assignable: " << btos(std::is_move_assignable_v< decltype([env = env]() {}) >) << std::endl; std::cout << "Manual lambda is move-assignable: " << btos(std::is_move_assignable_v< LambdaCPPInsights >); return 0; } The class LambdaCPPInsights is the translated (and then renamed) lambda struct as given by cpp insights, should therefore be the same thing as the lambda defined by [env = env]() {}. However, the output of the previous code under gcc 11.2 and c++20 is: True lambda is move-assignable: false Manual lambda is move-assignable: true The example on godbolt is found here: https://godbolt.org/z/Yx3n9eGj5 What am I missing?
A lambda with a capture has a deleted copy assignment operator, which also implies that it has no implicit move assignment operator. See [expr.prim.lambda.closure]/13. Your LambdaCPPInsights is not correctly reproducing the closure type. It should explicitly default the copy and move constructors, and explicitly delete the copy assignment operator.
71,308,999
71,309,211
Iomanip setprecision() Method Isn't Working as It Should Only on the First Line, Why?
So I'm writing a program to count the execution time of a function using clock and I used iomanip to change the output to decimal with 9 zeros. This is the code that I am using: #include <time.h> #include <iomanip> using namespace std; void linearFunction(int input) { for(int i = 0; i < input; i++) { } } void execution_time(int input) { clock_t start_time, end_time; start_time = clock(); linearFunction(input); end_time = clock(); double time_taken = double(end_time - start_time) / double(CLOCKS_PER_SEC); cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9); cout << " sec " << endl; } int main() { execution_time(10000); execution_time(100000); execution_time(1000000); execution_time(10000000); execution_time(100000000); execution_time(1000000000); return 0; } And the output shows: Time taken by function for input = 10000 is : 0.000000 sec Time taken by function for input = 100000 is : 0.001000000 sec Time taken by function for input = 1000000 is : 0.002000000 sec Time taken by function for input = 10000000 is : 0.038000000 sec Time taken by function for input = 100000000 is : 0.316000000 sec Time taken by function for input = 1000000000 is : 3.288000000 sec As you can see, the first time I call the function, it doesn't follow the setprecision(9) that I wrote. Why is this and how can I solve this? Thanks you in advance.
Look at the following line properly: cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9); See? You are setting the precision after printing out time_taken. So for the first time, you don't see the result of setprecision(). But for the second time and onwards, as setprecision() has already been executed, you get the desired decimal places. So to fix this issue, move setprecision() before time_taken as such: cout << "Time taken by function for input = " << input << " is : " << fixed << setprecision(9) << time_taken; ..or you can also do something like this: cout.precision(9); cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken; Also, consider not using the following line in your code: using namespace std; ..as it's considered as a bad practice. Instead use std:: every time like this: std::cout.precision(9); std::cout << "Time taken by function for input = " << input << " is : " << std::fixed << time_taken; For more information on this, look up to why is "using namespace std" considered as a bad practice.
71,309,239
71,309,644
solve clang-12 overloaded-virtual warning
The code below gives a clang-12 warning: warning: 'foo::TIFFFormat::encodePixels' hides overloaded virtual function [-Woverloaded-virtual] What can I do to solve the problem described by this warning ? namespace foo { struct bar { int k; }; class IImageFormat { public: virtual ~IImageFormat() = default; virtual bool encodePixels(void) = 0; virtual bool encodePixels(bar pixels) = 0; }; class ImageFormat : public IImageFormat { public: bool encodePixels(bar pixels) override; }; bool ImageFormat::encodePixels(bar pixels){ (void)pixels; return false; } class TIFFFormat : public ImageFormat { public: bool encodePixels() override; }; bool TIFFFormat::encodePixels(){ return false; } } foo::TIFFFormat tf;
Declaring one of the two overloads in the derived class, but not the other, will cause name lookup from the derived class to find only the one declared in the derived class. So with your code you will not be able to call e.g. tf.encodePixels(foo::bar{}). If you don't want to repeat all overloads in the derived class, you can import all of them via a using declaration in TIFFFormat: using ImageFormat::encodePixels; If you don't care or intent the overload to not be reachable from the derived class, then the warning is not relevant to you.
71,309,247
71,310,482
conditional execution path on static class trait
I have problems finding an adequate solution in the attempt to implement an new API alternative to an existing API, which I still want to support for backwards-compatibility; let this be my old API: typedef int[3] Node; template <class T> struct convert{ static std::pair<bool, T> decode(Node node); } //and a call to this construct here template<typename T> T decode_for_me(Node node) { return convert<T>::decode(node).second; } //with a specialization, for example a custom type struct custom_type {int a; int b;}; template<> struct convert<custom_type>{ static std::pair<bool, custom_type> decode(Node node) { custom_type c; c.a=node[0]; c.b=node[1]; return std::make_pair(true, c); }; }; int main() { Node node = {1,2}; decode_for_me<custom_type>(node); return 0; } now is would like to change a convert::decode to a little bit more slim signature and refresh the API for further types implemented: class alt_type { int x; int y; int z; alt_type(int x, int y, int z) : x(x), y(y), z(z) {}; } template<> struct convert<alt_type>{ static alt_type decode_new_api(Node node) {return {node[0], node[1], node[2]};}; } how would i now go about to implement a conditional switch on the class-layout/trait of convert<T> to select the correct call-path, replacing decode_for_me<T>() as: template<typename T> T decode_for_me(Node node) { if constexpr ( "has_trait<convert<T>, "decode">" ) //<<<< return convert<T>::decode(node).second; if constexpr ( "has_trait<convert<T>, "decode_new_api">" ) // <<<< return convert<T>::decode_new_api(node); throw std::runtime_error(); } I researched some similar questions and answers dealing with this in SFINAE varying from template constructs over use of decltype and declval. However, all those deal with member functions, while here I am interested in static evaluation. Also I could get none of them to work for me. Thanks for any help!
I don't know a way to solve this problem with a single type-traits that receive the name of the method (decode or decode_new_api) as argument. But, if you accept different tests for different methods, a possible solution is a couple of declared (no need to define) functions to test "declare" template <typename> std::false_type has_decode (long); template <typename T> auto has_decode (int) -> decltype( T::decode(std::declval<Node>()), std::true_type{}); and a couple for "declare_new_api" template <typename> std::false_type has_decode_new_api (long); template <typename T> auto has_decode_new_api (int) -> decltype( T::decode_new_api(std::declval<Node>()), std::true_type{}); Now your decode_for_me() become template <typename T> T decode_for_me(Node node) { if constexpr ( decltype(has_decode<convert<T>>(0))::value ) return convert<T>::decode(node).second; if constexpr ( decltype(has_decode_new_api<convert<T>>(0))::value ) return convert<T>::decode_new_api(node); throw std::runtime_error("no decode"); }
71,309,305
71,309,623
does std::vector::insert allocate spare capacity?
Code like std::vector<int> a; for(size_t i = 0; i < n; ++i) a.push_back(0); is guaranteed to run in linear time in n. This is achieved by allocating some additional spare capacity when reallocating (typically increasing the total capacity by a constant factor). But what about std::vector::insert(pos, x)? I.e. is it guaranteed that std::vector<int> a; for(size_t i = 0; i < n; ++i) a.insert(a.end(), 0); is linear as well? (similar question applies to insert(pos, first, last) of course) The documentaiton of push_back is clear in guaranteeing "amortized constant" complexity. But the documentation of insert says the complexity should be "constant plus linear in the distance between pos and end of the container". This can obviously only be true if no reallocation happens, thus my uncertainty. EDIT: Summary of the answers: When a reallocation occurs, the implementation can either increase the capacity the bare minimum or increase the capacity more than the minimum, thus making future insertions faster. In the case of push_back, option (2) is essentially required to achieve the "amortized constant" runtime. In the case of insert(pos, first, last), option (2) is required in case of single-pass InputIterator (But in case of multi-pass ForwardIterator, the implementation can and does use a single reallocation with new_capacity = max(2*old_capacity, new_size)). All other cases are implementation defined. Testing with GCC 11 and clang 12, the situation seems to be: reserve and assign increase capacity by the bare minimum, and push_back and insert and resize increase the capacity by a constant factor
The actual language is [vector.overview] A vector is a sequence container that supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time and more specifically [vector.modifiers 1] Complexity: If reallocation happens, linear in the number of elements of the resulting vector; otherwise, linear in the number of elements inserted plus the distance to the end of the vector. but we both agree insert is broadly linear. When reallocation happens, the options are: reuse the same internal mechanism for growing the vector as in push_back(): this is obviously still amortized constant time, so the linear-time element move still dominates grow the vector by just one element: since this is still linear time, it's still within the complexity allowed. However, it is actually more effort for the implementer, and objectively worse I don't think I've ever seen an implementation that didn't just reuse some internal grow() method for both of these, but it would be technically legal to spend more effort doing something worse. The exception to this reasoning is the range overload insert(iterator pos, InputIterator begin, InputIterator end) since, for a strict LegacyInputIterator, you can only do one pass. If you can't pre-calculate the number of elements to grow by, any growth must be amortized constant time, or the overall complexity would be governed by N * distance(begin,end), which could be O(N²) and thus non-conformant. tl;dr push_back must allocate extra capacity to remain amortized constant time insert(pos, begin, end) must use amortized constant-time growth for each element of (begin,end] to remain amortized linear time overall insert(pos, value) does not need to allocate extra capacity in order to meet its complexity requirement, but it's probably more effort for the implementer to get a worse result
71,309,925
71,310,893
When I perform placement new on trivial object, Is it guaranteed to preserve the object/value representation?
struct A { int x; } A t{}; t.x = 5; new (&t) A; // is it always safe to assume that t.x is 5? assert(t.x == 5); As far as I know, when a trivial object of class type is created, the compiler can omit the call of explicit or implicit default constructor because no initialization is required. (is that right?) Then, If placement new is performed on a trivial object whose lifetime has already begun, is it guaranteed to preserve its object/value representation? (If so, I want to know where I can find the specification..)
Well, let's ask some compilers for their opinion. Reading an indeterminate value is UB, which means that if it occurs inside a constant expression, it must be diagnosed. We can't directly use placement new in a constant expression, but we can use std::construct_at (which has a typed interface). I also modified the class A slightly so that value-initialization does the same thing as default-initialization: #include <memory> struct A { int x; constexpr A() {} }; constexpr int foo() { A t; t.x = 5; std::construct_at(&t); return t.x; } static_assert(foo() == 5); As you can see on Godbolt, Clang, ICC, and MSVC all reject the code, saying that foo() is not a constant expression. Clang and MSVC additionally indicate that they have a problem with the read of t.x, which they consider to be a read of an uninitialized value. P0593, while not directly related to this issue, contains an explanation that seems relevant: The properties ascribed to objects and references throughout this document apply for a given object or reference only during its lifetime. That is, reusing the storage occupied by an object in order to create a new object always destroys whatever value was held by the old object, because an object's value dies with its lifetime. Now, objects of type A are transparently replaceable by other objects of type A, so it is permitted to continue to use the name t even after its storage has been reused. That does not imply that the new t holds the value that the old t does. It only means that t is not a dangling reference to the old object. Going off what is said in P0593, GCC is wrong and the other compilers are right. In constant expression evaluation, this kind of code is required to be diagnosed. Otherwise, it's just UB.
71,310,054
71,310,216
How to declare the template argument for an overloaded function
I have a fairly big project that, regarding this question, I can summarize with this structure: void do_something() { //... } template<typename F> void use_funct(F funct) { // ... funct(); } int main() { // ... use_funct(do_something); } All is working ok until someone (me) decides to reformat a little minimizing some functions, rewriting as this minimum reproducible example: void do_something(const int a, const int b) { //... } void do_something() { //... do_something(1,2); } template<typename F> void use_funct(F funct) { // ... funct(); } int main() { // ... use_funct(do_something); } And now the code doesn't compile with error: no matching function for call where use_funct is instantiated. Since the error message was not so clear to me and the changes were a lot I wasted a considerable amount of time to understand that the compiler couldn't deduce the template parameter because do_something could now refer to any of the overloaded functions. I removed the ambiguity changing the function name, but I wonder if there's the possibility to avoid this error in the future not relying on template argument deduction. How could I specify in this case the template argument for do_something(), possibly without referring to a function pointer? I haven't the slightest idea to express explicitly: use_funct<-the-one-with-no-arguments->(do_something);
You can wrap the function in a lambda, or pass a function pointer after casting it to the type of the overload you want to call or explicitly specify the template parameter: use_funct([](){ do_something (); }); use_funct(static_cast<void(*)()>(do_something)); use_funct<void()>(do_something); Wrapping it in a lambda has the advantage, that it is possible to defer overload resolution to use_func. For example: void do_something(int) {} void do_something(double) {} template<typename F> void use_funct(F funct) { funct(1); // calls do_something(int) funct(1.0); // calls do_something(double) } int main() { use_funct([](auto x){ do_something (x); }); } [...] possibly without referring to a function pointer? I am not sure what you mean or why you want to avoid that. void() is the type of the function, not a function pointer. If you care about spelling out the type, you can use an alias: using func_type = void(); use_funct<func_type>(do_something);
71,310,201
71,310,605
MacOS: VSCode C/C++ intellisense fails to deduce types
MacOS Catalina 10.15.7, VSCode 1.64.2 (Universal) :I had the intellisense working for my project without problems, but then for whatever reason it has stopped working in some cases: whenever I assign something to an 'auto variable', for example: auto val = (float)foo; I'd get intellisense error: int val: explicit type is missing ('int' assumed)C/C++(260). Class enums are not recognised as they should, so I can't use EnumClass::Enum or get any enum-related autocomplete support. Those are the most reoccuring problems, but I'd say the intellisense generally doesn't work properly. I removed everything related to VSCode (using this: How to completely uninstall vscode on mac) and reinstalled with just C/C++ extention enabled and the problem persists. I have other people using the same setup with this project and they don't have this problem. I tried older versions of the extention without success aswell. Is there anything I could try to get it back to work?
The issue seems to be that intellisense is using older c++ version for determining the syntax. The way to fix this is to set to some newer version like c++17 Go to settings in your VSCode and search for Cpp Standard and from the dropdown select c++17 or any newer version that you use. In case you follow JSON style settings, then search for following "C_Cpp.default.cppStandard": "c++17" Attaching the screenshot of the settings page
71,310,261
71,313,929
ASIO C++ coroutine cancellation
I am spawning a coroutine as shown below. asio::co_spawn(executor, my_coro(), asio::detached); How am I supposed to cancel it? As far as I know, per handler cancellation can be achieved simply by binding a handler with asio::bind_cancellation_slot. This does not work in my specific example (irrespective of using the asio::detached "handler" or some lambda), and it makes sense to me that it does not work. I found this blog post which basically says that spawning the coroutine from another one and awaiting it (with appropriate asio::bind_cancellation_slot setup) does the trick. This fails for me as my_coro never seems to run in the example below. Besides, I don't even know why this should work at all (with respect to cancellation). asio::awaitable<void> cancelable(asio::cancellation_signal& sig, asio::awaitable<void>&& awaitable) { co_await asio::co_spawn(co_await asio::this_coro::executor, std::move(awaitable), asio::bind_cancellation_slot(sig.slot(), asio::use_awaitable)); co_return; } // ... asio::cancellation_signal signal; asio::co_spawn(executor, cancelable(signal, my_coro()), asio::detached); What is the correct way to connect a asio::cancellation_signal to the asio::cancellation_state of a coroutine (obtained by co_await asio::this_coro::cancellation_state) in ASIO? If it helps: I'm using ASIO stand-alone on the most recent master, i.e. not the boost version.
To cancel a coroutine in asio use the new awaitable_operator '||'. The awaitable operator '||' allows to co_await for more than one coroutine until one of the coroutines is finished. For example: #include "boost/asio/experimental/awaitable_operators.hpp" #include <boost/asio.hpp> #include <boost/asio/deadline_timer.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/system_timer.hpp> #include <boost/asio/this_coro.hpp> #include <chrono> #include <iostream> boost::asio::awaitable<void> printHelloEverySecond () { for (;;) { std::cout << "Hello" << std::endl; boost::asio::system_timer timer{ co_await boost::asio::this_coro::executor }; timer.expires_after (std::chrono::seconds{ 1 }); co_await timer.async_wait (boost::asio::use_awaitable); } } boost::asio::awaitable<void> stopAfter4500Milliseconds (boost::asio::system_timer &timer) { boost::asio::system_timer stopAfterFiveSeconds{ co_await boost::asio::this_coro::executor }; stopAfterFiveSeconds.expires_after (std::chrono::milliseconds{ 4500 }); co_await stopAfterFiveSeconds.async_wait (boost::asio::use_awaitable); timer.cancel (); } boost::asio::awaitable<void> cancel (boost::asio::system_timer &timer) { try { co_await timer.async_wait (boost::asio::use_awaitable); } catch (boost::system::system_error &e) { using namespace boost::system::errc; if (operation_canceled == e.code ()) { // swallow cancel } else { std::cout << "error in timer boost::system::errc: " << e.code () << std::endl; abort (); } } } int main () { boost::asio::io_context ioContext{}; boost::asio::system_timer timer{ ioContext }; timer.expires_at (std::chrono::system_clock::time_point::max ()); using namespace boost::asio::experimental::awaitable_operators; co_spawn (ioContext, printHelloEverySecond () || cancel (timer), [] (auto, auto) { std::cout << "stopped" << std::endl; }); co_spawn (ioContext, stopAfter4500Milliseconds (timer), boost::asio::detached); ioContext.run (); } Here "printHelloEverySecond ()" will run until "cancel()" returns successfully which happens when the timer is canceled (in "stopAfter4500Milliseconds") after 4500 milliseconds. This allows to cancel "printHelloEverySecond ()" when the timer gets canceled. For reference: Chris Kohlhoff explains awaitable_operator and cancelation
71,310,599
71,310,822
Convert a string array with special characters to an int array. Inputs are from a file
My problems here is to take all the integers in a file, and store to an int array (of course without |), and then do something with it (here I just need help to print out the array). The data from the file is said to be a 10x10 matrix. My code output is another 10x10 with trash values, as I tried using std::stringstream. Input: 1|11|2|13|2|2|2|11|13|2 1|11|2|13|2|2|2|13|2|11 1|13|1|13|2|2|2|2|2|2 1|13|1|12|2|2|2|2|2|2 1|13|1|13|1|2|2|2|2|2 1|13|1|13|1|1|2|2|2|2 1|13|1|13|1|1|1|2|2|2 1|13|1|13|1|1|1|1|2|2 1|13|1|13|1|1|1|1|1|2 1|13|1|13|1|1|1|1|1|1 Code: #include<iostream> #include<cstring> #include<fstream> #include<sstream> using namespace std; int main(){ //read data from file and store in a 2d array ifstream myfile("input.txt"); string arr[10][20]; for(int i=0;i<10;i++){ for(int j=0;j<20;j++){ getline(myfile,arr[i][j],'|'); } } //convert string to int //use stringstream int arr2[10][20]; for(int i=0;i<10;i++){ for(int j=0;j<20;j++){ stringstream ss; ss<<arr[i][j]; ss>>arr2[i][j]; } } //print arr2 for(int i=0;i<10;i++){ for(int j=0;j<20;j++){ cout<<arr2[i][j]<<" "; } cout<<endl; } myfile.close(); return 0; } The output should be: 1 11 2 13 2 2 2 11 13 2 1 11 2 13 2 2 2 13 2 11 1 13 1 13 2 2 2 2 2 2 1 13 1 12 2 2 2 2 2 2 1 13 1 13 1 2 2 2 2 2 1 13 1 13 1 1 2 2 2 2 1 13 1 13 1 1 1 2 2 2 1 13 1 13 1 1 1 1 2 2 1 13 1 13 1 1 1 1 1 2 1 13 1 13 1 1 1 1 1 1 My output: 1 11 2 13 2 2 2 11 13 2 1 13 2 2 2 2 2 2 13 1 1 2 2 2 2 2 13 1 13 1 1 2 2 2 13 1 13 1 1 1 1 2 13 1 13 1 1 1 1 1 1994842136 12 7086696 7085352 1994774642 0 1994842144 1994771436 0 0 6416848 2004213955 7086772 6416972 12 7086696 0 4 48 1994842112 2004213726 1 7149280 7149288 7086696 0 1988425164 0 2003400672 12 1999860416 6416972 2 1999966512 1999657456 1999691632 1999846272 1999845632 1999819744 1999860464 4194304 1994719472 0 6417024 0 6418312 2004471984 775517426 -2 6417120
Two issues: You try to read 10x20 when there is only 10x10 in the file. Further your code assumes that there is a | between all adjacent numbers, but thats not the case. There is no | between the last number in a line and the first in the next line. Change the size accordingly and read full lines before you split them at |: string arr[10][10]; for(int i=0;i<10;i++){ std::string line; getline(myfile,line); std::stringstream linestream{line}; for(int j=0;j<10;j++){ getline(linestream,arr[i][j],'|'); } } Live Demo This is minimum changes on your code. Next I would suggest to extract integers from the stream directly instead of first extracting string and then convert them to integers (by placing the strings into another stream and then extracting the integer, you could do this already with the ifstream).
71,310,805
71,311,108
Compiling a function with templates fails in variadic template function
I have come across a compiler error involving variadic templates. The following code is a strongly simplified version which reproduces the error in my original code: #include <iostream> #include <sstream> #include <string> #include <vector> typedef std::vector<std::string> stringvec; // dummy function: return string version of first vectorelemenr template<typename T> std::string vecDummy(const std::string sFormat, const T t) { std::stringstream ss(""); if (t.size() > 0) { ss << t[0]; } return ss.str(); } // recursion termination std::string recursiveY(stringvec &vFlags, uint i) { return ""; } // walk through arguments template<typename T, typename... Args> std::string recursiveY(stringvec &vFlags, uint i, T value, Args... args) { std::string sRes = ""; if (vFlags[i] == "%v") { sRes += vecDummy(vFlags[i], value); } sRes += " "+recursiveY(vFlags, i+1, args...); return sRes; } int main(void) { stringvec vPasta = {"spagis", "nudle", "penne", "tortellini"}; stringvec vFormats = {"%v", "%s"}; std::string st = ""; st += recursiveY(vFormats, 0, vPasta, "test12"); std::cout << ">>" << st << "<<" << std::endl; return 0; } This simple code should walk through the arguments passed to recursiveY() and, if the current format string is "%v" it would pass the corresponding argument to vecDummy() which would return a string version of the vector's first element (if there is one). The error message from the compiler is sptest2.cpp: In instantiation of ‘std::string vecDummy(std::string, T) [with T = const char*; std::string = std::__cxx11::basic_string<char>]’: sptest2.cpp:30:25: required from ‘std::string recursiveY(stringvec&, uint, T, Args ...) [with T = const char*; Args = {}; std::string = std::__cxx11::basic_string<char>; stringvec = std::vector<std::__cxx11::basic_string<char> >; uint = unsigned int]’ sptest2.cpp:32:27: required from ‘std::string recursiveY(stringvec&, uint, T, Args ...) [with T = std::vector<std::__cxx11::basic_string<char> >; Args = {const char*}; std::string = std::__cxx11::basic_string<char>; stringvec = std::vector<std::__cxx11::basic_string<char> >; uint = unsigned int]’ sptest2.cpp:43:21: required from here sptest2.cpp:12:11: error: request for member ‘size’ in ‘t’, which is of non-class type ‘const char* const’ 12 | if (t.size() > 0) { | ~~^~~~ It seems as if the compiler uses all types i pass to recursiveY() in main, but vecDummy() is designed to only work with vectors of some kind (and not with const char*, for example). Is there a possibility to modify this code so that it will work as intended? Is there perhaps a way of assuring the compiler that i will only pass vectors to vecDummy() (even at the risk of a runtime error or unexpected behaviour - similar to passing an integer to printf() when it expects a string)?
You can add an overload of vecDummy that handles the std::vector case and 'dumb down' the more general one to (say) just return an empty string: // dummy function: return string version of first vectorelement (catch-all) template<typename T> std::string vecDummy(const std::string, const T) { return ""; } // dummy function: return string version of first vectorelement (vectors only) template<typename T> std::string vecDummy(const std::string, const std::vector <T> &t) { std::stringstream ss(""); if (t.size() > 0) { ss << t[0]; } return ss.str(); } Live demo
71,310,981
71,312,908
Add an additional control to a QFileDialog
I am using the Native file dialog, so there is no layout() but want to add an additional control to the dialog. The builtin Notepad application has a perfect example when they allow the user to select the desired encoding (see below, to the left of the "Save" button). Is it possible to add an additional control in Qt5 while still using the native dialog?
TL;DR: Completely custom components are not available with native dialogs, filters can be controlled using QFileDialog::setNameFilters. Qt's implementation of the native windows file dialog uses ABI::Windows::Storage::Pickers. You can check the implementation out here. Depending on the type of action you perform, the implementation uses IFileOpenPicker, IFolderPicker or IFileSavePicker. If you want to manipulate the native dialog, this class would have to provide you with the option to do so. We can find the documentation for the FileSavePicker class here. Going through the available options, you see that there is no interface to provide any specific custom UI element. If you would only need the filter, the QFileDialog provides you with the ability to set a filter using QFileDialog::setNameFilters. If you need a completely custom control/functionality, you unfortunately have to provide your own QDialog.
71,311,512
71,311,850
Execute a bat file with parent process privilege in qt
I have a directory in the current working path of my executable which is called Store. In this directory, there is a bat file which is called init.bat. I have written the following code to run this file, but it seems CreateProcessW doesn't run the bat file. How should I fix this code? I didn't receive any error, the program just doesn't work and my bat file doesn't execute. #include "mainwindow.h" #include <QApplication> #include <QSplashScreen> #include <QMessageBox> #include <QDir> #include <windows.h> #include <tchar.h> #pragma comment(lib, "user32.lib") int main(int argc, char *argv[]) { QApplication a(argc, argv); bool status = FALSE; QSplashScreen *splash_loader = new QSplashScreen; splash_loader->setPixmap(QPixmap(":/new/prefix1/images/splash.png")); splash_loader->show(); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); QString path = QDir::toNativeSeparators(qApp->applicationDirPath()); path.append(L"\\Store\\init.bat"); // Execute requirement batch file LPWSTR final_path = _wcsdup(path.toStdWString().c_str()); status = CreateProcessW(NULL, final_path, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); if(status && WaitForSingleObject(pi.hProcess, INFINITE)) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); splash_loader->close(); } MainWindow w; w.show(); return a.exec(); }
In Qt, you would use the QProcess-API (see QProcess::start()). Using CreateProcess is not the Qt way to do this. In the linked documentation, you will find a hint on executing commands via cmd on Windows and hints for other OS.
71,311,765
71,324,900
QUdpSocket broadcast not working to more than one client
I have an application that uses QUdpSocket to broadcast a heartbeat message: mpsckUDP = new QUdpSocket(this); mpsckUDP->bind(QHostAddress::Broadcast, clsMainWnd::mscuint16Port); QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdh())); mscuint16Port is: const quint16 clsMainWnd::mscuint16Port(8081); The code that sends a message: const QByteArray carybytData(/*My message*/); qint64 int64Written(mpsckUDP->writeDatagram(carybytData, QHostAddress::LocalHost, clsMainWnd::mscuint16Port)); int64Written is assigned 47 after each call to writeDatagram. In my client applications which run on the same system: mpsckUDP = new QUdpSocket(this); uint uintPort(8081); mpsckUDP->bind(QHostAddress::LocalHost, uintPort); QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy())); The slot: void clsMainWnd::onUDPdataRdy() { QHostAddress objSender; QByteArray arybytData; quint16 uint16Port; arybytData.resize(mpsckUDP->pendingDatagramSize()); mpsckUDP->readDatagram(arybytData.data(), arybytData.size(), &objSender, &uint16Port); ... } I launch two instances on the client application on the same system the issue is that only the first instance is receiving the UDP broadcast, the other isn't receiving anything... The intention is to have many clients and a single broadcasting application.
Main application: mpsckUDP = new QUdpSocket(this); //Connection only required if you are going to receive data back on UDP QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy())); Broadcast logic: qint64 int64Written(mpsckUDP->writeDatagram(carybytData, QHostAddress::Broadcast, clsMainWnd::mscuint16Port)); In the client applications: mpsckUDP = new QUdpSocket(this); mpsckUDP->bind(uintPort, QUdpSocket::ShareAddress); QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy())); Now all is good!
71,311,939
71,312,140
Forward declared variable not accessible in cpp file
Considering the example below: header.h extern int somevariable; void somefunction(); source.cpp #include "header.h" somevariable = 0; // this declaration has no storage class or type specifier void somefunction(){ somevariable = 0; // works fine } I couldn't find the answer to the following questions: Why can't I just forward declare int somevariable and initialize it in the .cpp file? Why is the somefunction() function able to "see" somevariable when declared using extern int somevariable, and why is it not accessible outside of a function?
extern int somevariable; means definition of somevariable is located somewhere else. It is not forward declaration. Forward declaration is used in context of classes and structs. somevariable = 0; is invalid since this is assignment and you can't run arbitrary code in global scope. It should be: int somevariable = 0; and this means define (instantiate) global variable somevariable in this translation unit and initialize it to 0. Without this statement linking of your program will fail with error something like: undefined reference to 'somevariable' referenced by ... . Use of global variable in any langue is considered as bad practice, sine as project grows global variable makes code impossible to maintain and bug-prone.
71,312,797
71,312,939
C++ template argument limited to classes (not basic types)
Is it possible specify a template argument, that would never match to a basic type, such as an int? I'm heavily fighting ambiguities. So for example: template<class T> void Function(const T& x) { SetString(x.GetString()); }; That would work only if there's a method GetString in T, but if the compiler sees this function, it tries to uses it even if T is just int for example.
Method 1 You can use std::enable_if as shown below: C++11 //this function template will not be used with fundamental types template<class T> typename std::enable_if<!std::is_fundamental<T>::value>::type Function(const T& x) { SetString(x.GetString()); }; Demo C++17 template<class T> typename std::enable_if_t<!std::is_fundamental_v<T>> Function(const T& x) { SetString(x.GetString()); }; Demo Method 2 We can make use of SFINAE. Here we use decltype and the comma operator to define the return type of the function template. //this function template will work if the class type has a const member function named GetString template <typename T> auto Function (T const & x) -> decltype( x.GetString(), void()) { SetString(x.GetString()); }; Demo Here we've used trailing return type syntax to specify the return type of the function template.
71,313,002
71,313,525
Printf display only one word
I want to display more than one word using printf, Do I should change first parameter in pritnf? #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { int value; printf("How many:"); scanf("%d", &value); char* arr1 = new char[value]; scanf("%s[^\n]", arr1); printf("%s", arr1); delete [] arr1; return 0; }
As already pointed out in the comments section, the following line is wrong: scanf("%s[^\n]", arr1); The %s and %[^\n] are distinct conversion format specifiers. You seem to be attempting to use a hybrid of both. If you want to read a whole line of input, you should use the second one. However, even if you fix this line, your program will not work, for the following reason: The statement scanf("%d", &value); will read a number from standard input, but will only extract the number itself from the input stream. The newline character after the input will not be extracted. Therefore, when you later call scanf("%[^\n]", arr1); it will extract everything that remained from the previous scanf function call up to the newline character. This will result in no characters being extracted if the newline character immediately follows the number (which is normally the case). Example of program's behavior: How many:20ExtraInput ExtraInput As you can see, everything after the number up to the newline character is being extracted in the second scanf function call (which is then printed). However, this is not what you want. You want to extract everything that comes after the newline character instead. In order to fix this, you must discard everything up to and including the newline character beforehand. This must be done between the two scanf function calls. #include <stdio.h> int main() { int value; int c; printf("How many:"); scanf("%d", &value); char* arr1 = new char[value]; //discard remainder of line, including newline character do { c = getchar(); } while ( c != EOF && c != '\n' ); scanf("%[^\n]", arr1); printf("%s", arr1); delete [] arr1; return 0; } The program now has the following behavior: How many:20ExtraInput This is a test. This is a test. As you can see, the program now discards ExtraInput and it correctly echoes the line This is a test.
71,313,052
71,315,846
Function Pointers, In STM32 and how do i understand these Type Handles?
I'm getting a very confusing error as I may be making a small mistake with the phrasing or the type handles or it could be a more complicated problem Basically I want to create this funciton Buf_IO(HAL_StatusTypeDef IO) that can take one of two inputs either HAL_SPI_Transmit or HAL_SPI_Recieve these are both defined as HAL_StatusTypeDef HAL_SPI_Transmit/*or Recieve*/(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) so in my code i have defined my function pointer as follows HAL_StatusTypeDef (FuncPtr*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t) = IO; where IO is the argument to my function however for some reason i get the error invalid conversion from 'HAL_StatusTypeDef (*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t)' {aka 'HAL_StatusTypeDef (*)(__SPI_HandleTypeDef*, unsigned char*, short unsigned int, long unsigned int)'} to 'void (*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t)' {aka 'void (*)(__SPI_HandleTypeDef*, unsigned char*, short unsigned int, long unsigned int)'} for clarity this is how i have declared the funtion in the .cpp file void MAX_Interface::Buf_IO(HAL_StatusTypeDef IO) { HAL_StatusTypeDef (FuncPtr*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t) = IO; uint8_t* buf_ptr = (uint8_t*) &OBuf; HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_RESET); FuncPtr(h_SPI, buf_ptr, 3, 100); HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_SET); } I do understand that i may be overcomplicating this as I have previously written just two different functions for transmitting an receiving but I'm looking to make my code more concise and also learn a bit in the process so feel free to suggest a more elegant solution if you can think of one?
In C++, you should use the using directive to define the function signature. using is similar to typedef in C, but makes things much more readable. using IO = HAL_StatusTypeDef(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t); Note, that IO is now the alias of the function signature itself, not a pointer to the function. Now, in your function you use it as IO* to specify that the parameter is a function pointer: void MAX_Interface::Buf_IO(IO* funcPtr) { uint8_t* buf_ptr = (uint8_t*) &OBuf; HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_RESET); funcPtr(h_SPI, buf_ptr, 3, 100); HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_SET); }
71,313,184
71,314,167
I don't understand how cin.ignore() works. When I run this piece of code, my program breaks down
There is an array of classes. I want to input an amount of players and then by using a for-loop, input player's names. The problem is that I don't understand how to avoid the program crashing, using cin.ignore(). void main() { int numberOfPlayers; cout << "Input amount of players:"; getline(cin, numberOfPlayers); Player** arrOfPlayers = new Player*[numberOfPlayers]; string newName; for (int i = 0; i < numberOfPlayers; i++) { cout << "\nInput player " << i + 1 << " nickname: "; getline(cin, newName); arrOfPlayers[i]->setName(newName); } }
You have not allocated the individual players This Player** arrOfPlayers = new Player*[numberOfPlayers]; only allocates an array of pointers to players You also need to create those players for (int i = 0; i < numberOfPlayers; ++i) arrOfPlayers[i] = new Player;
71,313,729
71,313,808
Structure with an array, is memory contiguous?
if I have struct S { int a; float* b; int c; }; Aside from any padding. a, b (the variable where a pointer is kept), and c will be contiguous. The element that b is pointing to, may be somewhere else in memory if I have struct S { int a; float b[10]; int c; }; a, every element of b, and c will all be contiguous in memory. Correct? I wrote a test program and looked at the addresses to confirm, but I am not sure if that is the compiler being helpful or it is guaranteed.
Yes, a, (the elements of) b, and c will be contiguous, if we ignore possible padding between a and b, or b and c. Of course there's no padding between the elements of b.