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
70,219,273
70,219,412
Meyers' implementation of a Singleton Attempting to reference a deleted function (paho-mqttpp3 library) (mqtt::async_client class)
OS : Windows 10 x64 Build Tool : Visual Studio 2021 Language Standard : C++20 paho-mqttpp3 : 1.2.0 Package Manager : vcpkg I am trying to build a mqtt::async_client using paho-mqttpp3 verrsion 1.2.0 I am using Meyers' implementation of a Singleton for my MQTT Client. Reference : https://stackoverflow.com/a/17713799/6319901 I am getting the following error Error C2280 'MqttClient::MqttClient(void)': attempting to reference a deleted function on line static MqttClient instance; When I get my mouse over the instance (object) the tool-tip displays the following error. Error (active) E1790 the default constructor of "MqttClient" cannot be referenced -- it is a deleted function Source : MqttClient& MqttClient::get_instance(void) { static MqttClient instance; return instance; } Header: class MqttClient : public virtual mqtt::callback { private: mqtt::async_client client; void connected(const std::string& cause) override; void connection_lost(const std::string& cause) override; void delivery_complete(mqtt::delivery_token_ptr tok) override; void message_arrived(mqtt::const_message_ptr msg) override; MqttClient() = default; ~MqttClient() = default; public: static MqttClient& get_instance(void); MqttClient(const MqttClient& obj) = delete; MqttClient(MqttClient&& obj) = delete; MqttClient& operator=(const MqttClient& obj) = delete; MqttClient& operator=(MqttClient&& obj) = delete; };
From the documentation it appears, that mqtt:async_client is not default-constructible, meaning that you would have to provide an initializer in MqttClient's constructor or a default member initializer. Not doing so results in the default constructor being deleted, despite your attempt to explicitely default it.
70,219,509
70,219,935
Why is the nested macro not unfolded?
I am using nested macro under gcc-9.3.1. Here is the code. #define A(_name) _name, _name, _name #define P(_1, _2, _name, ...) _name #define B(...) P(__VA_ARGS__, A(something))(__VA_ARGS__) B(k) I expected the B(k) converted to P(k, something, something, something)(k) at first and then converted into something(k). However, compilier told me that two arguments were too few for P, which meant that A(something) was not unfolded. Why is that? And how can I make it unfolded?
B(k) expands to P(k, A(something))(k) which then undergoes recursive expansion. The first thing it finds there is P, which doesn't have enough arguments. If you want this to work the way I think you do, you need to arrange for A to expand before P. You can do that by adding explicit indirect EXPAND macros: #define EXPAND(...) __VA_ARGS__ #define B(...) EXPAND(P EXPAND((__VA_ARGS__, A(something))))(__VA_ARGS__) This way, P won't be recognized as a macro (no following () until after the inner EXPAND is expanded (which will also expand A). You need the outer EXPAND to explicitly expand P afterwards.
70,219,552
70,219,643
create lambda signature after template argument
I need to write a function (f) that accepts a std::function (g) with a generic callback parameter. In the function f, some additional code should be executed when the callback is called. I would therefore need to create a lambda with a signature depending on the generic callback parameter. My template skills fails me here. So basically, in the snippet below, both g1 and g2 should be possible to use as input to f: void g1(std::function<void()> cb) { // do stuff, call callback cb(); } void g2(std::function<void(int)> cb) { cb(1); } template<typename TFunc, typename TCb> void f(TFunc g, TCb handler) { // in some way intercept the callback from g to do additional stuff when callback arrives g([handler](int i) { // this only works for g2 now, needs to be generic // Do the extra stuff here before calling final callback // Call final callback with same signature as g1 (or g2) callback handler(i); }); } void main() { f(g1, [](){}); f(g2, [](int){}); }
I'm not sure if this is what you need, but maybe you can use it as a starting point... This requires C++14 g([handler](auto&&... args ) { // Do the extra stuff here before calling final callback // Call final callback with same signature as g1 (or g2) callback handler(std::forward<decltype(args)>(args)...); }); Full example here: https://godbolt.org/z/xranbfrEE If you can use C++20, you can use the new lambda template parameters: g([handler]<typename... Args> (Args&&... args ) { handler(std::forward<Args>(args)...); });
70,219,669
70,219,698
Use a Unicode character in a char variable (C++)
I get some input from the command line and want to support Unicode. This is my error: And this is my example code: #include <iostream> int main() { char test = '█'; } // Characters wanted: █, ▓, or ▒ How can I make my program support Unicode?
A char is usually only 1 byte, meaning it won't be able to store most Unicode characters. You should look into using wchar_t which is required to be large enough to hold any supported character codepoint. The associated char literal looks as follows: L'█'.
70,219,699
70,238,711
How does Boost::serialization store user-defined classes in archives?
I have a user-defined object (call it Foo) which consists of some primitive variables, as well as other (external library) objects which already contain implementations of the serialize function. I would like to know how the archive files are structured, and whether that structure is general (e.g. between text archives and binary archives). When I open a text archive in a text editor, the first characters are 22 serialization::archive 19 0 0. What follows appears to be all of the data from my user-defined object. My question is: what do those initial characters correspond to? And if I try to output the contents of my file into something which is not Foo, as follows: bool bool1; bool bool2; ia >> bool1 >> bool2; it seems to just output the first few zeros -- does it do that for any archive? And if so, is it reasonable to read out all of the member variables of Foo from that archive by just reading into the appropriate types as in: bool bool1; bool bool2; double Foo_member1; std::string Foo_member2; ia >> bool1 >> bool2 >> Foo_member1 >> Foo_member2; And finally, does this structure follow from any other kind of archive as well (e.g. a binary archive)?
it seems to just output the first few zeros What do you mean? You serialized two variables with indeterminate values (you never initialized them). You should not be expecting zeroes. Nor should you be expecting any particular layout (it is determined by archive type, version, library version(s) and platform architecture). like to know how the archive files are structured, and whether that structure is general It depends on the archive. It is "general" (for some definition of general). However, most archive formats include minimal meta-data describing its structure (they can not be "visited" or "traversed" in non-sequential fashion, nor is there a "reflectable" schema of some kind). If you need these kinds of serialization features, look at others (protobuf, msgpack, bson, XML/XSD, etc). The one archive type that will most satisfy your curiosity is the XML archive type. You will find that you are required to supply semantic information for the XML elements, e.g. Live On Coliru #include <boost/archive/xml_oarchive.hpp> #include <iostream> int main() { using boost::serialization::make_nvp; { boost::archive::xml_oarchive oa(std::cout); int a = 42, b = 99, c = a * b; oa << make_nvp("a", a) << make_nvp("b", b) << make_nvp("c", c); } // closes the archive } Which results in <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!DOCTYPE boost_serialization> <boost_serialization signature="serialization::archive" version="19"> <a>42</a> <b>99</b> <c>4158</c> </boost_serialization> This will at least lend some recognizable context to the version (19) and similar information. E.g. relating to Object Tracking and Identity, RTTI mapping and exported class keys etc. And if so, is it reasonable to read out all of the member variables of Foo from that archive by just reading into the appropriate types Yes but maybe no. The contract you have to fulfill is to (de)serialize the exact same types of data in the exact same order. Any way you manage that is fine. The typical way is to implement serialize for your type, not to serialize the members separately (Law Of Demeter and simple Encapsulation): Live On Coliru #include <boost/archive/xml_oarchive.hpp> namespace MyLib { struct Foo { bool bool1; bool bool2; double Foo_member1; std::string Foo_member2; }; template <typename Ar> void serialize(Ar& ar, Foo& foo, unsigned /*version*/) { ar& BOOST_NVP(foo.bool1) & BOOST_NVP(foo.bool2) & BOOST_NVP(foo.Foo_member1) & BOOST_NVP(foo.Foo_member2); } } // namespace MyLib #include <cmath> // for M_PI... #include <iostream> int main() { using boost::serialization::make_nvp; { boost::archive::xml_oarchive oa(std::cout); MyLib::Foo foo{true, false, M_PI, "Hello world"}; oa << make_nvp("foo", foo); } // closes the archive } Prints <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <!DOCTYPE boost_serialization> <boost_serialization signature="serialization::archive" version="19"> <foo class_id="0" tracking_level="0" version="0"> <foo.bool1>1</foo.bool1> <foo.bool2>0</foo.bool2> <foo.Foo_member1>3.14159265358979312e+00</foo.Foo_member1> <foo.Foo_member2>Hello world</foo.Foo_member2> </foo> </boost_serialization> CAVEAT It does sound a little like you're mistaking archives for random-access data streams with some standard format. See for more Archives are not streams
70,219,770
70,227,267
Problem with "setup.h" wxwidget - "cannot open file"
Hello i build 32 and 64 bit version wxwidget (Batch Build and select all) from source code without any problems. Then add path to the system variables as named "WXWIN" with C:\wxwidget (there is wxwidget source) In visual studio 2019 in solution i add these path's: C/C++ -> Additional Include Directories -> $(WXWIN)\include $(WXWIN)\include\msvc Linker -> Additional Library Directories -> $(WXWIN)\lib\vc_lib $(WXWIN)\lib\vc_lib\mswud But i got error in visual: Severity Code Description Project Path File Line Suppression State Error (active) E1696 cannot open source file "../../../lib/vc_lib/mswd/wx/setup.h" guiwxwidget C:\wxwidgets\include\wx C:\wxwidgets\include\wx\setup.h 140 And i dont know whats wrong with it. I try also recompile 4x wxwidget source without any progress.
Your project is not configured to use Unicode, hence it tries using non-Unicode build of wxWidgets (note the missing u in mswd/wx/setup.h) which is not available. You should ensure that the "Character Set" option in the "Advanced" section of your project properties is set to "Use Unicode Character Set". The strange thing is that this should be the default, so it looks like you might have changed it intentionally. If you really did, you will need to build wxWidgets in (deprecated and soon to be removed) ANSI build mode, but it's much better to leave this option at its default value and use Unicode -- we're in 2021, after all, not 1991.
70,219,858
70,220,112
How to make an object and put it into an array using a loop, so if I want to add data all I have to do is make a new string
How to make an object and put it into an array? I want to make an array of DailyStats with the parameterized constructor. I want to use a loop to add to the array of objects. #ifndef DAILYSTATS_H #define DAILYSTATS_H #include <iostream> #include <vector> using namespace std; class DailyStats { public: DailyStats(); DailyStats(string content); void parse(const string& line); double mean(); string getDate(); void setDate(string newDate); private: string date; double temperatureValues[]; }; #endif #include <iostream> #include "DailyStats.hpp" #include <vector> #include <cmath> using namespace std; DailyStats::DailyStats() { date = ""; count = 0; temperatureValues[0]; } DailyStats::DailyStats(string content) { parse(content); temperatureValues[24]; count = 0; } void DailyStats::parse(const string& line) { string random = ""; string random1 = ""; char del = ' '; int count2 = 0; for(int i = 0; i <= (int)line.size(); i++) { if(count < 10) { random1 += line[i]; setDate(random1); count++; } if(line[i] != del && count == 10) { random += line[i]; } else if (line[i] == del && count == 10) { temperatureValues[count2] = stod(random); random = ""; count2++; } } } double DailyStats::mean() { count = 1; double num = 0; while(count <= 24) { num += temperatureValues[count]; if(count == 24) { num = num/24; } count++; } return ceil(num * 100.0) / 100.0; } string DailyStats::getDate() { return date; } void DailyStats::setDate(string newDate) { date = newDate; } #include <iostream> #include <string> #include "DailyStats.hpp" using namespace std; int main() { string str0 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; string str1 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; string str2 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; string str3 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; DailyStats info[4]; info[1] = { {str0} }; cout << info[1].mean() << endl; return 0; } As you can see with my code, I have different strings that I would like to put in my objects to be used as the variable for my parameterized constructor. So, when I have that done, I can then call my mean() function so it can get the different means of the different data. I tried it without the array, and it all works fine, but I can't figure out how to get the array to work.
The main problem I see is that your temperatureValues[] array is unbound at compile-time. That will not work. Since you don't know the size of the array until runtime, use std::vector instead (in fact, you already have #include <vector> in your code), eg: #ifndef DAILYSTATS_H #define DAILYSTATS_H #include <vector> #include <string> class DailyStats { public: DailyStats() = default; DailyStats(const std::string& content); void parse(const std::string& line); double mean() const; std::string getDate() const; void setDate(const std::string& newDate); private: std::string date; std::vector<double> temperatureValues; }; #endif #include "DailyStats.hpp" #include <cmath> #include <sstream> DailyStats::DailyStats(const string& content) { parse(content); } void DailyStats::parse(const string& line) { std::istringstream iss(line); double value; iss >> date; temperatureValues.clear(); while (iss >> value) temperatureValues.push_back(value); } double DailyStats::mean() const { double num = 0.0; if (!temperatureValues.empty()) { for(size_t count = 0; count < temperatureValues.size(); ++count) { num += temperatureValues[count]; } num = std::ceil((num / temperatureValues.size()) * 100.0) / 100.0; } return num; } std::string DailyStats::getDate() const { return date; } void DailyStats::setDate(const std::string& newDate) { date = newDate; } #include <iostream> #include <string> #include "DailyStats.hpp" using namespace std; int main() { string str0 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; string str1 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; string str2 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; string str3 = "06/01/2021 74.85 71.58 78.68 71.55 78.14 72.36 76.89 71.35 79.94 78.87 78.07 75.78 77.86 74.04 76.56 72.96 75.07 74.02 70.21 75.56 79.61 72.97 75.29 73.33 "; DailyStats info[4]; info[0].parse(str0); info[1].parse(str1); info[2].parse(str2); info[3].parse(str3); cout << info[0].mean() << endl; cout << info[1].mean() << endl; cout << info[2].mean() << endl; cout << info[3].mean() << endl; return 0; }
70,219,925
70,264,803
How to speed up character output?
I want to make this for loop run faster by optimizing the I/O: for ( int row = 0; row < Y_AxisLen; ++row ) { for ( int col = 0; col < X_AxisLen; ++col ) { std::cout << characterMatrix[ row ][ col ]; } } std::vector< std::vector<char> > characterMatrix; is a matrix and I need to print it out. Is printing one char at a time bad for performance? Also, should I use the {fmt} library instead of std::cout? Will this work faster? std::array<char, X_AxisLen> rowStr { }; for ( int row = 0; row < Y_AxisLen; ++row ) { for ( int col = 0; col < X_AxisLen; ++col ) { rowStr[ col ] = characterMatrix[ row ][ col ]; } std::cout << rowStr.data( ); // fmt::print( "{}", rowStr.data( ) ); // Or using this one. But will this even work? }
You can write the whole row in one go and use fmt::print for better performance: #include <fmt/core.h> #include <vector> int main() { auto X_AxisLen = 10000u; auto Y_AxisLen = 10000u; auto characterMatrix = std::vector<std::vector<char>>(X_AxisLen, std::vector<char>(Y_AxisLen)); for (int i = 0; i < Y_AxisLen; ++i) { const auto& row = characterMatrix[i]; fmt::print("{}", std::string_view(row.data(), row.size())); } } % c++ test.cc -O3 -DNDEBUG -std=c++17 -I include src/format.cc -o test-fmt % time ./test-fmt > /dev/null ./test-fmt > /dev/null 0.03s user 0.04s system 52% cpu 0.135 total For comparison, this is ~30 times (not percent) faster than using cout and writing character by character: #include <iostream> #include <vector> int main() { auto X_AxisLen = 10000u; auto Y_AxisLen = 10000u; auto characterMatrix = std::vector<std::vector<char>>(X_AxisLen, std::vector<char>(Y_AxisLen)); for (int row = 0; row < Y_AxisLen; ++row) { for (int col = 0; col < X_AxisLen; ++col) { std::cout << characterMatrix[row][col]; } } } % c++ test.cc -O3 -DNDEBUG -std=c++17 -I include src/format.cc -o test-cout % time ./test-cout > /dev/null ./test-cout > /dev/null 4.30s user 0.08s system 95% cpu 4.581 total This example is a bit artificial, in real world the difference may not be as dramatic particularly if you turn off sync with stdio. However, the {fmt} result can also be improved by using format string compilation and the unsynchronized API (if you are writing to a file).
70,219,989
70,220,030
C++ (Atom GCC compiler) "no declaration matches 'int ClassName::FuncName(Paramaters)'" using non-numerical types / ignoring set type for default
I have been getting this Compiler/Linter Error every time I try to create a function member of a class with a return type other than int, double, and similar types. As far as I can tell, the compiler is setting the default int return type for these functions. But I can't figure out why. I have no excess header or cpp files in the directory, which I have also read can cause the problem. The error is shows up under the addSample function. error: no declaration matches 'int BinaryCounter::addSample(std::cxx11::string)' BinaryCounter::addSample(std::string sample) Using these .cpp and .h files. Main is currently empty. #include <vector> #include <string> class BinaryCounter { public: BinaryCounter(); BinaryCounter(std::string sample); ~BinaryCounter(); std::vector<int> addSample(std::string sample); std::vector<int> oneCountColumns; int binaryLength; }; #include "BinaryCounter.h" BinaryCounter::BinaryCounter() { } BinaryCounter::~BinaryCounter() { } BinaryCounter::BinaryCounter(std::string sample) { binaryLength = sample.length(); } BinaryCounter::addSample(std::string sample) { return oneCountColumns; }
std::vector<int> addSample(std::string sample); returns an std::vector<int>, so at your cpp file you have to return the same type like this: std::vector<int> BinaryCounter::addSample(std::string sample) { return oneCountColumns; }
70,220,130
70,296,697
How can I "join" quadratic or cubic splines?
I have 2 function to either calculate a point on a spline, quadratic or cubic: struct vec2 {float x, y;}; vec2 spline_quadratic(vec2 & a, vec2 & b, vec2 & c, float t) { return { (1 - t) * (1 - t) * p1.x + 2 * (1 - t) * t * p2.x + t * t * p3.x, (1 - t) * (1 - t) * p1.y + 2 * (1 - t) * t * p2.y + t * t * p3.y }; } vec2 spline_cubic(vec2 & a, vec2 & b, vec2 & c, vec2 & d, float t){ return { //B(t) = (1-t)**3 p0 + 3(1 - t)**2 t P1 + 3(1-t)t**2 P2 + t**3 P3 (1 - t) * (1 - t) * (1 - t) * p1.x + 3 * (1 - t) * (1 - t) * t * p2.x + 3 * (1 - t) * t * t * p3.x + t * t * t * p4.x, (1 - t) * (1 - t) * (1 - t) * p1.y + 3 * (1 - t) * (1 - t) * t * p2.y + 3 * (1 - t) * t * t * p3.y + t * t * t * p4.y }; Is it possible to join several curves of an array of points? I'm looking to make a function that has this signature: vector<vec2> spline_join(vector<vec2> & points, int segments = 16){ vector<vec2> spline_points; for(int i = 0; i < points.size()-2; ++i){ for(int div = 0; div < segments; ++div){ spline_points.push_back(spline_quadratic(points[0], points[1], points[2], 1.f/segments); } } } I've read that it requires interpolation, but I'm not sure... What would the code look like? I've searched and I can't find relevant question and answers... I've seen there are libraries, but I'm looking for a shorter implementation. Edit: I've tried the question and answer here and apparently this is what I want: Joining B-Spline segments in OpenGL / C++ The code is not really clean but after some cleaning, it does work.
I've cleaned this answer Joining B-Spline segments in OpenGL / C++ This is not an Hermite spline, an hermite spline passes through the points, a B-spline does not. Here is what worked and the result float B0(float u) { //return float(pow(u - 1, 3) / 6.0); // (1-t)*(1-t)*(1-t)/6.f return float(pow(1-u, 3) / 6.0); } float B1(float u) { return float((3 * pow(u, 3) - 6 * pow(u, 2) + 4) / 6.0); // (3 * t * t * t - 6 * t * t + 4) / 6 } float B2(float u) { return float((-3 * pow(u, 3) + 3 * pow(u, 2) + 3 * u + 1) / 6.0); // (-3 * t * t * t + 3 * t * t + 3 * t + 1) / 6 } float B3(float u) { return float(pow(u, 3) / 6.0); // t * t * t / 6 } vector<Vec2> computeBSpline(vector<Vec2>& points) { vector<Vec2> result; int MAX_STEPS = 100; int NUM_OF_POINTS = points.size(); for (int i = 0; i < NUM_OF_POINTS - 3; i++) { //cout << "Computing for P" << i << " P " << i + 1 << " P " << i + 2 << " P " << i + 3 << endl; for (int j = 0; j <= MAX_STEPS; j++) { float u = float(j) / float(MAX_STEPS); float Qx = B0(u) * points[i].x + B1(u) * points[i + 1].x + B2(u) * points[i + 2].x + B3(u) * points[i + 3].x; float Qy = B0(u) * points[i].y + B1(u) * points[i + 1].y + B2(u) * points[i + 2].y + B3(u) * points[i + 3].y; result.push_back({ Qx, Qy }); //cout << count << '(' << Qx << ", " << Qy << ")\n"; } } return result; }
70,220,154
70,220,186
Assign another name/alias for std::vector
I am trying to give std::vector a different name like MyVector, so I did following typedef typedef std::vector<float> MyVector<float>; However, visual studio complains on MyVector that "MyVector is not a template" How do I assign std::vector another name? I have may MyVector in my code which is essentially std::vector, so I just want to equal std::vector with MyVector so I don't have to change all the MyVector into std::vector.
What you want is an alias template, like this: template <typename T> using MyVector = std::vector<T>; That will allow you to use it like this: MyVector<float> vec = stuff; Where vec will be a std::vector<float>.
70,220,263
70,220,312
Getting multiple inputs from one line from a file in c++
Basically, I'm attempting to get three things from one line of code, read from a .txt file. This will be repeated, but for now I only need to know how to get one line. The line I'm reading looks like this: Biology $11 12 So I want to get a string, and two ints, and completely ignore the $ (note, I cannot change the .txt file, so i have to leave the $ in) So if I have string subject; int biologyscores[25]; The code I have is : int biologyscores[25]; //array to store the integer values std::string subject; //string to store the subject the scores are for std::ifstream infile("myScores.txt"); //declare infile to read from "myScores.txt" infile >> subject >> biologyscores[0] >> biologyscores [1]; //read into string and int array So the string will be used to check which subject these scores are for, and the scores themselves will be stored in an array biologyscores, indexed next to each other. The problem is after this code executes, subject = "Biology" which is desired, but biologyscores at index 0 and 1 both seem to have junk numbers, not what I want to read into them.
You can use a dummy character variable which will "pick up" $ character: char dummy_char; infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1]; //read into string and int array
70,220,397
70,370,535
Android Studio Error Message: Use Of Undeclared Identifier 'accept4'
the jni folder not appear in android studio and after build only java folder get build. as you can see the jni folder appear in explorer but not inside android studio. EDIT: so after i added this in my build.gradle externalNativeBuild { ndkBuild { path 'src/main/jni/Android.mk' } } the jni folder appered as cpp folder name but when i compile i get this error from SocketServer.cpp: use of undeclared identifier 'accept4' This is the code : bool SocketServer::Accept() { if ((acceptfd = accept4(listenfd, nullptr, nullptr, SOCK_CLOEXEC)) < 0) { Close(); return false; } return true; } and headers is already includes: #include <sys/types.h> #include <sys/socket.h>
i get pass the error "use of undeclared identifier 'accept4'" by setting these : from compileSdkVersion 29 to compileSdkVersion 30 from buildToolsVersion "29.0.3" to buildToolsVersion "30.0.3" from minSdkVersion 21 to minSdkVersion 22 from targetSdkVersion 29 to targetSdkVersion 30
70,220,404
70,220,836
Question on dynamic allocation in vectors
#include <iostream> #include <vector> #include "malloc.h" using namespace std; int main() { // Write C++ code here vector<vector<vector<int*>>> storage; for (int i=0; i< 13; i++) { storage.push_back(vector<vector<int*>>()); for (int j=0; j< 13; j++) { storage[i].push_back(vector<int*>()); storage[i][j].push_back((int*)malloc(5 * sizeof(int))); for (int k =0; k<4; k++) { storage[i][j][k]=k; } } } return 0; } I am trying to dynamically allocate a list inside the innermost dimension of the last vector, but it turns out it throws some compilation error when I try to set a value to the vector: error: invalid conversion from 'int' to '__gnu_cxx::__alloc_traits<std::allocator<int*>, int*>::value_type' {aka 'int*'} [-fpermissive]
The error message is telling you that you are trying to assign an int to an int*. Specifically, on this statement: storage[i][j][k]=k; storage[i][j][k] returns (a reference to) an int*, but k is an int. Since you have 3 levels of vectors containing an int[] array, you need 4 loops to initialize the individual ints, but you only have 3 loops, so add another loop: #include <iostream> #include <vector> using namespace std; int main() { vector<vector<vector<int*>>> storage; for (int i = 0; i < 13; ++i) { storage.push_back(vector<vector<int*>>()); for (int j = 0; j < 13; ++j) { storage[i].push_back(vector<int*>()); for(int k = 0; k < N; ++k) // <-- decide what N should be! { storage[i][j].push_back(new int[5]); for (int m = 0; m < 5; ++m) { storage[i][j][k][m] = k; } } } } // don't forget to delete[] all of the new[]'ed arrays! // consider using either std::unique_ptr<int[]> or // std::array<int,5> instead of int* ... return 0; } I would suggest simplifying the code to make it more readable, eg: #include <iostream> #include <vector> #include <array> using namespace std; using arr5Ints = array<int, 5>; using vec1D_arr5Ints = vector<arr5Ints>; using vec2D_arr5Ints = vector<vec1D_arr5Ints>; using vec3D_arr5Ints = vector<vec2D_arr5Ints>; int main() { vec3D_arr5Ints storage( 13, vec2D_arr5Ints( 13, vec1D_arr5Ints(N) // <-- decide what N should be! ) ); for (auto &vec2d : storage) { for (auto &vec1d : vec2d) { for(auto &arr : vec1d) { int k = 0; for (int &i : arr) { i = k++; } } } } return 0; }
70,220,440
70,220,635
Weird syntax error in a simple code in C++
There is a weird syntax error in this code. I don't understand it or any of the errors. #pragma once #include <iostream> class Tree { public: Node* root; void InputTree() { int n, father; int nd; int child; char dir; std::cin >> n; int** tree = new int* [n]; for (int i = 0; i < n; i++) { std::cin >> nd; tree[i] = new int[3]; tree[i][0] = nd; tree[i][1] = -1; tree[i][2] = -1; } for (int i = 0; i < n - 1; i++) { std::cin >> father >> child >> dir; if (dir == 'L') tree[father][1] = child; else tree[father][2] = child; } Initialize(tree, 0); } private: void Initialize(int** tree, int headIndex) { if (headIndex != -1) { root->value = tree[headIndex][0]; root->right_tree->Initialize(tree, tree[headIndex][2]); root->left_tree->Initialize(tree, tree[headIndex][1]); } } }; class Node { public: int value; Tree* left_tree; Tree* right_tree; }; This is the build output of Visual Studio: Build started... 1>------ Build started: Project: CppMainProject, Configuration: Debug Win32 ------ 1>CppMainProject.cpp 1>tstream.h(5,6): error C2143: syntax error: missing ';' before '*' 1>tstream.h(5,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>tstream.h(5,12): error C2238: unexpected token(s) preceding ';' 1>tstream.h(33,4): error C2065: 'root': undeclared identifier 1>tstream.h(34,4): error C2065: 'root': undeclared identifier 1>tstream.h(35,4): error C2065: 'root': undeclared identifier 1>Done building project "CppMainProject.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
In lines like root->value = tree[headIndex][0];, you are trying to use the Node class before you have told the compiler what that class is. You can declare variables as pointers to classes before their full definition (but you need a forward declaration of the class to do so) but you can't dereference such pointers until after the full class definition has been provided. In your code, you can move the definition of the Node class to before the Tree class; but then, as that uses Tree pointers, you have to provide a forward declaration that Tree is a class. #pragma once #include <iostream> class Tree; // Forward declaration that this is a class... class Node { public: int value; Tree* left_tree; // ... so we can now declare pointers to "Tree" Tree* right_tree; }; class Tree { public: Node* root; // We can declare a pointer void InputTree() { // ... and then the rest of your code as is ... Some worthwhile reading: When can I use a forward declaration?
70,220,508
70,220,975
Template member function specialization of a templated class without specifying the class template parameter
What is the correct syntax to specialize a templated member function of a templated class without specifying the class template parameter? Here is what I mean: Example #1 (works): #include <iostream> struct C1 { template <class B> void f(void) const; }; template <> void C1::f<int>(void) const { std::cout<<777<<std::endl; } int main(void) { C1 c1; c1.f<int>(); } Example #2 (works): #include <iostream> template <class A> struct C2 { template <class B> void f(void) const; }; template <> template <> void C2<int>::f<int>(void) const { std::cout<<888<<std::endl; } int main(void) { C2<int> c2; c2.f<int>(); return 0; } Example #3 (does not compile: "enclosing class templates are not explicitly specialized"): #include <iostream> template <class A> struct C3 { template <class B> void f(void) const; }; struct D { static int g(void){ return 999; } }; template <class A> template <> void C3<A>::f<int>(void) const { std::cout<<A::g()+1<<std::endl; } template <class A> template <> void C3<A>::f<char>(void) const { std::cout<<A::g()+2<<std::endl; } int main(void) { C3<D> c3a; c3a.f<int >(); // expect to see 1000 C3<D> c3b; c3b.f<char>(); // expect to see 1001 return 0; } How can I make example #3 work?
You can use a technique called tag dispatch and replace the template specialisations by function overloads. template<typename> struct Tag {}; template <class A> struct C3 { void f_impl(Tag<int>) const; void f_impl(Tag<char>) const; template<class B> void f() const { f_impl(Tag<B>{}); } }; struct D { static int g(void){ return 999; } }; template <class A> void C3<A>::f_impl(Tag<int>) const { std::cout<<A::g()+1<<std::endl; } template <class A> void C3<A>::f_impl(Tag<char>) const { std::cout<<A::g()+2<<std::endl; } Then your call site looks exactly as you want: C3<D> c3; c3.f<int>(); // expect to see 1000 C3<D> c4; c4.f<char>(); // expect to see 1001 Full example here.
70,221,058
70,221,082
C++ is there way to access a std::vector element by name?
I am experimenting with a simple vertex class. class Vertex { public: std::vector<float> coords; //other functionality here - largely irrelevant }; And lets say we create a Vertex object as below: Vertex v0(1.f, 5.f, 7.f); I am wondering if there is anyway to assign a name to each element of a vector? Let's say that each std::vector will only ever have a size of 3. I know I can access an element or index of the vector in a way such as v0.coords[0] through to v0.coords[2]; However, I am wondering if there is a way in which I could assign a name to each element of the vector, ie: v0.coords.x == v0.coords[0]; v0.coords.y == v0.coords[1]; v0.coords.z == v0.coords[2]; So that if I was to access the vector, I could access via a name rather than an index. Is such a thing possible? If so, how do I go about creating such aliasing?
I am wondering if there is anyway to assign a name to each element of a vector? No, there is not. At least, not the way you want. I suppose you could use macros, eg: #define coords_x coords[0] #define coords_y coords[1] #define coords_x coords[2] Now you can use v0.coords_x, v0.coords_y, and v0.coords_z as needed. Or, you can use getter methods, eg: class Vertex { public: vector<float> coords; //other functionality here - largely irrelevant float& x(){ return coords[0]; } float& y(){ return coords[1]; } float& z(){ return coords[2]; } }; Now you can use v0.x(), v0.y(), and v0.z() as needed. But really, in this situation, there is just good no reason to use a vector at all. It is simply the wrong tool for the job. Use a struct instead, eg: struct Coords { float x; float y; float z; }; class Vertex { public: Coords coords; //other functionality here - largely irrelevant }; Alternatively: class Vertex { public: struct { float x; float y; float z; } coords; //other functionality here - largely irrelevant }; Now you can use v0.coords.x, v0.coords.y, and v0.coords.z as needed.
70,221,439
70,221,794
c++ ifstream to stringstream using getline()
I am making a bowling program for school that stored scores in a text file with the format: paul 10 9 1 8 1, ...etc jerry 8 1 8 1 10 ...etc ...etc I want to read the file into a stringstream using getline() so I can use each endl as a marker for a new player's score (because the amount of numbers on a line can be variable, if you get a spare or strike on round 10). I can then read the stringstream using >> to get each score and push it into a vector individually. However, when trying to use getline(fstream, stringstream), I get an error no instance of overloaded function "getline" matches the argument list -- argument types are: (std::fstream, std::stringstream) How can I make this work? My code looks like this: #include <iostream> #include <vector> #include <fstream> #include <exception> #include <string> #include <sstream> using namespace std; //other parts of the program which probably don't matter for this error vector <int> gameScore; vector<string> playerName; int i = 0; int j = 0; string name; int score; stringstream line; while (in.good()){ //in is my fstream playerName.push_back(name); cout << playerName[i] << " "; i++; getline(in, line); while (line >> score){ gameScore.push_back(score); cout << gameScore[j] << " "; j++; } }
You can't use std::getline() to read from a std::ifstream directly into a std::stringstream. You can only read into a std::string, which you can then assign to the std::stringstream, eg: vector<int> gameScore; vector<string> playerName; string name, line; int score; while (getline(in, line)){ istringstream iss(line); iss >> name; playerName.push_back(name); cout << name << " "; while (iss >> score){ gameScore.push_back(score); cout << score << " "; } }
70,221,889
70,221,952
Decrypt rotating XOR with 10-byte key across packet bytes in C++
Trying to figure out how to write something in C++ that will decrypt a rotating XOR to packet bytes that will be in varying sizes with a known 10 byte key (key can be ascii or hex, whatever is easier). For example: XOR 10-byte key in hex: 41 30 42 44 46 4c 58 53 52 54 XOR 10-byte key in ascii: A0BDFLXSRT Here is "This is my message in clear text" in hex that needs to be decrypted with above key 15 58 2B 37 66 25 2B 73 3F 2D 61 5D 27 37 35 2D 3F 36 72 3D 2F 10 21 28 23 2D 2A 73 26 31 39 44 I need a way to apply my XOR key over the top of these bytes like this in a rotating fashion: 41 30 42 44 46 4c 58 53 52 54 41 30 42 44 46 4c 58 53 52 54 41 30 42 44 46 4c 58 53 52 54 52 54 15 58 2B 37 66 25 2B 73 3F 2D 61 5D 27 37 35 2D 3F 36 72 3D 2F 10 21 28 23 2D 2A 73 26 31 39 44 When I XOR these together, I get the data in readable format again: "This is my message in clear text" I've seen some examples that take the entire XOR key and apply it to each byte, but that's not what I need. It needs to somehow rotate over the bytes until the end of the data is reached. Is there anyone who can assist?
Use the % (modulus) operator! using byte_t = unsigned char; std::vector< byte_t > xor_key; std::vector< byte_t > cipher_text; std::string plain_text; plain_text.reserve( cipher_text.size( ) ); for( std::size_t i = 0; i < cipher_text.size( ); ++i ) { auto const cipher_byte = cipher_text[ i ]; // i % xor_key.size( ) will "rotate" the index auto const key_byte = xor_key[ i % xor_key.size( ) ]; // xor like usual! plain_text += static_cast< char >( cipher_byte ^ key_byte ); }
70,222,595
70,222,686
std::complex<float> with error C2106: '=': left operand must be l-value
I performed fast Fourier transform (fft) on my signal, turning it into signalComplex; signal is a series of real float numbers and signalComplex represents a series of complex numbers: std::vector<std::complex<float>> signalComplex(numSamplesPerScan); // int numSamplesPerScan fft.fwd(signalComplex, signal); // std::vector<float> signal for (int n = 1; n < numSamplesPerScan / 2; n++) // simplified procedure to calculate HT { float real = signalComplex[n].real(); // positive frequency X 2 float imag = signalComplex[n].imag(); real *= 2; imag *= 2; signalComplex[n].real() = real; // compiler complains here signalComplex[n].imag() = imag; // compiler complains here signalComplex[n + numSamplesPerScan / 2].real() = 0; // compiler complains here signalComplex[n + numSamplesPerScan / 2].imag() = 0; // compiler complains here } In the for loop above, I am trying to do some simple computation on real and imaginary parts of the signalComplex. However, the compiler complains about "error C2106: '=': left operand must be l-value"; I am not sure how to do computation on the real imaginary parts in this case. Any pointer is appreciated. Some code is highly appreciated.
I want to thank all people here that were trying to help me. Like Brian pointed out, the code in the questions is modified to std::vector<std::complex<float>> signalComplex(numSamplesPerScan); fft.fwd(signalComplex, signal); for (int n = 1; n < numSamplesPerScan / 2; n++) { signalComplex[n] = { signalComplex[n].real()*2, signalComplex[n].imag()*2 }; // following is the key part signalComplex[n + numSamplesPerScan / 2] = {0, 0}; } and it compiles just fine.
70,222,629
70,238,555
Can boost spin_condition be used for process synchronization?
I see below code in interprocess_condition, I know that interprocess_condition is used for process synchronization, but I am not sure whether spin_condition can be. private: #if defined(BOOST_INTERPROCESS_CONDITION_USE_POSIX) ipcdetail::posix_condition m_condition; #elif defined(BOOST_INTERPROCESS_CONDITION_USE_WINAPI) ipcdetail::winapi_condition m_condition; #else ipcdetail::spin_condition m_condition; // this condition #endif doubt Because I found that the spin_condition is implemented through the volatile keyword variable. Can volatile keyword variables be used as shared memory between processes? spin_mutex m_enter_mut; volatile boost::uint32_t m_command; volatile boost::uint32_t m_num_waiters;
It can. Memory is just that, memory. If you share it between processes, it effectively makes threads from different processes behave like threads from the same process in relation to that memory location. However, unless lock contention is very rare, a spin-lock without back-off is recipe for very inefficient power consumption and throughput. Alternatively, if efficiency is not your concern but you care about absolute latency, you will have to be in strict control of thread scheduling (how many threads coexist on the same machine/NUMA node/..., thread affinity, thread priority and real-time scheduling options to name a few). In practice, you won't have that control unless you already knew the answers to your question, so the recommendation must be to stay away from spin-lock-only synchronization.
70,222,956
70,223,245
Is it possible to use a dynamic number of range adaptors?
I am fairly new to ranges, and I wanted to know if there was a way to apply a dynamic number of range adaptors. I have fiddled around with some code for a while, and I have also done some searching, but to no avail. #include <iostream> #include <ranges> int main() { auto output = std::ranges::views::iota(2, 100); for (int i = 2; i < 100; i++) { output = output | std::ranges::views::filter([i](int num){ return num % i != 0 || num == i; }); } std::cout << "The 10th prime is: " << output[9] << "\n"; } Essentially, I want something like this, but this gives a compile error (no match for 'operator='). It seems that each application of a range adaptor requires a new type, so we can't dynamically create this range. Is there some way around this?
For a fixed number like this, it would be possible to use metaprogramming to recursively build the range (although you might hit a template instantiation depth limit). You can do a truly dynamic number by type-erasing the ranges, such that the chain of filters is connected by virtual function calls. The result is slow and the code is painful, but it’s certainly possible.
70,223,022
70,223,078
C++ for loop ends after input
#include <iostream> #include <string> using namespace std; struct Student { string name; string hometown; int age; int games; int* hours = new int [games]; }; int main(){ int players; Student* s = new Student [players]; cout << "How many esports players are there at TTU who major in csc?\n"; cin >> players; cout << "\nPlease enter in information about each player: \n\n"; for(int i = 0; i < players; i++){ cout << "PLAYER " << (i + 1) << ":\n"; cout << "\tNAME:\t"; getline(cin >> ws, s[i].name); cout << "\tHOMETOWN:\t"; getline(cin >> ws, s[i].hometown); cout << "\tAGE:\t"; cin >> s[i].age; cout << "\tHOW MANY GAMES DOES " << s[i].name << " PLAY?\t"; cin >> s[i].games; for(int j = 0; j < s[i].games; j++){ cout << "NUMBER OF HOURS " << s[i].name << "PLAYED GAME" << (j + 1) << "\t"; cin >> s[i].hours[j]; } } return 0; } For some reason, the for loop is ending after asking for age. I have tried with multiple inputs and it does the same thing. I am new to c++. Does anyone know why? Thank you for your time
You are not handling arrays correctly. You are allocating them using uninitialized variables for their sizes: in int games; int* hours = new int [games];, games is uninitialized. in int players; Student* s = new Student [players];, players is uninitialized. And, even if you were allocating the arrays correctly, you would be leaking them, since you are not freeing them when you are done using them. When you need to use an array whose size is not known until runtime, you are correct to use new[], but not until after you determine the size, eg: #include <iostream> #include <string> using namespace std; struct Student { string name; string hometown; int age = 0; int games = 0; int* hours = nullptr; }; int main(){ cout << "How many esports players are there at TTU who major in csc?\n"; int players; cin >> players; Student *s = new Student[players]; cout << "\nPlease enter in information about each player: \n\n"; for(int i = 0; i < players; ++i){ cout << "PLAYER " << (i + 1) << ":\n"; cout << "\tNAME:\t"; getline(cin >> ws, s[i].name); cout << "\tHOMETOWN:\t"; getline(cin >> ws, s[i].hometown); cout << "\tAGE:\t"; cin >> s[i].age; cout << "\tHOW MANY GAMES DOES " << s[i].name << " PLAY?\t"; cin >> s[i].games; s[i].hours = new int[s[i].games]; for(int j = 0; j < s[i].games; ++j){ cout << "NUMBER OF HOURS " << s[i].name << " PLAYED GAME " << (j + 1) << "\t"; cin >> s[i].hours[j]; } } // use player info as neded... for(int i = 0; i < players; ++i){ delete[] s[i].hours; } delete[] s; return 0; } That being said, you should use std::vector instead of new[]/delete[] manually, eg: #include <iostream> #include <string> #include <vector> using namespace std; struct Student { string name; string hometown; int age = 0; int games = 0; std::vector<int> hours; }; int main(){ cout << "How many esports players are there at TTU who major in csc?\n"; int players; cin >> players; std::vector<Student> s(players); cout << "\nPlease enter in information about each player: \n\n"; for(int i = 0; i < players; ++i){ cout << "PLAYER " << (i + 1) << ":\n"; cout << "\tNAME:\t"; getline(cin >> ws, s[i].name); cout << "\tHOMETOWN:\t"; getline(cin >> ws, s[i].hometown); cout << "\tAGE:\t"; cin >> s[i].age; cout << "\tHOW MANY GAMES DOES " << s[i].name << " PLAY?\t"; cin >> s[i].games; s[i].hours.resize(s[i].games); for(int j = 0; j < s[i].games; ++j){ cout << "NUMBER OF HOURS " << s[i].name << " PLAYED GAME " << (j + 1) << "\t"; cin >> s[i].hours[j]; } } // use player info as needed... return 0; }
70,223,348
70,223,379
'this' keyword used in class and objects is a constant pointer?
This question came in my mind due to the following error in my c++ program #include <iostream> using namespace std; class Test { private: int x; public: Test(int x = 0) { this->x = x; } void change(Test *t) { this = t; } void print() { cout << "x = " << x << endl; } }; int main() { Test obj(15); Test *ptr = new Test (100); obj.change(ptr); obj.print(); return 0; } Error: main.cpp:18:31: error: lvalue required as left operand of assignment 18 | void change(Test *t) { this = t; } | I searched about this error and found that it generally occurs when we try to assign the constants on the left hand side of the assignment operators to the variable on the right hand side. Please correct me if I am wrong. Thanks
According to 9.3.2 The this pointer [class.this] 1 In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. [...] So as the error says, the left hand side should be an lvalue but you're giving it a prvalue because change is a non-static member function and inside any non-static member function the keyword this is a prvalue according to the above quoted statement. Hence the error. But you can modify the object that this points to, as shown below: #include <iostream> using namespace std; class Test { private: int x; public: Test(int x = 0) { this->x = x; } void change(Test *t) { *this = *t; }//THIS WORKS void print() { cout << "x = " << x << endl; } }; int main() { Test obj(15); Test *ptr = new Test (100); obj.change(ptr); obj.print(); return 0; } Note in the above example i have replaced this = t; with *this = *t;//this time it works because now the left hand side is an lvalue This time the program works because now the left hand side is an lvalue. Some More Explanation From IBM's this pointer documentation, The this parameter has the type Test *const. That is, it is a constant pointer to a Test object. Now since it is constant pointer, you cannot assign a different pointer value to it using this = t;. And hence the error. Similarly, from Microsoft's this pointer documentation, the this pointer is always a const pointer. It can't be reassigned. So this also explains the error you're getting.
70,223,662
70,223,741
Is there a way to delete a pointer that has not been assigned with new operator in the destructor? If so, should I delete it in the destructor?
For example, class Test{ private: int* foo; public: Test(int* foo){this->foo = foo;} } In this case, is there any way I can delete foo in the destructor? Will I have to delete foo in the destructor or at least set it to nullptr?
Sure, you can. It is legal syntax. And depending on the rest of your program, it might do what you want, or it might be a double delete (delete the same pointer twice) which corrupts the heap and will lead to an eventual crash. (Debugging compilers might catch this.) One of the reasons the C++ standard template library gave us shared_ptr and unique_ptr is that memory management by hand is hard. It isn't impossible; people did it (or tried to) for many, many years. But it was also a source of many runtime disasters, either the double delete (also called a premature free from the old malloc/free routines), or the opposite, a memory leak. Automatic memory management was one of Java’s selling points as a C/C++-similar language without the memory bug risk. Later C# made the same pitch to users. I suggest using the STL and thinking about the ownership semantics of your foo. Maybe the Test class should own it; maybe it should share it; maybe it should really have a weak reference. Can't tell from a program fragment. I can only say you should review modern ideas of memory management in C++ and adopt them.
70,224,159
70,224,694
how to display text file in c++?
I want to display the text file in my c++ program but nothing appears and the program just ended. I am using struct here. I previously used this kind of method, but now I am not sure why it isn't working. I hope someone could help me. Thanks a lot. struct Records{ int ID; string desc; string supplier; double price; int quantity; int rop; string category; string uom; }record[50]; void inventory() { int ID, quantity, rop; string desc, supplier, category, uom; double price; ifstream file("sample inventory.txt"); if (file.fail()) { cout << "Error opening records file." <<endl; exit(1); } int i = 0; while(! file.eof()){ file >> ID >> desc >> supplier >> price >> quantity >> rop >> category >> uom; record[i].ID = ID; record[i].desc = desc; record[i].supplier = supplier; record[i].price = price; record[i].quantity = quantity; record[i].rop = rop; record[i].category = category; record[i].uom = uom; i++; } for (int a = 0; a < 15; a++) { cout << "\n\t"; cout.width(10); cout << left << record[a].ID; cout.width(10); cout << left << record[a].desc; cout.width(10); cout << left << record[a].supplier; cout.width(10); cout << left << record[a].price; cout.width(10); cout << left << record[a].quantity; cout.width(10); cout << left << record[a].rop; cout.width(10); cout << left << record[a].category; cout.width(10); cout << left << record[a].uom << endl; } file.close(); } Here is the txt file:
Here are a couple of things you should consider. Declare the variables as you need them. Don’t declare them at the top of your function. It makes the code more readable. Use the file’s full path to avoid confusions. For instance "c:/temp/sample inventory.txt". if ( ! file ) is shorter. To read data in a loop, use the actual read as a condition while( file >> ID >>... ). This would have revealed the cause of your problem. Read about the setw manipulator. file's destructor will close the stream - you don't need to call close() Your file format consists of a header and data. You do not read the header. You are trying to directly read the data. You try to match the header against various data types: strings, integers, floats; but the header is entirely made of words. Your attempt will invalidate the stream and all subsequent reading attempts will fail. So, first discard the header – you may use getline. Some columns contain data consisting of more than one word. file >> supplier reads one word, not two or more. So you will get "Mongol", not "Mongol Inc." Your data format needs a separator between columns. Otherwise you won’t be able to tell where the column ends. If you add a separator, again, you may use getline to read fields. The CATEGORY column is empty. Trying to read it will result in reading from a different column. Adding a separator will also solve the empty category column problem. This is how your first rows will look like if you use comma as separator: ID,PROD DESC,SUPPLIER,PRICE,QTY,ROP,CATEGORY,UOM 001,Pencil,Mongol Inc.,8,200,5,,pcs A different format solution would be to define a string as a zero or more characters enclosed in quotes: 001 "Pencil" "Mongol Inc." 8 200 5 "" "pcs" and take advantage of the quoted manipulator (note the empty category string): const int max_records_count = 50; Record records[max_records_count]; istream& read_record(istream& is, Record& r) // returns the read record in r { return is >> r.ID >> quoted(r.desc) >> quoted(r.supplier) >> r.price >> r.quantity >> r.rop >> quoted(r.category) >> quoted(r.uom); } istream& read_inventory(istream& is, int& i) // returns the number of read records in i { //... for (i = 0; i < max_records_count && read_record(is, records[i]); ++i) ; // no operation return is; }
70,224,226
70,224,317
What is the meaning of {{strs[0}} and how does it work?
I came accross this code on leetcode, but I am not getting how {{strs[0]}} works (Line no. 6) class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { // Base case if(strs.size() == 1) return {{strs[0]}}; vector<vector<string>> ans; unordered_map<string, vector<string>> M; for(int i = 0; i < strs.size(); i++) { string str = strs[i]; sort(strs[i].begin(), strs[i].end()); // Sorting the string M[strs[i]].push_back(str); // Sorted string is the key and the value is the initial string } for(auto i = M.begin(); i != M.end(); i++) ans.push_back(i -> second); // Traversing the map and adding the vectors of string to ans return ans; } };
strs is a vector of strings, where strs[0] is the 1st string. The function returns a vector of vectors of strings. In the syntax {{strs[0]}}, the outer {} represents the outer vector. Inside of the {} is a comma-separated list of the vector's elements. Since the element type of the outer vector is another vector, each element is wrapped in its own{}. In this case, there is 1 element. And the element type of the inner vector is a string. So, the return statement is returning a vector that holds 1 vector that holds the value of strs[0]. From a more technical perspective, each {} is converted by the compiler into a std::initializer_list that is then passed to std::vector's constructor. So, the return statement in question is roughly equivalent (not quite) to the following: std::string tempStr = strs[0]; std::initializer_list<std::string> init1(&tempStr, 1); std::vector<std::string> tempVec1(init1); std::initializer_list<std::vector<std::string>> init2(&tempVec1, 1); std::vector<std::vector<std::string>> tempVec2(init2); return tempVec2;
70,224,395
70,226,552
How to check if it's a silent installation from the custom action DLL?
When my installer is started with msiexec /q /i command line, is there a way to tell that it's a silent installation from my custom action C++ DLL? PS. I'm using WiX to build my MSI.
The UILevel property of Windows Installer will tell you whether the setup has been launched silently. Four different UI levels are possible: INSTALLUILEVEL_NONE - 2 - switch: /qn - Completely silent installation. INSTALLUILEVEL_BASIC - 3 - switch: /qb - Simple progress and error handling. INSTALLUILEVEL_REDUCED - 4 - switch: /qr - Authored UI, wizard dialogs suppressed. INSTALLUILEVEL_FULL - 5 - Authored UI with wizards, progress, errors (/qf). UILevel may be better used to condition a whole custom action to run or not run depending on what the UILevel is set to? Or you can get its value inside the custom action and change behavior accordingly. Essential Links: Determining UI Level from a Custom Action. Common problems with C++ Custom Actions Debugging Custom Actions Further Links: How do I add C# methods to an existing large wix script Debug C# custom actions Determine if this is unattended installation mode? UPDATE: From the old Wise Command Line Builder tool, here are some options for the MSI GUI. Note the use of plus and minus to show or hide completion screen for silent install:
70,224,513
70,265,178
How to prefill edit boxes when my custom dialog is shown from the custom action script in my MSI?
I'm using WiX to create a custom dialog/page in my installer, based on WixUI_Mondo. The custom dialog has edit controls, similar to this: <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Fragment> <UI> <Dialog Id="ConfigDlg" Width="370" Height="270" Title="!(loc.SetupTypeDlg_Title)" > <Control Id="idTxt11" Type="Text" X="20" Y="65" Width="60" Height="16" Text="Name:" /> <Control Id="idEdt11" Type="Edit" X="90" Y="60" Width="120" Height="20" Default="yes" Property="PROP_NAME" /> <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" /> <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Text="!(loc.WixUINext)" /> <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)"> <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish> </Control> </Dialog> </UI> </Fragment> </Wix> I can read those controls from my custom action DLL (written in C++) when the Next button is clicked, by invoking it as such: <Publish Dialog="ConfigDlg" Control="Next" Event="DoAction" Value="idCA_NextBtn">1</Publish> but I also need to pre-populate those edit boxes when the page is first shown (by reading these values from the registry). This may be needed if someone is upgrading or repairing my software. The question is, how do I do that from my custom action?
For each property that you need read from the registry (for upgrades/repairs) just add a <RegistrySearch> element that populates those properties.
70,224,603
70,224,665
Double declaration and initialization of vector in a class, C++?
Good night dear all I have a question, look i working with classes and in many cases i am using vectors of vector (2D vectors), my code runs quite well. However, i am a bit confused, look in my header file i declared a vector of vectors in my protected variables, then in my cpp file in the constructors section i declared again the vector of vectors, but this time giving the needed sizes and having "0" in all the elements. However, when i tried to use this vector of vectors in my member function, it seems that not dimension was delcared and not "0" values, if i use .size() the output is "0" and i was expecting 3. However, when i declare again the vectors of vectors in the member (see commented line in the cpp file) function the code gives the 3 and the full matrix which is a 3 X 3, composed by "0". Why is that? using the constructor is to bassically give the values of the variables. See the next code, the commented line on the cpp file is on which i have declare again the vector. the header file is: #pragma once #include <iostream> #include <vector> class Matrix { private: const int m_nRows; const int m_nCols; protected: std::vector <std::vector <double>> MATRIX; public: Matrix(int rows, int cols); ~Matrix(); void getMatrix(); }; The cpp file is: #include "Matrix.h" Matrix::Matrix(int rows, int cols) : m_nRows(rows), m_nCols(cols) { std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0)); } Matrix::~Matrix() { } void Matrix::getMatrix() { //std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0)); std::cout << MATRIX.size() << std::endl; for (auto& columns : MATRIX) { for (auto& element : columns) { std::cout << element << " "; } std::cout << "\n"; } } The main file is: #include <iostream> #include <vector> #include "Matrix.h" int main() { int rows = 3; int cols = 3; Matrix SmallMatrix(rows, cols); SmallMatrix.getMatrix(); system("pause>0"); }
In your constructor: Matrix::Matrix(int rows, int cols) : m_nRows(rows), m_nCols(cols) { std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0)); } you define a brand new variable with the name MATRIX, which is totally distinct from the member variable Matrix::MATRIX. To initialize the Matrix::MATRIX member variable you should do it in the member initializer list, jut like for the m_nRows and m_nCols variables: Matrix::Matrix(int rows, int cols) : m_nRows(rows), m_nCols(cols), MATRIX(m_nRows, std::vector<double>(m_nCols, 0)) { }
70,224,680
70,224,804
argument of type "WCHAR *" is incompatible with parameter of type "LPCSTR" in c++
I know that there are lots of questions like this as it is a common error, I also know it is happening because I am using unicode. However, after reading through SO/microsoft docs and fixing the code, it still does not seem to work and I am stumped. The code is as follows: #include <Windows.h> #include <Tlhelp32.h> #include <string> DWORD find_pid(const char* procname) { // Dynamically resolve some functions HMODULE kernel32 = GetModuleHandleA("Kernel32.dll"); using CreateToolhelp32SnapshotPrototype = HANDLE(WINAPI *)(DWORD, DWORD); CreateToolhelp32SnapshotPrototype CreateToolhelp32Snapshot = (CreateToolhelp32SnapshotPrototype)GetProcAddress(kernel32, "CreateToolhelp32Snapshot"); using Process32FirstPrototype = BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32); Process32FirstPrototype Process32First = (Process32FirstPrototype)GetProcAddress(kernel32, "Process32First"); using Process32NextPrototype = BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32); Process32NextPrototype Process32Next = (Process32NextPrototype)GetProcAddress(kernel32, "Process32Next"); // Init some important local variables HANDLE hProcSnap; PROCESSENTRY32 pe32; DWORD pid = 0; pe32.dwSize = sizeof(PROCESSENTRY32); // Find the PID now by enumerating a snapshot of all the running processes hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hProcSnap) return 0; if (!Process32First(hProcSnap, &pe32)) { CloseHandle(hProcSnap); return 0; } while (Process32Next(hProcSnap, &pe32)) { //--->here is offending code... if (lstrcmpiA(procname, pe32.szExeFile) == 0) { pid = pe32.th32ProcessID; break; } } // Cleanup CloseHandle(hProcSnap); return pid; } I changed the code to this: if (strcmp(procname, pe32.szExeFile) == 0) { pid = pe32.th32ProcessID; break; } but still get the same error. Any ideas?
PROCESSENTRY32 uses wchars when you define UNICODE. The doc's are probably misleading. Tlhelp32.h defines this: #ifdef UNICODE #define Process32First Process32FirstW #define Process32Next Process32NextW #define PROCESSENTRY32 PROCESSENTRY32W #define PPROCESSENTRY32 PPROCESSENTRY32W #define LPPROCESSENTRY32 LPPROCESSENTRY32W #endif // !UNICODE As you can see, PROCESSENTRY32 maps to PROCESSENTRY32W if UNICODE is defined. pe32.szExeFile is a WCHAR szExeFile[MAX_PATH]; // Path That is the reason why strcmp fails with the error you get. strcmp expects a char* but you pass pe32.szExeFile, which in your case is a WCHAR*. Take real care to get the correct pointers to the helper functions. Are you getting the ANSI or UNICODE pointers? You are using a lot of C-style casts in the GetProcAddress calls. You can easily end up casting the return value to an ANSI style function, but using the UNICODE style pointer type.
70,225,008
70,225,062
Generate a number based on a given number of digits
I'm trying to write a program that generates a hex number based on a given number of digits. For instance, say that the user inputs 3, I want to generate a hex number of 0x000 and store it in some variable. Another example, say the user inputs 4 the hex number to be generated will be 0x0000. Any ideas? Thanks in advance.
0x0, 0x00, 0x000 and so on, when stored in a variable, all have the same effect. What you want to do is to store the desired number of digits in a separate variable and apply that configuration when selecting a representation of the value (be it 0 or otherwise) in output. For doing that in C++, I recommend the formatting features provided as described e.g. here: https://en.cppreference.com/w/cpp/io/manip/setw and at the links you find on that page as "See also".
70,225,120
70,225,189
How to access correct class member?
I've been running across this snippet of code and after execution I found out that everything compiles and executes fine (the int code member of the derived class is set to 65). However I was wondering how would one be able to access the char code member of the derived class? #include <iostream> using namespace std; class base { public: base() : code('B') { } char code; }; class derived : public base { public: int code; }; int main(void) { derived d; d.code = 65; std::cout << d.code; };
By specifying the correct scope for the base member variable using a qualified name lookup, as follows: d.base::code = 'x' std::cout << d.base::code << '\n'; See this section on qualified name lookups for more details.
70,225,218
70,225,375
C++ Primer Exercise 4.25 converting binary number
I have a question regarding the exercise 4.25 in C++ Primer: Exercise 4.25: What is the value of ~'q' << 6 on a machine with 32-bit ints and 8 bit chars, that uses Latin-1 character set in which 'q' has the bit pattern 01110001? I have the solution in binary, but I don't understand how this converts to int: int main() { cout << (std::bitset<8 * sizeof(~'q' << 6)>(~'q' << 6))<<endl; cout << (~'q' << 6) << endl; return 0; } After executing, the following 2 lines are printed: 11111111111111111110001110000000 -7296 The first line is what I expected, but I don't understand how is it converted to -7296. I would expect a lot larger number. Also online converters give a different result from this. Thanks in advance for the help.
In order to answer the question, we need to analyze what types are the partial expressions and what is the precedence of the operators in play. For this we could refer to character constant and operator precedence. 'q' represents an int as described in the first link: single-byte integer character constant, e.g. 'a' or '\n' or '\13'. Such constant has type int ... 'q' thus is equivalent to the int value of its Latin-1 code (binary 01110001) but expanded to fit a 32-bit integer: 00000000 0000000 00000000 01110001. The operator ~ precedes the operator << so the bitwise negation will be performed first. The results is 11111111 11111111 11111111 10001110. Then a bitwise shift left is performed (dropping the left 6 bits of the value and padding with 0-s on the right): 11111111 11111111 11100011 10000000. Now, regarding your second half of the question: cout << (~'q' << 6) << endl; interpretes this value as an int (signed). The standard states: However, all C++ compilers use two's complement representation, and as of C++20, it is the only representation allowed by the standard, with the guaranteed range from −2N−1 to +2N−1−1 (e.g. -128 to 127 for a signed 8-bit type). The two's complement value for 11111111 11111111 11100011 10000000 on a 32-bit machine results in the binary code for the decimal -7296. The number is not large as you would expect, because when you start from -1 decimal (11111111 11111111 11111111 11111111 binary) and count down, the binary representations all have a lot of leading 1-s. The leftmost bit is 1 for a negative number and 0 for a positive number. When you expand the negative value to more bits (e.g. from 32 to 64), you would add more 1-s to the left until you reach 64 bits. More information can be found here. And here is an online converter.
70,225,816
70,231,551
Finding and changing repeated letters in a word
I'm trying to create logic that goes through the word and tries to find if there are letters, that are used more than once. If a letter repeats, then change it to "1", if it's not then change it to "2". Example: Radar - 11211, Amazon - 121222, karate - 212122. Specific problem is that if I use for(), each letter compares to the last one. Also I don't understand how can I check last letter by using for(). Last letter is always 2. Here is my code: #include <iostream> #include <string> using namespace std; int main() { string word; char bracket1('1'); char bracket2('2'); cout << "Write your word: "; cin >> word; for (int i = 0; i < word.length(); ++i) { char let1 = word[i]; char let2 = word[i+1]; if (let1 == let2) { word[i] = bracket1;} else { word[i] = bracket2; } } cout << word; } Example: test returns 1e22 instead of 1221
You have undefined behavior in your program when wrote word[i+1]; inside the for loop. This is because you're going out of bounds for the last value of i by using i+1. One possible way to solve this would be to use std::map as shown below. In the program given std::tolower is used because you want capital and small letters to be treated the same. #include <iostream> #include <map> #include <algorithm> int main() { std::string word; std::cout << "Write your word: "; std::getline(std::cin, word); //print out the word before replacing with 1 and 2 std::cout<<"Before transformation: "<<word<<std::endl; std::map<char, int> charCount; //this map will keep count of the repeating characters //iterate through each character in the input word and populate the map for(char &c: word) { charCount[std::tolower(c)]++;//increment the value by 1 } //replace the repeating characters by 1 and non-repeating by 2 for(char &c: word) { if(charCount.at(std::tolower(c)) > 1) { c = '1'; } else { c = '2'; } } //print out the word after transformation std::cout<<"After transformation: "<<word<<std::endl; return 0; } The output of the program can be seen here. Output for the input Amazon is: Write your word: Amazon Before transformation: Amazon After transformation: 121222
70,225,854
70,225,879
How to use a static method as a callback in c++
I have a comparison/ordering function that relates to a class. I can use it if I define it as a separate closure object. I would like to make it into a static method of the class it operates on so it is tidier. I guessed how to do this but I get an error that I can't interpret. Generally I would like to know how to treat static methods as callable objects. Minimal related example code (not working): #include <set> class MyClass { // More code here static auto compare(MyClass a, MyClass b) { return a < b; } }; int main() { std::set<MyClass, decltype(MyClass::compare)> s(MyClass::compare); return 0; } Update, I'm not sure if my example confused the issue, so I updated it.
Couple of issues: compare is private, make it public. One must use & to get the address of functions. #include <set> class MyClass { public: static auto compare(int a, int b) { return a < b; } }; int main() { std::set<int, decltype(&MyClass::compare)> s(&MyClass::compare); return 0; }
70,226,047
70,226,452
Make a version file of macros which run at compile time
I want to ask if I can make a file of macros that basically defined at compile time and use these macros in my c++ code which compiles specific code if the condition is true. SO what is basically the extension for that file is it a .txt file or a .h file. and how to put this file in CmakeList.txt to make it executable at compile time. for example like this in a specific file? #define melodic 1 #define noetic 2
A C++ macro is a shortcut for writing code, what happens when you compile your project is that this code: #define SOMETHING 32 int i = SOMETHING Is changed to before it is compiled: int i = 32 So a macro just substitutes text wherever you place it. There is also another use of macros that maybe is what you are looking for. You can use the preprocessing directive #ifdef MACRO to compile some code conditionally. For example, let's say that you have a function that is only there for debugging, but you don't want that code to make it to release. You could define it like: void hello() { #ifdef DEBUG print("debug"); #endif } Then, if that file has a #define DEBUG before the #ifdef macro, the code will be included. Otherwise, the code will be discarded. Note that to use #ifdef the macro body may be empty or not, it just checks if the defined directive was used. What you might want to accomplish is to have a series of preprocessor macros that you either set or don't in a separate configuration file to change the code produced. They are a very powerful tool, but they must be use with caution since having too many can make code not very readable. To accomplish that, you need to include the #define MACRO in the same file that you are checking if it is defined, and before you check it. If you are only using that macro in that file, it would be good to place it at the top of it, but if you use it on multiple files you can create a header file (.h) and use #include "name.h", since include copies the contents of the header file there, therefore adding the macro definitions to your file. The preprocessor directives are dependent on the compiler, so the version and type of compiler you use (gcc, clang...) will have different support for them. However, defined and ifdef are very widely spread and most if not all compilers have them. I recommend reading more about directives, for example here. Finally, in case you go the route of the .h file, you would add it like any other header file you have in your project to the CmakeList.txt.
70,226,077
70,230,811
Interrupt ISR not triggering when using while loop
I am using an interrupt to turn a flag to True when data is ready from an external ADC. This interrupt is being triggered, however when I add: while(!dataReady); to wait for the interrupt to change the flag True, the interrupt ISR function no longer triggers. Here is my full code: static volatile bool dataReady = false; void dataReadyInterrupt() { dataReady = true; } MCP3464::MCP3464() { ch = 0; attachInterrupt(digitalPinToInterrupt(dataReadyPin), dataReadyInterrupt, RISING); } signed short MCP3464::read() { // wait for interrupt to turn dataReady True before reading next adc conversion while(!dataReady); dataReady = false; // SPI full duplex transfer digitalWrite(adcChipSelectPin,LOW); SPI.transfer(readConversionData); adcReading = (SPI.transfer(0) << 8); adcReading += SPI.transfer(0); digitalWrite(adcChipSelectPin, HIGH); ch++; if (ch >= numOfCh) { ch = 0; } // Write the new ADC channel to multiplexer writeData(&muxRegisters[ch][0], 2); // Start the next conversion (single conversion mode) writeData(&startConversionFastCmd, 1); return adcReading; } Any ideas much appreciated.
MCP3464::MCP3464() { ch = 0; attachInterrupt(digitalPinToInterrupt(dataReadyPin), dataReadyInterrupt, RISING); } You are setting up the interrupt through the class constructor, for standard C++ Class, this is perfectly fine. However, for Arduino, although you didn't mention how and where you instantiate the Class instance. But if you create a instance before setup(), your constructor run, and the Arduino has not initializes all the pins assignments and the system init yet, you can see this in the main function of Arduino Core. It is why most of the Arduino library uses a begin() method to setup the library instance instead of using the class constructor as Arduino Style Guide for Writing Libraries suggests to: Use begin() to initialize a library instance, usually with some settings. Use end() to stop it. One more thing, I noticed that you are using SPI.transfer() without using the SPI.beginTransaction() and SPI.endTransaction(), this may works for single instance of SPI or if you only had one SPI device on the bus, but you might facing problem/issue when you have multiple instances/devices. For that, I would suggest you read my answer to another question here.
70,226,290
70,226,697
Line spacing removal, empty line ignoring
I've got an issue with unnecessary spacing removal and empty line ignorance. So the code below -> reads a line from a file, gets all 5 values from the line (value1, ..., value5). Then the value5 is checked if it's a float, then it gets compared with a user input price and if the line's float value is less or equal to the user's input price, then that line's data is being printed out. That part is working, but it prints the data out with an empty line, unnecessary spacings just as in the given data file (db.csv -> see below). I guess the getline part in which it assigns the values to value1 etc is working ignoring the earlier spacing deletion. Any ideas? fstream file("db.csv", ios::in); string value1, value2, value3, value4, value5, line; float inputPrice, priceFile; cin >> inputPrice; if (file.is_open()) { cout << "result:" << endl; while (getline(file, line)) { if (!line.empty()) { line.erase(remove(line.begin(), line.end(), ' '), line.end()); getline(file, value1, ','); getline(file, value2, ','); getline(file, value3, ','); getline(file, value4, ','); getline(file, value5, '\n'); istringstream str(value5); str >> priceFile; if (priceFile <= inputPrice) { cout << value1 << " " << value2 << " " << value3 << " " << value4 << " " << value5 << endl; } } } DB.CSV FILE DATA BELOW Riga,Kraslava,Pr,15:00,11.00 Riga ,Kraslava,Pr ,18:00,11.00 Kraslava,Riga,Pr,08:00,11.00 Kraslava,Daugavpils,Ot ,10:00, 3.00 Ventsplis,8.00,Liepaja,Sv,20:00 Dagda,Sv Rezekne,Riga,Tr,13:00,10.50 Dagda,Kraslava, Ce,18:00, 2.50 Dagda,Kraslava,Ce,18:00,2.50,Sv Riga,Ventspils, Pt,09:00 , 6.70 Liepaja,Ventspils,Pt,17:00,5.50 OUTPUT BELOW 5.90 result: Kraslava Daugavpils Ot 10:00 3.00 Dagda Kraslava Ce 18:00 2.50,Sv Liepaja Ventspils Pt 17:00 5.50 REQUIRED OUTPUT BELOW 5.90 result: Kraslava Daugavpils Ot 10:00 3.00 Dagda Kraslava Ce 18:00 2.50 Liepaja Ventspils Pt 17:00 5.50
If you don't want empty lines to be printed then you can use the below shown program: #include <iostream> #include <sstream> #include <fstream> int main() { std::ifstream inputFile("input.txt"); std::string word1,word2,word3,word4,word5,line; float price;//price take from user std::cin >> price; float priceFile; //price read from file if(inputFile) { while(std::getline(inputFile,line) )//read line by line { //check if line is/isnot empty if(!line.empty()) { std::istringstream ss(line); while(std::getline(ss, word1,','),//read the first word std::getline(ss, word2,','),//read the second word std::getline(ss, word3,','),//read the third word std::getline(ss, word4,','),//read the fourth word std::getline(ss, word5) ) { std::istringstream ss2(word5); ss2 >> priceFile; //check if(priceFile <= price) { //remove space from here if you need std::cout<<word1 <<" "<<word2<<" "<<word3<<" "<<word4<<" "<<priceFile<<std::endl; } } } } } else { std::cout<<"Input file cannot be openede"<<std::endl; } } The output of the program can be seen here.
70,226,584
70,226,912
Why should I prefer a separate function over a static method for functional programming in c++?
In my other question, How to use a static method as a callback in c++, people solved my practical problem, then suggested I take a different approach in general to follow best practice. I would like a better understanding of why. This example uses a comparator, but I would really like to understand if there is a general rule for functional programming (for example perhaps also aggregator functions related to a class etc.) Example use case for a comparator function: #include <set> int main() { std::set<MyClass, decltype(SOMETHING_HERE)> s(SOMETHING_HERE); return 0; } Below are solutions I am aware of, from most to least recommended (I believe) - the opposite order to what I would currently choose. 1. Recommended way (I believe) with a functor: struct MyComparator { bool operator() (MyClass a, MyClass b) const { return a > b; // Reversed } }; std::set<MyClass, MyComparator)> s; I don't like: verbose; not lexically tied to MyClass; I don't understand why s has no constructor argument. I am confused about the lack of argument because set seems to mix up/combine deciding the comparison algorithm at compile time / with the typesystem (as in this example), and at runtime / with a pointer. If it was just one way or the other I would be fine with "that's just how it is". 2. A method that seems nicer to me: auto const my_comparator = [](int a, int b) { return a > b; }; std::set<int, decltype(my_comparator)> s(my_comparator); It's terser. Intention is clear: it is a function, not a class that could be potentially added to. Passing the object, not just the type, makes sense to me (couldn't there be 2 different implementations). 3. The method that makes most sense to me (based on other languages): class MyClass { public: // More code here static auto compare_reverse(MyClass a, MyClass b) { return a > b; } }; std::set<int, decltype(&MyClass::compare_reverse)> s(&MyClass::compare_reverse); It is clearly related (and lexically tied to) MyClass. Seems efficient (though I have been told it's not) and terse. Any explanation why the recommended order is better, performance, bugs/maintainability, philosophical, very appreciated.
Firstly, note that if you just want a > comparator, there are std::greater<> and std::greater<MyClass> (the former is usually superior). Reviewing the options you listed: (1) struct MyComparator { bool operator()(MyClass a, MyClass b) const { return a > b; } }; std::set<MyClass, MyComparator)> s; As you said, this is the recommended way. not lexically tied to MyClass As suggested in the comments, you can put it inside MyClass. don't understand why s has no constructor argument If you don't pass the comparator to the constructor, the comparator is default-constructed (if it's default-constructible, otherwise you get a compilation error). You can pass MyComparator{} manually, but there is no point. (2) auto my_comparator = [](int a, int b) { return a > b; }; std::set<int, decltype(my_comparator)> s(my_comparator); It's exactly equivalent to (1), except you're forced to pass my_comparator to the constructor. C++20 fixed this by making lambdas default-constructible (if they have no captures), making the argument unnecessary. (3) class MyClass { public: static auto compare_reverse(MyClass a, MyClass b) { return a > b; } }; std::set<int, decltype(&MyClass::compare_reverse)> s(&MyClass::compare_reverse); This gives you an extra feature: you can choose the comparator at runtime, by passing different functions to the constructor. This ability comes with an overhead: the set stores a pointer to the function (normally 4 or 8 bytes), and has to look at the pointer when making comparisons. (3.5) You can wrap your function in std::integral_constant. The result is equivalent to (1). bool foo(int x, int y) {return x > y;} std::set<int, std::integral_constant<decltype(&foo), foo>> s; // Or: using MyComparator = std::integral_constant<decltype(&foo), foo>; std::set<int, MyComparator> s; This is good if you're dealing with an existing type, that provides the comparator as a function, and you don't want the overhead of (3). All of those (except (3)) are equivalent. If std::greater<> is applicable, you should use it. Otherwise I'd recommend (1) as the least confusing option.
70,226,784
70,226,975
How to extract the size of a type from a binary without running or using special tools
I want to extract the size of certain types from an object file / library without running the binary without special tools for any toolchain (GNU, MSVC, IAR) I'd like to follow the approach presented here, but in a more generic form. Ideally it would work like this: // Some file.cpp class MyClass { // lots of members }; #include "SizeInfo.h" const SizeInfo<MyClass, "MyIdentifier"> info; I would put SizeInfo anywhere I am interested in the size of a type. I might be interested in multiple types per translation unit. The solution should put the string SizeOf MyIdentifier:1234 into the resulting object file so that I can extract both identifier and size using a simple tool like grep. It is expected that the variable is thrown out of the resulting executable or a shared library because it's not used anywhere. I am using boost in my project, so if that would simplify the implementation, I am all for it.
I think it should be possible to simply get the size of the type with a regular sizeof and then convert the number to a string as explained in this post via variadic templates. Then you can export a string variable from your object file and grep for it on the outside. It should work something like this: SizeInfo.h: namespace detail { template<unsigned... digits> struct to_chars { static const char value[]; }; template<unsigned... digits> constexpr char to_chars<digits...>::value[] = {('0' + digits)..., 0}; template<unsigned rem, unsigned... digits> struct explode : explode<rem / 10, rem % 10, digits...> {}; template<unsigned... digits> struct explode<0, digits...> : to_chars<digits...> {}; } template<unsigned num> struct num_to_string : detail::explode<num> {}; I downloaded the header file static_string.hpp from this excellent tutorial on static strings. Some file.cpp: class MyClass { // lots of members }; #include "static_string.hpp" namespace sstr = ak_toolkit::static_str; #include "Sizeinfo.h" constexpr auto MyClassSize = "MyIdentifier: " + sstr::literal(num_to_string<sizeof(MyClass)>::value); After compiling with gcc -c Somefile.cpp I can validate the following string inside the object file: MyIdentifier: 8.
70,226,926
70,227,796
Serializing and Deserializing in a client-server architecture
I'm using cereal to serialize and deserialize data in c++, and I came upon a problem. I'm sending data using a socket to the client side, so i send a stringstream with the serialized files in a JSON format. The problem is that I can't deserialize it with simple data types, nor with complex ones, on the client side as it fails a rapidjson check and it tells me it's not an object What would be the proper way of deserializing data considering that i can't create an instance of a class from the server side ? Here is a simple example in which i try to send the username of a user to the client side The send function : void DBUser::SendUser() { std::stringstream os; { cereal::JSONOutputArchive archive_out(os); archive_out(CEREAL_NVP(m_user)); } ServerSocket* instance= ServerSocket::GetInstance(); instance->SendData(os.str()); } In case it is needed, here is the function used to send the stringstream to the client side void ServerSocket::SendData(std::string message) { try { asio::error_code ignored_error; asio::write(*socket, asio::buffer(message), ignored_error); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } And here is the code when i try to deserialize: std::array<char, 5000> buf; asio::error_code error; size_t len = socket.read_some(asio::buffer(buf), error); std::string testString; std::stringstream is(buf.data()); { cereal::JSONInputArchive archive_in(is); archive_in(testString); } std::cout << "Message from server: "; std::cout << testString; std::cout << std::endl;
You need to null terminate the received socket data. Can you try null terminating it like buf[len] = '\0'; after this size_t len = socket.read_some(asio::buffer(buf), error); statement.
70,227,123
70,227,542
Error Can not convert char** to const char**
I have following code:- static char* ListOfStr[] = { "str1", "str2", "str3" }; void Foo(const char** listOfStr) { // do something } When I call Foo like; Foo(ListOfStr); I get Error Can not convert char** to const char** (C2664 - vc++) I know how to solve the problem using casting or other way around like defining const array at first place. But isn't it safe to use char** as const char** than why it gives error ? I supposed there should be auto convertion like std::string to const std::string when passing to function. Only the reverse of this cont char** to char** must give the Error without cast.
The issue is covered in the C++ FAQ, thanks to Steve Summit: https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion I have looked at it for 10 minutes and still don't fully understand it, but the problem is apparently that you could create non-const aliases and thus modify an originally const object if this were allowed.
70,227,162
70,227,239
Is there any equivalent to index.js in C++?
In JavaScript, I can do import "/my-folder" and it will import /my-folder/index.js". Is there some equivalent filename in C++? (so that #include "my-folder" will include my-folder/filename.fileext)?
No, there is not equivalent to index.js in standard C++. It would however be perfectly legal for a specific compiler to implement something like that, though I'm not aware of any compiler that does. Quoting from 19.2 [cpp.include] (N4659): (1) A #include directive shall identify a header or source file that can be processed by the implementation. (3) A preprocessing directive of the form # include " q-char-sequence " new-line causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. Emphasis mine. I'm not sure what role index.js typically plays in JavaScript libraries, but if you're trying to implement a portable catch-all header for your library (so that the end users only need to include a single header instead of many), you'll just have to write your own header to serve that purpose. Headers named along the lines of my_folder/my_folder.h or my_folder/prelude.h would be common candidates.
70,227,294
70,228,090
c++98 use iterator constructor only if InputIt is an iterator of type T
For a school project I have to implement std::vector but only using C++98 standard. The problem is that the size constructor and iterator constructor are conflicting with each other when I call it with a signed integer, so I came up with this ( whith my own implementations of enable_if, is_same, and iterator_traits): // Size constructor explicit vector( size_type count, const T &value = T(), const Allocator &alloc = Allocator() ) : _allocator(alloc), _capacity(count), _size(count), _array(_allocator.allocate(_capacity)) { std::fill(begin(), end(), value); } // Iterator constructor template < class InputIt > vector( InputIt first, InputIt last, const Allocator &alloc = Allocator(), typename ft::enable_if< ft::is_same< typename ft::iterator_traits< InputIt >::value_type, T >::value, int >::type = 0 ) : _allocator(alloc), _capacity(std::distance(first, last)), _size(_capacity), _array(_allocator.allocate(_capacity)) { std::copy(first, last, begin()); } But now I have a problem with my implementation of iterator_traits: when I call it with an int of course it doesn't work because int doesn't have iterator member types, but when I look at cppreference about iterator_traits, it says that If Iter does not have all five member types difference_type, value_type, pointer, reference, and iterator_category, then this template has no members by any of those names (std::iterator_traits is SFINAE-friendly) (since C++17) (until C++20) which means that the check isn't implemented before C++17, so how does the real std::vector check for Iterator validity even before C++11? Here is the compiler error I get when calling the constructor with 2 ints: /home/crochu/Documents/42/ft_containers/iterator_traits.hpp:22:20: error: type 'int' cannot be used prior to '::' because it has no members typedef typename Iter::difference_type difference_type; ^ /home/crochu/Documents/42/ft_containers/vector.hpp:78:55: note: in instantiation of template class 'ft::iterator_traits<int>' requested here typename ft::enable_if< ft::is_same< typename ft::iterator_traits< InputIt >::value_type, T >::value, int >::type = 0 ^ /home/crochu/Documents/42/ft_containers/main.cpp:19:20: note: while substituting deduced template arguments into function template 'vector' [with InputIt = int] ft::vector< int > v(5, 42); ^ In file included from /home/crochu/Documents/42/ft_containers/main.cpp:13: In file included from /home/crochu/Documents/42/ft_containers/ft_containers.hpp:15: /home/crochu/Documents/42/ft_containers/iterator_traits.hpp:23:20: error: type 'int' cannot be used prior to '::' because it has no members typedef typename Iter::value_type value_type; ^ /home/crochu/Documents/42/ft_containers/iterator_traits.hpp:24:20: error: type 'int' cannot be used prior to '::' because it has no members typedef typename Iter::pointer pointer; ^ /home/crochu/Documents/42/ft_containers/iterator_traits.hpp:25:20: error: type 'int' cannot be used prior to '::' because it has no members typedef typename Iter::reference reference; ^ /home/crochu/Documents/42/ft_containers/iterator_traits.hpp:26:20: error: type 'int' cannot be used prior to '::' because it has no members typedef typename Iter::iterator_category iterator_category; ^ 5 errors generated.
As an example, the implementation of this constructor in libstdc++ is located in the header bits/stl_vector.h: template<typename _InputIterator> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } This is a tag dispatch using a proto-std::integral_constant class, to one of these functions: // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template<typename _Integer> void _M_initialize_dispatch(_Integer __n, _Integer __value, __true_type) { this->_M_impl._M_start = _M_allocate(_S_check_init_len( static_cast<size_type>(__n), _M_get_Tp_allocator())); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + static_cast<size_type>(__n); _M_fill_initialize(static_cast<size_type>(__n), __value); } // Called by the range constructor to implement [23.1.1]/9 template<typename _InputIterator> void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_range_initialize(__first, __last, std::__iterator_category(__first)); } I'd say that's about as elegant as you could get under your constraints!
70,227,334
70,227,681
What is best to insert several values at the end of a std::vector?
To add elements to a std::vector<int> v is it better to do: // Read and manipulate a, b, c triplet as ints. // Potentially also: v.reserve(v.size() + 3); or trust vector growth policy? v.push_back(a); v.push_back(b); v.push_back(c); or v.insert(v.end(), {a, b, c}); from a performance point of view (assuming we are always going to insert triplets that are different everytime and a large unfixed number of them, say 1 million triplets)? Thanks for tips.
First of all, doing v.reserve(v.size() + 3); in a loop is generally a very bad idea since it will certainly cause a new reallocations for each iteration. For example, both Clang and GCC with the libstdc++ and libc++ actually do a linear number of reallocations (see here, here or even there). Here is a quote from cppreference: Correctly using reserve() can prevent unnecessary reallocations, but inappropriate uses of reserve() (for instance, calling it before every push_back() call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially) and result in increased computational complexity and decreased performance. For example, a function that receives an arbitrary vector by reference and appends elements to it should usually not call reserve() on the vector, since it does not know of the vector's usage characteristics. When inserting a range, the range version of insert() is generally preferable as it preserves the correct capacity growth behavior, unlike reserve() followed by a series of push_back()s. reserve() cannot be used to reduce the capacity of the container; to that end shrink_to_fit() is provided. When it comes to insert VS push_backs, insert should be slightly better than many push_back because the capacity check can be done only once as opposed to multiple push_backs. That being said, the performance difference is very dependent of the standard library implementation.
70,227,583
70,238,205
bcc32c Error integer literal is too large to be represented in any integer type
I have a large __int64 literal: const __int64 PwTab[] = { 50036500600837093008i64, 3006206760097890820056i64 }; It is accepted nicely by bcc32 (Borland classic compiler) but not by bcc32c (clang). The error for the clang compiler is: integer literal is too large to be represented in any integer type I use the i64 suffix to tell the computer it is a 64bit integer literal. How can I write an __int64 literal in clang, which is also compatible with the __int64 type in the classic compiler?
As mentioned in the comments the problem was in bcc32 not reporting too large literal during the compile time but silently overflowing which of course created completely different array than expected during runtime. e.g. int64_t testVar = 0x112233445566778899aai64; Which is of course larger than what 64-bit integer can accept and results in runtime value of: 0x33445566778899aa A sidenote - ll suffix doesn't work in Borland classic compiler. So I have to use i64 in it. But it won't be a problem after switching to clang.
70,227,643
70,227,694
How to overload call operator() function with same type and parameters, but different return type?
I want to define a new call operator() function with the parameters and type defined for the first operator() function. The reason for doing this is that the operations I want to perform with the new operator() function needs the same parameters as the first one, but maybe named differently but the type I need should remain the same. I know that it is not possible, but could someone suggest any different method to do this or are there any way around? code listing: namespace correlator { class mean_square_displacement { public: typedef std::shared_ptr<boost::multi_array<float, 2>> sample_type; typedef double result_type; // fixed_vector<double, 3> result_type operator() (sample_type const& first, sample_type const& second) const { double msd = 0; size_t N = first->size(); // number of rows in one frame (11214 in one frame) for (unsigned int i = 0; i < N; ++i) { for (unsigned int j = 0; j < 3; ++j) { double dr = (*first)[i][j] - (*second)[i][j]; msd += dr * dr; //ofile_msd << i << " " << msd << std::endl; if (msd > 0) std::cout << "msd::" << msd << std::endl; } } return msd/N; } // first operator ends here double operator()(sample_type const& first, sample_type const& second) const { std::cout << *(*first)[0][0] <<"The first element :." << std::endl; return 0; } }; } // namespace correlator
Adapters: struct Foo { // these are your current operator() functions int op1(int); float op2(int); }; struct FooAdapter1 { Foo& foo; auto operator()(int i) { return foo.op1(i); } }; struct FooAdapter2 { Foo& foo; auto operator()(int i) { return foo.op2(i); } }; So, instead of passing a Foo object like this: std::invoke(foo,7); // no You pass it via an adapter: std::invoke(FooAdapter1{foo},7); // calls op1 And you give the Adapters good semantically sensible names, of course. Alternatively, use an out argument to select the overload: struct Foo { // these are your current operator() functions void operator()(int, int&); void operator()(int, float&); }; And then the somewhat ugly call: float& result{}; std::invoke(foo,7,result); // selects the fist overload
70,227,792
70,227,892
subtle usage of reinterpret cast in Pool allocator implementation
I am currently implementing my own pool allocator to store n chunks of the same size in one big block of memory. I am linking all the chunks together using a *next pointer stored in the struct chunk like this struct Chunk{ Chunk* next; }; so I would expect to make a linked list like this given that i have a variable num_chunks which stores the number of chunks in the block Chunk* allocate_block(size_t chunk_size){ alloc_pointer = (Chunk*) malloc(chunk_size * num_chunks); Chunk* chunk = alloc_pointer; for (int i = 0; i < num_chunks; ++i){ /* I need to solve the problem of how to link all these chunks together. So I know that I have to work using the next pointer. This next pointer must point to an address chunk_size away from the current pointer and so on so forth. So basically: chunk -> next = alloc_pointer + chunk_size and chunk is going to be this chunk -> next on the successive call. */ chunk -> next = chunk + chunk_size; chunk = chunk -> next;} chunk -> next = nullptr; return chunk; } However looking at a blog post I have this implementation which makes sense but still do not understand why mine should be wrong /** * Allocates a new block from OS. * * Returns a Chunk pointer set to the beginning of the block. */ Chunk *PoolAllocator::allocateBlock(size_t chunkSize) { cout << "\nAllocating block (" << mChunksPerBlock << " chunks):\n\n"; size_t blockSize = mChunksPerBlock * chunkSize; // The first chunk of the new block. Chunk *blockBegin = reinterpret_cast<Chunk *>(malloc(blockSize)); // Once the block is allocated, we need to chain all // the chunks in this block: Chunk *chunk = blockBegin; for (int i = 0; i < mChunksPerBlock - 1; ++i) { chunk->next = reinterpret_cast<Chunk *>(reinterpret_cast<char *>(chunk) + chunkSize); chunk = chunk->next; } chunk->next = nullptr; return blockBegin; } I don’t really understand why I should convert the type of chunk to char and then add that to the size of the chunk. Thanks in advance
When you add to pointers, pointer arithmetic is used. With pointer arithmetic, the memory address result depends on the size of the pointer being added to. Let's break down this expression: reinterpret_cast<Chunk *>(reinterpret_cast<char *>(chunk) + chunkSize); The first part of this expression to be evaluated is reinterpret_cast<char *>(chunk) This will take the chunk pointer and tell the compiler to treat it as a char* rather than as Chunk*. This means that when pointer arithmetic is performed on the pointer, it will be in terms of 1 byte offsets (since a char has a size of 1 byte), instead of in offsets of sizeof(Chunk) bytes. Next, chunkSize is added to this pointer. Because we are doing pointer arithmetic on a char* pointer, we will take the memory address of chunk, and add chunkSize*sizeof(char) = chunkSize*1 to that memory address. That covers everything inside the outer set of brackets. The problem now is that the result of our pointer arithmetic is still understood by the compiler to be a char* pointer, but we really want it to be a Chunk*. To fix this, we cast back to Chunk*. This effectively undoes the temporary cast to char*. You can find more info on pointer arithmetic in the answers to this question.
70,228,001
70,228,714
QCandlestickSeries::hovered signal is not being emitted
The QObject::connect returns true and when I manually emit the signal, the breakpoint is hit in the slot, but when I hover over a QCandlestickSet, the signal is not emitted. I removed all other custom drawings from the chart to be sure nothing was overlaying the candlesticks, but the signal still does not fire. 'chartView' is of type 'ChartView' which is derived from 'QChartView'. 'series' is of type 'QCandlestickSeries'. Connection: QObject::connect(this->series, SIGNAL(hovered(bool, QCandlestickSet *)), this->chartView, SLOT(displayCandleValues(bool, QCandlestickSet *))); Slot: void ChartView::displayCandleValues(bool status, QCandlestickSet *candle) { qint32 x = 0; // A breakpoint is set on this line and is triggered when calling 'emit this->series->hovered(false, Q_NULLPTR);' } Thank you in advance. Edit: When I single click on the on a candle the signal is NOT emitted, but when I double click on a candle the signal IS emitted, and the breakpoint is triggered.
So I found the issue. I had overridden the mouseMoveEvent to draw my crosshair and I forgot to call the parent class' mouseMoveEvent. Old definition: void ChartView::mouseMoveEvent(QMouseEvent *event) { this->drawCrosshair(event->pos()); } New definition: void ChartView::mouseMoveEvent(QMouseEvent *event) { this->drawCrosshair(event->pos()); QChartView::mouseMoveEvent(event); }
70,228,029
70,228,233
C++ - Overloading of operators needed for an iterator
I'm trying to create an iterator on a library that allows reading a specific file format. From the docs, to read the file content you need do something like this: CKMCFile database; if (!database.OpenForListing(path)) { std::cerr << "ERROR: unable to open " << path << std::endl; } CKMCFileInfo info; database.Info(info); CKmerAPI kmer(info.kmer_length); uint32 cnt; std::vector<uint64_t> data; std::vector<uint64> ulong_kmer; data.reserve(info.total_kmers); while (database.ReadNextKmer(kmer, cnt)) { kmer.to_long(ulong_kmer); data.push_back(ulong_kmer[0]); } Now, I started with this class wrapper: class FileWrapper { CKMCFile database; CKMCFileInfo info; Iterator _end; public: explicit FileWrapper(const std::string &path) { if (!database.OpenForListing(path)) { std::cout << "ERROR: unable to open " << path << std::endl; } database.Info(info); } Iterator begin() { Iterator it; it.database = &database; it.total = 0; uint32_t cnt; std::vector<uint64_t> ulong_kmer; CKmerAPI tmp(info.kmer_length); database.ReadNextKmer(tmp, cnt); tmp.to_long(ulong_kmer); return it; } Iterator end() const { return _end; } uint64_t size() { return info.total_kmers; } }; And then, this is the Iterator class: class Iterator { friend class FileWrapper; CKMCFileInfo info; CKMCFile *database; uint64_t kmer, total; public: Iterator &operator++() { ++total; uint32_t cnt; std::vector<uint64_t> ulong_kmer; CKmerAPI tmp(info.kmer_length); database->ReadNextKmer(tmp, cnt); tmp.to_long(ulong_kmer); return *this; } bool operator<(const Iterator &rhs) const { return total < rhs.total; } uint64_t operator*() const { return kmer; } }; But, during some test I can't use into a for loop for something like for (auto it = begin(); it != end(); ++i) { ... } or begin() + size(). How can I overload correctly this two operatos? opeartor!= and operato+
You'll have to think about 2 major things before: Ownership. Currently, you have to make sure your FileWrapper survives at least as long as any Iterator returned from it by calling its begin() (since your Iterators store pointers to data owned by the FileWrapper object). If you cannot guarantee that, maybe think about using unique_ptrs or shared_ptrs Iterator Category. As discussed in the comments, it appears that your database requires you to use "input iterators". They can only be incremented by one (do not provide operator+(int)) and dereferenced. Indeed, what would the iterator begin() + 10 look like? If this should advance your file-pointer, then you cannot define the end as begin() + size() as that would just skip through the file. Representation. What should an end-iterator look like? A simple choice might be to indicate the end with database == nullptr. In this case, an operator!= might look like this: bool is_end() const { return database == nullptr; } bool operator==(const Iterator& other) const { if(is_end()) return other.is_end(); if(other.is_end()) return false; return (database == other.database) && (total == other.total); } bool operator!=(const Iterator& other) const { return !operator==(other); } Now, you'll need code that ensures that all end-iterators have database == nullptr and, whenever a non-end iterator becomes and end-iterator by application of operator++(), you'll need to set database = nullptr and total = 0 (or something). A note at the end: your Iterators may be in an inconsistent state after construction and before assignment of their database member. It is prudent to declare a proper constructor for Iterator that initializes its members. EDIT: here's a suggestion for an integration
70,228,102
70,265,851
Different compilation + linking errors for static and constexpr between clang and gcc
I have the following code: // template_header.hpp #ifndef TEMPLATE_HEADER_HPP #define TEMPLATE_HEADER_HPP namespace template_header { template <int dim1> /*static*/ constexpr int dim2 = 0; template <> /*static*/ constexpr int dim2<2> = 3; template <> /*static*/ constexpr int dim2<3> = 5; } #endif // lib1.cpp #include <array> #include "template_header.hpp" template <int dim1> class lib1_class { public: std::array< double, template_header::dim2<dim1> > ar1 = {0}; }; // lib2.cpp #include <array> #include "template_header.hpp" template <int dim1> class lib1_class { public: std::array< double, template_header::dim2<dim1> > ar1 = {0}; }; If I compile any of the .cpp files with static uncommented, GCC gives me an "explicit template specialization cannot have a a storage class" error. If static is commented, I can compile both .cpp files and then link them together as a shared library with g++ lib1.o lib2.o -shared -o shared_lib.so. However, if I compile with static commented out with clang, I get no problems during compilation, but I get a "multiple definition of template_header::dim2<2>'" error during linking. If I uncomment static`, then everything compiles and links fine. I'm pretty confused about this, firstly given that this answer indicates that, since my constexpr's happen in a namespace scope, they ought to automatically be static and therefore should pose no problem for the linker even if static is commented out. Additionally, I don't understand why adding static beforehand would change how GCC compiles the .cpp files, given that it should be implicitly static. Any explanation of the errors + possible fixes are appreciated. Edit: I am using C++14.
So, without inline variables, I was able to get something achieving your goals working. The basic idea is to have a "backend" struct to hold static members and then fully specialize that struct to your options. This method has the added benefit of causing a compiler error if you attempt to access a member of the backend using a template parameter that has not been defined yet. The header file would look like #ifndef TEMPLATED_HEADER_HPP #define TEMPLATED_HEADER_HPP namespace template_header { /** * the "primary" template of the backend struct * notice I leave the variable we want undefined! * if you prefer to have a default for all other values of dim1 * you would put that here */ template<int dim1> struct backend {}; template<> struct backend<2> { static constexpr int dim2 = 3; }; template<> struct backend<3> { static constexpr int dim2 = 5; }; /** * Helper constexpr * this is optional, but makes code outside this file more readable * also, I named it in a way for your source files to be unchanged. */ template <int dim1> constexpr dim2 = backend<dim1>::dim2; } #endif I have a working version of this idea on Compiler Explorer which verifies that both this works with both GCC and clang. If you were to try to call dim2<dim1> where dim1 does not equal 2 or 3, then a compiler error complaining about backend<dim1>::dims not defined will be generated. You could add other members to the backend specializations, taking care to keep the names the same across the different values of dim1. Total side note, why are you setting ar1 = {0};? From my reading of the std array reference, this would only set the first element in the array to 0.
70,228,120
70,229,257
Error with initializer_list<initializer_list<T>>
I want to initialize my own class similar to this: vector< Point3f >={{1f,2f,3f},{2f,3f,1f},{2f,2f,2f}}; but there is an error shown: can't convert “initializer list” to “std::vector<LB::Point3f,std::allocator<LB::Point3f>>... I want to know what the right way is to initialize my own class with lists in braces. This is my code: #pragma once #ifndef POINT_HPP #define POINT_HPP #include<initializer_list> namespace LB { using namespace std; template< typename T,unsigned length> class Point { T data[length]; public: Point(){} Point(const initializer_list<T>& t) { int min = t.size() < length ? t.size() : length; int i = 0; for (auto& each : t) { if (i >= min) break; data[i] = each; i++; } } Point(Point<T, length>& other) { for (int i = 0; i < length; i++) { data[i] = other[i]; } } /* other operation function */ }; using Point2i = Point<int, 2>; using Point2f = Point<float, 2>; using Point2d = Point<double, 2>; using Point3i = Point<int, 3>; using Point3f = Point<float, 3>; using Point3d = Point<double, 3>; using Point4i = Point<int, 4>; using Point4f = Point<float, 4>; using Point4d = Point<double, 4>; } #endif
Basically it's failing because your current implementation of `Point<T,unsigned> doesn't have a working copy constructor. The copy constructor needs to take a const Point<T, length>& since the initializer list is const, and it will need a const version of operator[], given your current implementation of copy, because the argument of the copy constructor is a reference to your custom point class, not an array. Code below: #include <iostream> #include<initializer_list> #include <vector> namespace LB { template< typename T, unsigned length> class Point { T data[length]; public: Point() {} Point(const std::initializer_list<T>& t) { int min = t.size() < length ? t.size() : length; int i = 0; for (auto& each : t) { if (i >= min) break; data[i] = each; i++; } } Point(const Point<T, length>& other) { for (size_t i = 0; i < length; i++) { data[i] = other[i]; } } T& operator[](size_t i) { return data[i]; } const T& operator[](size_t i) const { return const_cast<const T&>( const_cast<Point&>(*this)[i] ); } }; using Point3f = Point<float, 3>; } int main() { std::vector<LB::Point3f> vec = { {1.0f,2.0f,3.0f},{2.0f,3.0f,1.0f},{2.0f,2.0f,2.0f} }; std::cout << vec[1][0] << " , " << vec[1][1] << " , " << vec[1][2] << "\n"; }
70,228,130
70,232,327
cannot find -lbgi | codeblocks
I'm trying to write some program with the legendary graphics.h I got a toy code. And downloaded all necessary files: winbgim.h graphics.h libbgi.a And then fixed all header bugs. And tried to compile with proper linking. And the build log looks something like this: g++.exe -c C:\tem\1.cpp -o C:\tem\1.o g++.exe -o C:\tem\1.exe C:\tem\1.o -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32 C:\tem\libbgi.a And the error says: C:/Program-Files-Soft/codeblocks-20.03mingw-nosetup/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lbgi
gcc (QP MinGW32) 4.4.5, 32 bit I had tried different compiler, but nothing worked: gcc (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0 gcc (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0 there were 4 more But the thing that resolved this is: gcc (QP MinGW32) 4.4.5, and this build was for 32-bit although my system is 64-bit. And for some reason, this works. Without any crash or worse blue screen. As @πάνταῥεῖ mentioned this is really old, and the source code and build are from 2010. And here is a completely portable version of Codeblocks IDE: https://github.com/maifeeulasad/codeblocks-ep. Everything should work. Else feel free to open an issue or pull.
70,228,218
70,229,029
create a to_vector function that can conditionally const cast to elements of input range based on output type
I would like to create a to_vector function that works with input vieweable_ranges. I can easily get this to work if input view and output vector have exactly the same type, but cannot get it to work if the output requires a const cast on the elements of the input range. In my case, the input ranges have non-const pointers, but the output may specify const pointers. I want to use it something like this: auto a = to_vector( view ); // returns a vector<obj *>. This case is easy vector<const obj *> b = to_vector( view ); // returns a vector of const pointers. This gives error shown at the end The standard library has no problem casting pointers when making the vector vector<const obj *> c( view.begin(), view.end() ); But I can't create a templated function to make it work. I've tried many variations, but I think my closest idea is something like this: #include <ranges> #include <vector> using namespace std::ranges; template <range Range, typename T = range_value_t<Range>> // default element type, T, based on input range inline std::vector<T> to_vector(Range&& r) { // idea: user specifies T. (doesn't work) std::vector<T> v; if constexpr (std::ranges::sized_range<T>) { v.reserve(std::ranges::size(r)); } std::copy(std::ranges::begin(r), std::ranges::end(r), std::back_inserter(v)); return v; } The to_vector compiles, but I get an error when I try to require a vector output with an error something like this: cannot convert std::vector<Obj *,std::allocator<Obj *>>' to 'std::vector<const Obj *,std::allocator<const Obj *>>
This is because your function creates a return value of type std::vector<Obj*>, which is indeed a different type to std::vector<const Obj*>; and so unless std::vector provided an overloaded constructor which accepted a non-const version of itself then this conversion is impossible. The return value is not deduced by the value you assign the result of the function to but by the T template parameter, so this will work if you explicitly call the function with T=const Obj* You would need to explicitly overload the function to construct a vector of const objects, either by passing a dummy tag parameter, an extra template parameter or a to_const_vector function.
70,228,223
70,228,417
std move bug? heap error with std vector assignment of a vector reference if nesting the assignment copy within a loop that iterates more than once
I got a heap runtime error. I suspect that it is a compiler bug when it use move too excessively. A simplified version of the code is vector<vector<int>>result{{1,2,3}}; int size = result.size(); for(auto jdx = size-1; jdx >= 0; --jdx){ vector<int> &row = result[jdx]; // vector<int> newrow(row); for(int idx = 2; idx >=1; --idx) { vector<int> newrow(row); result.push_back(newrow); } } if I swap the newrow(row) line out of the inner most loop, it is then fine like below, vector<vector>result{{1,2,3}}; int size = result.size(); for(auto jdx = size-1; jdx >= 0; --jdx){ vector<int> &row = result[jdx]; vector<int> newrow(row); for(int idx = 2; idx >=1; --idx) { //vector<int> newrow(row); result.push_back(newrow); } } the dump out error is like below ================================================================= ==31==ERROR: AddressSanitizer: heap-use-after-free on address 0x6040000000b0 at pc 0x00000034789d bp 0x7ffd3434d6b0 sp 0x7ffd3434d6a8 READ of size 8 at 0x6040000000b0 thread T0 #4 0x7f9a26d790b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) 0x6040000000b0 is located 32 bytes inside of 48-byte region [0x604000000090,0x6040000000c0) freed by thread T0 here: #5 0x7f9a26d790b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) previously allocated by thread T0 here: #6 0x7f9a26d790b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) Shadow bytes around the buggy address: 0x0c087fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c087fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c087fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c087fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c087fff8000: fa fa fd fd fd fd fd fd fa fa 00 00 00 00 00 06 =>0x0c087fff8010: fa fa fd fd fd fd[fd]fd fa fa fa fa fa fa fa fa 0x0c087fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c087fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c087fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c087fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c087fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb Shadow gap: cc ==31==ABORTING
Here, the comment I made initially about your code: you keep a reference on an element of the vector, then you extend this vector, which can lead to reallocation. This reference becomes invalid Another comment gives the link that explains this behaviour. Below is a minimal example to illustrate explicitly the same situation. We can see that after extending the vector, the whole storage is elsewhere on the heap (elements have been moved) but the reference still refers to the previous address of the element at index 2. /** g++ -std=c++17 -o prog_cpp prog_cpp.cpp \ -pedantic -Wall -Wextra -Wconversion -Wno-sign-conversion \ -g -O0 -UNDEBUG -fsanitize=address,undefined $ ./prog_cpp v from 0x602000000010 to 0x602000000020 elem at 0x602000000018 is 30 v from 0x603000000010 to 0x603000000024 elem at 0x602000000018================================================================= ==186890==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000018 at pc 0x55f3af7583e1 bp 0x7ffd22315d80 sp 0x7ffd22315d70 READ of size 4 at 0x602000000018 thread T0 ... **/ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include <iostream> #include <vector> int main() { auto v=std::vector<int>{10, 20, 30, 40}; std::cout << "v from " << data(v) << " to " << data(v)+size(v) << '\n'; const auto &elem=v[2]; std::cout << "elem at " << &elem << std::flush << " is " << elem << '\n'; v.emplace_back(50); std::cout << "v from " << data(v) << " to " << data(v)+size(v) << '\n'; std::cout << "elem at " << &elem << std::flush << " is " << elem << '\n'; return 0; }
70,228,299
70,228,405
C++ if constexpr vs template specialization
Consider these 2 examples Example 1 template<Type type> static BaseSomething* createSomething(); template<> BaseSomething* createSomething<Type::Something1>() { return Something1Creator.create(); } template<> BaseSomething* createSomething<Type::Something2>() { return Something2Creator.create(); } .... // other somethings Example2 template<Type type> static BaseSomething* createSomething() { if constexpr(type == Type::Something1) { return Something1Creator.create(); } else if constexpr(type == Type::Something2) { return Something2Creator.create(); } // Other somethings } I know that these two examples are conceptually the same, but consider these functional is in a SomethingFactory.hpp file, and my main.cpp includes it. In main.cpp I may create only type Something1 without ever knowing that other Something types exist. I really do care about size of my executable in the end. What do you think which pattern shall I take for my executable to be at minimal size? Or there is no big deal about these, and we are all doomed anyway?
What do you think which pattern shall I take for my executable to be at minimal size? In both cases, if you only instantiate createSomething<Type::Something1> you will get one function definition that is effectively one line of code. I really do care about size of my executable in the end Then get rid of the static. Template functions are implicitly inline, but static functions will have unique copies for each translation unit. I know that these two examples are conceptually the same They are not. createSomething<void> is a defined function using Example2, and is undefined using Example 1.
70,228,321
70,228,377
Can std::function have a function pointer as the type?
Suppose that I have the C-style callback type like below. For C++, I could create a std::function type like callback2, and this kind of declaration is all examples I could find. But instead of typing the signature again, can I reuse callback like callback3 below? If callback3 is possible, how can I call the callback? Is c.target<callback>(); like below is the correct way to call the callback? how can I pass a member function? For the common type, I could use worker2([this]() {toBeCalled();}); but worker3([this]() {toBeCalled();}); did not work. Code typedef void (*callback)(); typedef std::function<void()> callback2; typedef std::function<callback> callback3; void worker(callback c) { c(); } void worker2(callback2 c) { c(); } void worker3(callback3 c) { //Is this the way to call the callback? c.target<callback>(); } class Caller { public: Caller() { //worker2([this]() {toBeCalled();}); worker3(????); } void toBeCalled() { std::cout << "toBeCalled()"; } };
Can std::function have a function pointer as the type? No. The class template std::function is defined only for a function type template argument. The template is undefined for all other argument types, including function pointers. I also recommend against aliasing pointer types in general (there are exceptions to this rule of thumb though). If you avoid it, then you can re-use the alias just fine: typedef void callback(); typedef std::function<callback> callback2; // or preferably using the modern syntax using callback = void(); using callback2 = std::function<callback>; void worker (callback* c); void worker2(callback2 c);
70,229,195
70,229,384
Generic KDTree in C++
I would like to have a generic KDTree implementation in C++ that can hold any kind of positionable object. Such objects have a 2D position. Unfortunately. Positionable classes could have different ways of getting the position. Getters getX() and getY() std::pair<double, double> sf::Vector2f ... What would be the proper way to wrap such classes into my KDTree? My Tree is composed of nodes such as: template <typename T> struct Node { int id; T element; Node *left, *right; Node(T element) : element(element), left(NULL), right(NULL) { static int id = 0; this->id = id++; } }; Somehow I would like to have a generic getter to the position of T element. One possible solution is to define a positionable interface: struct KDTreeElement { virtual getX() = 0; virtual getY() = 0; } The con of this method is that the positionable element must know the KDTree library What are the alternatives?
Check the design rationale of boost geometry for a solution to this problem. The methodology boils down to these steps: Declare a class template that extracts position information from a type, e.g. template <class Geometry> struct Position; To make your kd Tree usable with a new type, say MyAwesome2dPoint, specialize this template for it. In the specialization you can use the type's method of getting the position: template <> struct Position<MyAwesome2dPoint> { static float getX(MyAwesome2dPoint const& p) { return p.x; } static float getY(MyAwesome2dPoint const& p) { return p.y; } } Use this type system in your kd tree, i.e. instead of directly accessing positions, go through the Position class: class KdTree { template <class PointType> auto contains(PointType const& g) { // Geometric properties are accessed through the traits system. return contains_impl( Position<PointType>::getX(g), Position<PointType>::getY(g)); } } For extra credit, create a concept to avoid the weird compilation errors when using a type that hasn't been configured to work with your library: template <class G> concept Positionable = requires (G g) { Position<G>::getX() + Position<G>::getY(); }; // So now you can explicitly operate on such types template <Positionable G> auto contains(G const& g) { } No inheritance, no virtuals, no modifications to existing types. Just create a layer that can be specialized for everyone (even C types) and you're good to go. Concepts will save your life when abstracting even further, e.g. boost geometry generalizes to N dimensions, different coordinate systems and more.
70,229,226
70,229,283
How to resolve "error: ‘The’ does not name a type" when reading from txt file?
Currently trying to read from a text file using C++ I created and for it to loop to display the words. I tried used fstream and istream but for some reason I still receive this error saying HarlemRenaissance.txt:1:1: error: ‘The’ does not name a type 1 | The Harlem Renaissance was an intellectual Do anyone know what the problem may be? Heres a snippit of my code: #include <iostream> #include <fstream> #include <stdio.h> #include "HarlemRenaissance.txt" using namespace std; int main() { //reads file // Create a text string, which is used to output the text file string myText; // Read from the text file std::ifstream MyReadFile("HarlemRenaissance.txt"); // Use a while loop together with the getline() function to read the file line by line while (std::getline (MyReadFile,myText)) { // Output the text from the file std::cout << myText << std::endl; } //output data outputStats(); //closes file MyReadFile.close(); }
Remove the #include "HarlemRenaissance.txt" from your code. Practically include means a copy-paste. The content of the included file will be pasted in the sorce file. In this case, the content of your file is pasted into your source code. Perhaps it has some words that syntacticly incorrect. This is why you get this error message.
70,229,319
70,229,432
Must I use lambda to pass a member function as std::function?
The following code works, but I feel that the line worker([this](int a, long b, int* c){receiver(a, b, c);}); is sort of redundant because it is repeating the signature of receiver. Instead of passing a lambda function that in turn calls the member function, can I somehow pass the member function directly? using callback = std::function<void(int, long, int*)>; void worker(callback c) { c(1,2L,(int*)3); } class Caller { public: Caller() { worker([this](int a, long b, int* c){receiver(a, b, c);}); } void receiver(int a, long b, int* c) { } };
std::bind is the classical approach, that avoids the need to explicitly spell out the forwarding signature: using namespace std::placeholders; // ... worker(std::bind(&Caller::receiver, this, _1, _2, _3)); C++20 also has std::bind_front; it reduces this verbiage, somewhat. You cannot pass a pointer to a member function "directly". This is because a member function requires a specific instance of an object whose member function should get invoked. So, in some form of fashion, in some way, you cannot avoid this, or some other instance of the object, to be involved in the process. This is fundamental to C++. The only thing that can be done here is to find some syntactic sugar, which is basically all this is, here.
70,229,506
70,230,018
Rabin-Karp algorithm in c++
I am trying to understand the implementation of the Rabin-Karp algorithm. d is the number of characters in the input alphabet, but if I replace 0 or any other value instead of 20, it won't affect anything. Why is this happening like this ? // Rabin-Karp algorithm in C++ #include <string.h> #include <iostream> using namespace std; #define d 20 void rabinKarp(char pattern[], char text[], int q) { int m = strlen(pattern); int n = strlen(text); int i, j; int p = 0; int t = 0; int h = 1; for (i = 0; i < m - 1; i++) h = (h * d) % q; // Calculate hash value for pattern and text for (i = 0; i < m; i++) { p = (d * p + pattern[i]) % q; t = (d * t + text[i]) % q; } // Find the match for (i = 0; i <= n - m; i++) { if (p == t) { for (j = 0; j < m; j++) { if (text[i + j] != pattern[j]) break; } if (j == m) cout << "Pattern is found at position: " << i + 1 << endl; } if (i < n - m) { t = (d * (t - text[i] * h) + text[i + m]) % q; if (t < 0) t = (t + q); } } } int main() { // char text[] = "ABCCDXAEFGX"; char text[] = "QWERTYUIOPASDFGHJKLXQWERTYUIOPASDFGHJKLX"; char pattern[] = "KLXQW"; int q = 13; rabinKarp(pattern, text, q); }
I believe the short answer is that the lower d is the more hash collisions you will have, but you go about verifying the match anyway so it does not affect anything. A bit more verbose: First let me modify your code to be have more expressive variables: // Rabin-Karp algorithm in C++ #include <string.h> #include <iostream> using namespace std; #define HASH_BASE 0 void rabinKarp(char pattern[], char text[], int inputBase) { int patternLen = strlen(pattern); int textLen = strlen(text); int i, j; //predefined iterators int patternHash = 0; int textHash = 0; int patternLenOut = 1; for (i = 0; i < patternLen - 1; i++) patternLenOut = (patternLenOut * HASH_BASE) % inputBase; // hash of pattern len // Calculate hash value for pattern and text for (i = 0; i < patternLen; i++) { patternHash = (HASH_BASE * patternHash + pattern[i]) % inputBase; textHash = (HASH_BASE * textHash + text[i]) % inputBase; } // Find the match for (i = 0; i <= textLen - patternLen; i++) { if (patternHash == textHash) { for (j = 0; j < patternLen; j++) { if (text[i + j] != pattern[j]) break; } if (j == patternLen) cout << "Pattern is found at position: " << i + 1 << endl; } if (i < textLen - patternLen) { textHash = (HASH_BASE * (textHash - text[i] * patternLenOut) + text[i + patternLen]) % inputBase; if (textHash < 0) textHash = (textHash + inputBase); } } } int main() { // char text[] = "ABCCDXAEFGX"; char text[] = "QWEEERTYUIOPASDFGHJKLXQWERTYUIOPASDFGHJKLX"; char pattern[] = "EE"; int q = 13; rabinKarp(pattern, text, q); } The easiest way to attack it is to set HASH_BASE (previously d) to zero and see where we can simplify. The rabinKarp function can then be reduced to: void rabinKarp(char pattern[], char text[], int inputBase) { int patternLen = strlen(pattern); int textLen = strlen(text); int i, j; //predefined iterators int patternHash = 0; int textHash = 0; int patternLenOut = 0; // Calculate hash value for pattern and text for (i = 0; i < patternLen; i++) { patternHash = (pattern[i]) % inputBase; textHash = (text[i]) % inputBase; } // Find the match for (i = 0; i <= textLen - patternLen; i++) { if (patternHash == textHash) { for (j = 0; j < patternLen; j++) { if (text[i + j] != pattern[j]) break; } if (j == patternLen) cout << "Pattern is found at position: " << i + 1 << endl; } if (i < textLen - patternLen) { textHash = (text[i + patternLen]) % inputBase; if (textHash < 0) textHash = (textHash + inputBase); } } } now you'll notice that all the hashes becomes is the sum of the letters mod some number (in your case 13, in my case 2). This is a bad hash, meaning many things will sum to the same number. However, in this portion of the code: if (patternHash == textHash) { for (j = 0; j < patternLen; j++) { if (text[i + j] != pattern[j]) break; } if (j == patternLen) cout << "Pattern is found at position: " << i + 1 << endl; } you explicitly check the match, letter by letter, if the hashes match. The worse your hash function is, the more often you will have false positives (which will mean a longer runtime for your function). There are more details, but I believe that directly answers your question. What might be interesting is to record false positives and see how the false positive rate increases as d and q decrease.
70,229,531
70,229,710
C++ Add string to const char* array
Hey so this is probably a dumb beginner question. I want to write the filename of all .txt files from a folder inside a const char* array[]. So I tried to do it like this: const char* locations[] = {"1"}; bool x = true; int i = 0; LPCSTR file = "C:/Folder/*.txt"; WIN32_FIND_DATA FindFileData; HANDLE hFind; hFind = FindFirstFile(file, &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { do { locations.append(FindFileData.cFileName); //Gives an error i++; } while (FindNextFile(hFind, &FindFileData)); FindClose(hFind); } cout << "number of files " << i << endl; Basically the code should add the Filename of the .txt file to the const char* locations array but it doesn't work using append as it gives me the error: "C++ expression must have class type but it has type ''const char *''" So how do I do it right?
Problem: You can't append items to a C array -T n[]- because the length of the array is determined at compile time. An array is a pointer(which is a scalar type), which isn't an object and doesn't have methods. Solution: The easiest solution is to use an std::vector which is a dynamic array: #include <vector> // ... std::vector<T> name; // or if you have initial values... std::vector<T> name = { // bla bla bla.. }; In your case an array called location of strings is std::vector<std::string> locations. For some reason, C++ containers don't like the classical append(), and provide the following methods: container.push_back(); // append. container.push_front(); // prepend. container.pop_back(); // remove last container.pop_front(); // remove first Note that std::vector only provides push_back and pop_back See: std::vector
70,229,619
70,230,027
I need help to writing a program that prints out shape that takes number of rows from user
The shape should look like this: shape For example, this figure has 10 lines. And the shape should continue with this pattern. Here is my code so far: #include <iostream> using namespace std; int main() { int rows, a, b, c, d; cout << "Enter the number of the rows: "; cin >> rows; for (a = 1; a <= rows; a++) { for (b = 1; b <= a; b = a + 4) { cout << " ******" << endl; } for (c = 2; c <= rows; c += 2) { cout << " **********" << endl; } for (d = 3; d <= rows; d += 4) { cout << "************" << endl; } } return 0; } I'm having trouble getting it back in order. For example, when I enter the value 5, each row repeats 5 times, but I want the number of rows to be 5.
Here is a solution: #include <iostream> #include <iomanip> int main( ) { std::cout << "Enter the number of the rows: "; std::size_t rowCount { }; std::cin >> rowCount; constexpr std::size_t initialAsteriskCount { 6 }; std::size_t asteriskCount { initialAsteriskCount }; bool isIncreasing { }; int fieldWidth { initialAsteriskCount + 3 }; for ( std::size_t row = 0; row < rowCount; ++row ) { std::cout << std::right << std::setw( fieldWidth ) << std::setfill(' ') << std::string( asteriskCount, '*' ) << '\n'; switch ( asteriskCount ) { break; case 6: isIncreasing = true; asteriskCount += 4; fieldWidth = 11; break; case 10: asteriskCount += ( isIncreasing ) ? 2 : -4; fieldWidth = ( isIncreasing ) ? 12 : 9; break; case 12: isIncreasing = false; asteriskCount -= 2; fieldWidth = 11; } } return 0; } This can probably be simplified a bit more. But it's working properly. Also, note that the syntax of the switch statement might seem a bit strange at first sight. But it's the new and safer way of writing a switch block and recommended by experts.
70,229,622
70,229,915
Process file by line in C++ where one line is string and second is array of floats
I have this file format: Jane Doe 10 3.1 8 7.4 5 10 6 8 0.1 2 And I want to read the file line by line, storing the first line in a string and the second line is an array of floats. string name; double scores[10]; ifstream scoreFile; scoreFile.open(SCORES_FILENAME); if (scoreFile) { while (getline (scoreFile,line)) { // ?? } scoreFile.close(); } How do I do this?
You can use a std::istringstream to parse the array, eg: string name, line; double scores[10]; ... getline(scoreFile, name); getline(scoreFile, line); std::istringstream iss(line); for(int i = 0; (i < 10) && (iss >> scores[i]); ++i);
70,229,973
70,230,890
Is there a C/C++ APIfor pkg-config?
I have a strange use case. I have a C++ program that compiles a library object and dynamically loads it at runtime. The library it compiles depends on a third party dependency, which so far I have been solving by manually hard coding the path and changing it when I switch computers. Is there a way to call pkg-config from C++ to ask it if a library is installed and where? I know I could call it from a bash session and parse the output, but this is not what I want, I would like to call it directly instead of invoking a shell if that is possible.
Is there a C/C++ APIfor pkg-config? Yes, there is a C api. https://github.com/pkgconf/pkgconf/blob/master/libpkgconf/libpkgconf.h , which should get installed with libpkgconf.so shared library.
70,230,015
70,230,070
Using std::bind with overloaded methods in namespace in C++
#include <iostream> #include <map> #include <functional> namespace xAOD{ namespace EgammaParameters{ enum ShowerShapeType{ var1 = 0, var2 = 1, var3 = 3 }; }; class Photon{ public: // I don't want to use this overload //double test(float& value, const EgammaParameters::ShowerShapeType information) const {return 1;} // I want to use this overload double test(const EgammaParameters::ShowerShapeType information) const {return 1;} private: }; }; struct funcLookup { funcLookup(xAOD::Photon * photon) { //this works without the first overload lookup_callback["test"] = std::bind(&xAOD::Photon::test, photon, xAOD::EgammaParameters::ShowerShapeType::var1); // static casting doesn't work: //lookup_callback["test"] = std::bind(static_cast<double(&)(const xAOD::EgammaParameters::ShowerShapeType)>(&xAOD::Photon::test), photon,xAOD::EgammaParameters::ShowerShapeType::var1); } double call(std::string name) { if (lookup_callback.count(name) > 0){ return lookup_callback[name](); } else{ std::cerr << "Invalid Function Call "<< std::endl; return -1; } } std::map<std::string, std::function<double(void)>> lookup_callback; }; int main() { xAOD::Photon * photon; funcLookup funcMap(photon); std::cout<<funcMap.call("test")<<std::endl; return 0; } I am trying to bind a method (test) which is overload in a namespace EgammaParameters in the class Photon. As far as I understand, I need to specifically tell C++ which overloaded method it should use, so I tried to use static casting like: std::bind(static_cast<double(&)(const xAOD::EgammaParameters::ShowerShapeType)>(&xAOD::Photon::test), photon,xAOD::EgammaParameters::ShowerShapeType::var1); However, this gives me the error error: invalid static_cast from type ‘’ to type ‘double (&)(xAOD::EgammaParameters::ShowerShapeType). What am I missing?
Using lambda is easier: lookup_callback["test"] = [=] { return photon->test(xAOD::EgammaParameters::ShowerShapeType::var1); }; If you really want to use bind: lookup_callback["test"] = std::bind( static_cast<double (xAOD::Photon::*) (xAOD::EgammaParameters::ShowerShapeType) const>( &xAOD::Photon::test), photon, xAOD::EgammaParameters::ShowerShapeType::var1); And I would suggest at least a helper alias: using TestType = double (xAOD::Photon::*) (xAOD::EgammaParameters::ShowerShapeType) const; lookup_callback["test"] = std::bind( static_cast<TestType>(&xAOD::Photon::test), photon, xAOD::EgammaParameters::ShowerShapeType::var1); And since C++20 I would suggest replacing std::bind with std::bind_front.
70,230,034
70,230,284
C++ writing byte to file
I am trying to write one byte to a file in C++. When I save it, is is 8 byte large, instead of 1 byte. How can I save exactly one byte? ofstream binFile("compressed.bin", ios::out | ios::binary); bitset<8> a("10010010"); binFile << a; Output of ls -la: .rw-r--r-- name staff 8 B Sat Dec 4 23:26:18 2021  compressed.bin How can I small it down to one byte?
operator << is designed for formatted output. When writing strict binary, you should focus on member functions put (for one byte) or write (for a variable number of bytes). This will write your bitset as a single byte. binFile.put( a.to_ulong() );
70,230,055
70,230,122
OpenGL slows for 5k points
I am writing a SLAM library and want to visualize its work with OpenGL. I need to draw some 100k points and a few hundred rectangles and I would expect that OpenGL can handle it easily. However, after the number of points reaches 5k my program slows down. I am new to OpenGL, so I guess I am not doing things in a proper way. I used this tutorial for learning. As the program works, it spits out certain events from which only a few are relevant: Point Created (size_t id, float x,y,z;) Point Updated (szie_t id, float x,y,z;) Position Estimated (Quaternion Q, Vector3D T) The part of the program that visualizes these events (simplified) works as follows. We assign a GL_ARRAY_BUFFER to each point. In order not to allocate a new buffer every time we get a new point, I decided to keep a repository of buffers. As a new point arrives we assign to it a "free" buffer from the repository. Only if the repo is empty, we allocate a new buffer with glGenBuffers. std::stack<GLuint> point_buffer_stack; std::map<size_t, GLuint> active_points; void OnPointCreated(size_t id, float x, float y, float z ){ GLuint point_buffer_id; if(point_buffer_stack.empty()){ glGenBuffers(1, &point_buffer_id); } else { point_buffer_id = point_buffer_stack.top(); point_buffer_stack.pop(); } active_points[id] = point_buffer_id; OnPointUpdated(id, x, y, z); } void OnPointUpdated(size_t id, float x, float y, float z){ GLuint point_buffer_id = active_points[id]; float buffer[3] = {x,y,z}; glBindBuffer(GL_ARRAY_BUFFER, point_buffer_id); glBufferData(GL_ARRAY_BUFFER, sizeof(buffer), buffer, GL_STATIC_DRAW); } void OnPointDeleted(size_t id){ GLuint point_buffer_id = active_points[id]; point_buffer_stack.push(point_buffer_id); active_points.erase(id); } Draw the frame only when the position is updated: void OnPositionUpdated (const glm::mat4 & projection){ glm::mat4 model_view_projection; /* Compute model_view_projection and set the corresponding UniformMatrix4fv for using in the vertex shader */ // Draw points glEnableVertexAttribArray(0); for(const auto & id_vertex: active_points){ glBindBuffer(GL_ARRAY_BUFFER, id_vertex.second); glVertexAttribPointer( 0, // layout from vertex shader. 3, // 3D GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *) 0 // array buffer offset ); glDrawArrays(GL_POINTS, 0, 1); } glDisableVertexAttribArray(0); /*Draw a rectangle that shows the current position by drawing two triangles */ glfwSwapBuffers(window); glfwPollEvents(); } On my Asus Zenbook with Intel® Xe Graphics, Ubuntu 20.04, OpenGL starts to lag behind the camera at ~5k points. After some time I get an insufficient memory error from OpenCV (which is built with OpenGL support). Is this expected? What am I doing wrong? How to solve this issue? For the reference, the initialization of OpenGL is done as follows: glfwInit(); glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(1920, 1080, "SLAM 3D visualization", NULL, NULL);
We assign a GL_ARRAY_BUFFER to each point. That's your problem. This means you are allocating an entire buffer object for all of 12 bytes of memory. Putting each point in its own buffer also means that you must render each point with a separate draw call. None of that is a recipe for performance. Create a single large buffer for all the points you intend to use, and render them all with a single draw call. If you need to change parameters or something between points, make them a separate vertex attribute. Or failing that, make them uniforms to your shader and render all of the points that use one set of parameters, change the uniforms, then render the next points that use the new parameters, etc.
70,231,064
70,231,091
Replacing decayed array with a pointer to array resulting in segmentation fault
I was trying to loop through an array using pointers: #include <iostream> #include <iterator> int main() { char name[]{ "Abhi" }; for (char* ptr_c{ name }; ptr_c != (ptr_c + std::size(name)); ++ptr_c) { std::cout << *ptr_c; } std::cout << "\n"; } This results in: Error: Segmentation fault core dumped However, in the for loop's condition testing: for (char* ptr_c{ name }; ptr_c != (ptr_c + std::size(name)); ++ptr_c) ^^^^^^ Replcaing ptr_c with name makes it work. Why? Shouldn't name decay to ptr_c anyway?
ptr_c != ptr_c + std::size(name) This condition is never false. If you add a non-zero number to a pointer, the resulting pointer will never equal the original pointer. Hence, the infinite loop overflows the array. Shouldn't name decay to ptr_c anyway? No. name always decays to a pointer to the first element. ptr_c only starts as the first element, but after the first iteration, it points to other elements.
70,231,173
70,231,199
error: void value not ignored as it ought to be in Arduino
This is a function to convert 1 digit number to 3 digit. For example convert '2' to '002'. void loop() { int x = convertdigit(time); } void convertdigit(int num){ char buffer[50]; int n; n=sprintf (buffer, "%03d",num); return buffer; } Error: void value not ignored as it ought to be /sketch/sketch.ino: In function 'void loop()': /sketch/sketch.ino:33:30: error: void value not ignored as it ought to be int x = convertdigit(time); ^ Error during build: exit status 1 May i know how to fix it?
When you write this you are telling the compiler that convertdigit does not return anything (void): void convertdigit(int num) When you write this, you are telling the compiler to use the return value of convertdigit and store it in x: int x = convertdigit(num); Those two things are in conflict: if convertdigit doesn't return anything, how can you store that nothing in x? Your code is kind of confusing so I'm not sure what you actually intended, but now that I have explained that error message, I hope you are able to make progress. Hint: If you want convertdigit to return an int, change void convertdigit(... to int convertdigit(....
70,231,191
70,231,262
Creating a 2D array with user input
I am trying to make a 2D array where user inputs the number of elements that array can take, also the elements inside the array. I think I manage to create the array, but when I try to put some elements inside it, for example 2x2 array and putting 2 as all of its elements i get this as the output. Here is the code: #include<iostream> #include<stdio.h> using namespace std; int main() { int rowCount,colCount; cout<<"Enter the number of rows in Grid-Land:"; cin>>rowCount; cout<<"Enter the number of columns in Grid-Land:"; cin>>colCount; int** arr = new int*[rowCount]; for(int i = 0; i < rowCount; ++i) arr[i] = new int[colCount]; cout<<"Enter the garbage amounts at the nodes of the MxN Grid-Land:"<<endl; //Elements of the array for(int i=0; i<rowCount; i++){ for (int j=0; i<colCount; i++) cin>>arr[i][j]; } cout<<"\nThe 2-D Array is:\n"; for(int i=0;i<rowCount;i++){ for(int j=0;j<colCount;j++){ cout<<"\t"<<arr[i][j]; } cout<<endl; } return 0; }
It's a typo. Instead of using the "j" variable in the inner loop while taking the input, you have used the "i" variable.
70,231,290
70,240,187
Why doesn't curl-config --cflags print libcurl's header files directory?
I'm trying to include libcurl in my c++ project, and so am trying to find where the header files are located, but running "curl-config --cflags" just prints an empty line, instead of any useful information. I do have libcurl installed, not only because curl-config is included in libcurl and doesn't throw an error when calling it, but running "sudo apt-get install libcurl4" tells me it's already installed, and is the latest version. I've tried googling this problem but haven't found anyone else with the same issue, I've run "sudo apt-get upgrade libcurl4" and "sudo apt-get update" and still get the same issue, and I've run out of ideas. Does anyone know what the problem might be? My operating system is Linux Mint Cinnamon. Let me know if you need other info. Thanks!
I believe S.M. found the answer, which in hindsight I should have tried. Apparently, my system already had the necessary header files in its default include paths, meaning there would be no path to include, hence the blank line. I probably should have tested this by seeing if my code completion software detected it, I would've saved the headache! :) For the sake of future programmers with this issue, here's the takeaway: test to see if a library is installed already first, THEN try to install it! Thanks S.M. for the help!
70,231,702
70,231,963
how do I make a conditional statement to ignore std::string types when using template parameters?
I'm encountering issues when I try to use this operator++() function in a class on a string object instead of a char or numeric data type. I tried the following implementation to check if the data being iterated over is a std::string, but the function is still returning an error when this part of the code is executed: this->current -= this->range->step; This makes sense, sense you can't perform that operation on a std::string, however my current method of making an exception for strings isn't quite working right, it keeps throwing: error: no match for 'operator-=' (operand types are 'std::__cxx11::basic_string<char>' and 'std::__cxx11::basic_string<char>' this->current -= this->range->step; Any ideas on a better implementation, or perhaps a different way to write this code? Iterator& operator++() { bool isStr = false; std::string str = "s"; auto cmp = this->range->step; if (typeid(cmp) == typeid(str)) { // check if the variable is a string isStr = true; } if (this->range->stop > this->range->start || isStr) { // if increasing, or working w/ strings this->current += range->step; return *this; } else if (this->range->stop < this->range->start) { // if decreasing if (!isStr) { this->current -= this->range->step; } } return *this; }
Like your code this isn't complete and won't compile. But when working with code that should make choices dependent on type use compile time constructs! Use things, like "overloading", "templates", "if constexpr", "SFINAE". For example : #include <type_traits> #include <string> struct foo_t { template<typename type_t> auto& operator++() { if constexpr (std::is_same_v<type_t, std::string>) // <== check types at compile time! { // working with strings we go only one way current += range->step; } else { // if increasing if (range->stop > range->start ) { current += range->step; } else if (range->stop < range->start) { current -= range->step; } } return *this; } };
70,231,757
70,231,792
What should I do so that "nan" doesn't show up in console?
My teacher gave this homework. Basically I have two numbers, a and b. I have to show to console answer of this formula for every 'a' number added h=(b-a)/10 but in console I see just nan. How can I solve this error? My code is: #include <iostream> #include <math.h> using namespace std; double s(double x){ long f = 1; long double anw=1; for(int k=1;k<=100;k++){ f=k*f; anw=((pow((x-1),k)*pow(log(3),k))/f)+anw; } return anw; } int main(){ double a=0.2, b=0.8, h; h=(b-a)/10; for(double x=a; x<=b ;x+=h){ cout<<"s(x)="<<s(x)<<endl; } return 0; } Sorry for my bad English!
You get a signed integer overflow in f=k*f; so I suggest that you make f a double: double s(double x){ double f = 1; // double long double anw=1; for(int k=1;k<=100;k++){ f = k * f; // or else you get a signed integer overflow here // f *= k; // a simpler way of writing the above anw=((pow((x-1),k)*pow(log(3),k))/f)+anw; } return anw; } Another note: Include the C++ header cmath instead of the C header math.h.
70,231,789
70,232,271
Where is Node.js own dependencies (V8, libuv) located locally?
I looked at Node.js's documentation: "Node.js includes a number of other statically linked libraries including OpenSSL. These other libraries are located in the deps/ directory in the Node.js source tree." I installed Node.js and check out the directory Program files/nodejs, but I cannot find the deps/directory? Where is V8, libuv being stored in my local files?
Node is a program where its C/C++, static libraries it uses (such as libuv) and various other resources it uses are compiled into node.exe (on Windows). So, the things you're asking about are inside of node.exe. They are not separately available in your file system when you just install the runnable version of nodejs. If you cloned the source repository and built it yourself, you'd have all the components in your local source repository that are then compiled into node.exe. But, if you install an already built version of nodejs, then you will just get the binary executable files that already have the components built into them.
70,232,681
70,232,729
What modifications are possible via a variable of type `const int*&`?
Can we change the value of *y in void function(const int*& x ) when y (i.e int*y= new int) is passed as an argument to function()? If anyone could put it in words it would be great. Please refer to the following code for a better comprehension of my question: void DoWork(const int* &n) { *n = *n * 2; // will this change the value of *a? } int main() { int* a= new int; DoWork(a); } I was trying to understand a program where I came across a similar syntax. Have a look at a snippet from that program: void segmentTable(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr& cloud, const pcl::PointCloud<pcl::PointXYZRGB>::Ptr& seg_cloud){ double z_min = -5, z_max = 0; pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<pcl::PointXYZRGB> seg; // Optional seg.setOptimizeCoefficients (true); // Mandatory seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (0.01); seg.setInputCloud (cloud); seg.segment (*inliers, *coefficients); // Project the model inliers pcl::ProjectInliers<pcl::PointXYZRGB> proj; proj.setModelType (pcl::SACMODEL_PLANE); // proj.setIndices (inliers); proj.setInputCloud (cloud); proj.setModelCoefficients (coefficients); proj.filter (*seg_cloud); /* Create Convex Hull to segment everything above plane */ pcl::ConvexHull<pcl::PointXYZRGB> cHull; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_hull (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointIndices::Ptr hull_inliers (new pcl::PointIndices); cHull.setInputCloud(seg_cloud); cHull.reconstruct(*cloud_hull); cHull.setDimension (2); if (cHull.getDimension () == 2){ pcl::ExtractPolygonalPrismData<pcl::PointXYZRGB> prism; prism.setInputCloud (cloud); prism.setInputPlanarHull (cloud_hull); prism.setHeightLimits (z_min, z_max); prism.setHeightLimits (z_min, z_max); prism.segment (*hull_inliers); } pcl::ExtractIndices<pcl::PointXYZRGB> extract_indices; extract_indices.setInputCloud(cloud); extract_indices.setIndices(hull_inliers); extract_indices.setNegative(true); extract_indices.filter(*cloud); } void int main(){pcl::PointCloud<pcl::PointXYZRGB>::Ptr temp_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud); pcl::PointCloud<pcl::PointXYZRGB>::Ptr seg_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); passThroughFilter(temp_cloud); segmentTable(temp_cloud, seg_cloud);} This code does change the values in temp_cloud and seg_cloud.
No, you are not allowed to change *n since it's a const int. You need to make it non-const for it to work: void DoWork(int*& n) { *n = *n * 2; } Also note that *a is uninitialized so reading it would make the program have undefined behavior. You need to initialize it: int main() { int* a = new int{1}; // *a is now initialized to 1 DoWork(a); delete a; // and delete } The global int a; that you added isn't involved here. The local a in main shadows the global a in main and it's that local a that is passed as an argument to DoWork. The code in the added block doesn't do the same thing. In your added code block the value Ptr is pointing at is non-const so there the value can be changed. Consider this: using Ptr = int*; void foo(const Ptr& p) { // p = int* const& *p *= 2; // ok, *p is an int, not a const int // p = nullptr; // error, the pointer is const } int main() { int* a = new int{1}; foo(a); delete a; }
70,232,859
70,237,784
Is it safe to take address of an out of bounds vector index?
In C++ Primer 5th edition it is mentioned that you can take the address of the non-existent element one past the last element of an array (so long as you don't de-reference it). int arr[] = {0,1,2,3,4,5,6,7,8,9}; int *e = &arr[10]; // 10 is 1 past the end. For std::vector, does indexing into the vector with the [] operator and taking a reference have the same guarantee as array that it won't crash? vector<int> vec(10, 0); int *e = &vec[10]; I do understand there's little use-case for this since we have end() iterators and all that.
It's undefined behaviour. The definition of vec[10] is *(vec.begin() + 10) which is dereferencing an past-the-end iterator. Furthermore Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.
70,232,964
70,233,340
How to pass functions with different signatures as parameter to other function
I'm struggling with the following problem and if this has been asked, I apologize. I have multiple parts in my code doing a similar job - they mainly differ in a function call: int doSomething(string* s, int i) { ... } int doSomethingOther(string* s, string t) { ... } int main() { int num; string s; // do something with num // repeating part start string str1; // do some stuff int res1 = doSomething(&str1, num); cout << "res: " << res1 << " str1: " << str1 << endl; // end // do something with s // here we go again but with a different function call string str2; // do some stuff int res2 = doSomethingOther(&str2, s); cout << "res: " << res2 << " str2: " << str2 << endl; //end return 0; } Is it possible to define a general function to reduce the writing effort? One possibilityis using a parameter for this common function indicating which function should be used. On the other hand if the called function was always the same, it would be also possible by using a function pointer: ... void generalFct(int p, int(*doSomethingFct)(string* aString, int anInt)) { string s; // do some stuff int res = (*doSomethingFct)(&s, p); cout << "res: " << res << " s: " << s << endl; // do some other stuff } ... int main() { int num; // do something with num generalFct(num, &doSomething); ... // update num... generalFct(num, &doSomething); } But unfortunately the signature of doSomething and doSomethingOther differs (otherwise that would be a solution) and that's where I stuck. Is there any kind of technique that helps me to achieve my goal, i.e. something like that: int main() { int num; // do something with num generalFct(num, &doSomething); ... // update num... generalFct(num, &doSomethingOther); }
You can do it like this : #include <iostream> #include <functional> #include <string> // std::function&& so it can accept temporaries // std::function<int(void)> ensures you can only use // functions returning an int. int generic_function(int p, std::function<int(void)>&& fn) { auto value = fn(); auto result = (p * p) + value; std::cout << result << "\n"; return result; } int doSomething(const std::string& str, int i) { std::cout << "doSomething\n"; return i; } int doSomethingOther(const std::string& str1, const std::string& str2) { std::cout << "doSomethingOther\n"; return 12; } int main() { // pass a lambda generic_function(42, [] { return doSomething("1", 1); }); generic_function(12, [] { return doSomethingOther("1", "2"); }); return 0; }
70,233,198
70,233,243
Difference between operator<< and write function?
I wonder what is the difference between std::basic_ostream<CharT,Traits>::operator<< and std::basic_ostream<CharT,Traits>::write. What about performance? #include <iostream> #include <string> int main() { std::string tempMsg; tempMsg.reserve( 100 ); tempMsg += "This is a string"; std::cout.write( tempMsg.data( ), tempMsg.size( ) ).write( "\n", 1 ); std::cout << tempMsg << '\n'; } They both print the same string. But what are the advantages of each of them?
The function allows to specify the number of characters to be outputted for a character array. For example of you have declaration const char *s = "Hello World!"; and want to output only the word "Hello" from the string literal then you can write std::cout.write( s, 5 ); If you will write std::cout << s; then the whole string literal will be outputted. Thus using the function you can output any part of a character array as for example std::cout. write( s + 6, 2 ) << 'w' << s + 11 << '\n'; As for the performance then there is no difference or the difference is insignificant. What is important is the functionality.
70,234,093
70,234,665
How to read into an array from a text file c++
I am sorry if this question seems a bit dumb but i can't get it working even though i have tried many times. So my question is, i have a text file which has a numbers inside it like the following: 10 20 30 30 40 50 60 70 80 The numbers, the row size and the column size are inputs from the user. So far i have written the code for all of this. Which means that user can enter row size, column size and the integers. But i can't read from this file into an array. What can i do for this?
The 2d vector solution is quite good. But if you don't want to use vectors you can use 2d dynamic arrays as well. Here is also a solution where you can use 2d dynamic arrays if you specifically want to input the rows and cols and read from the file. It would be a bit advanced concept for you as it is covered in C++ OOP but you can easily read from your .txt file into a 2d array just according to your requirement. #include<iostream> #include<fstream> #include<string> using namespace std; void main() { int rows=0,cols=0; cout<<"Enter your rows: "; cin>>rows; cout<<"Enter your rows: "; cin>>cols; int** arr= new int*[rows]; for(int k=0;k< rows; k++) arr[k]= new int[cols]; ifstream read_num; read_num.open("matrix.txt"); if(read_num.is_open()) { for(int x=0;x<rows; x++) { for(int y=0;y<cols; y++) { read_num>>arr[x][y]; } } } else cout<<"Failed to open file"<<endl; cout<<"After reading data from file:"<<endl; for(int x=0; x<rows; x++) { for(int y=0; y< cols; y++) { cout<<arr[x][y]<<" "; } cout<<endl; } read_num.close(); for (int i = 0; i < rows; i++) { delete [] arr[i]; } delete[] arr; system("pause"); } The output of this code can be seen here and the input file in the code is named as matrix.txt.
70,234,212
70,234,502
How to recover from segmentation fault on C++?
I have some production-critical code that has to keep running. think of the code as while (true){ init(); do_important_things(); //segfault here clean(); } I can't trust the code to be bug-free, and I need to be able to log problems to investigate later. This time, I know for a fact somewhere in the code there is a segmentation fault getting thrown, and I need to be able to at least log that, and then start everything over. Reading here there are a few solutions, but following each one is a flame-war claiming the solution will actually do more harm than good, with no real explanation. I also found this answer which I consider using, but I'm not sure it is good for my use case. So, what is the best way to recover from segmentation fault on C++?
I suggest that you create a very small program that you make really safe that monitors the buggy program. If the buggy program exits in a way you don't like, restart the program. Posix example: #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdio> #include <iostream> int main(int argc, char* argv[]) { if(argc < 2) { std::cerr << "USAGE: " << argv[0] << " program_to_monitor <arguments...>\n"; return 1; } while(true) { pid_t child = fork(); // create a child process if(child == -1) { std::perror("fork"); return 1; } if(child == 0) { execvp(argv[1], argv + 1); // start the buggy program perror(argv[1]); // starting failed std::exit(0); // exit with 0 to not trigger a retry } // Wait for the buggy program to terminate and check the status // to see if it should be restarted. if(int wstatus; waitpid(child, &wstatus, 0) != -1) { if(WIFEXITED(wstatus)) { if(WEXITSTATUS(wstatus) == 0) return 0; // normal exit, terminate std::cerr << argv[0] << ": " << argv[1] << " exited with " << WEXITSTATUS(wstatus) << '\n'; } if(WIFSIGNALED(wstatus)) { std::cerr << argv[0] << ": " << argv[1] << " terminated by signal " << WTERMSIG(wstatus); if(WCOREDUMP(wstatus)) std::cout << " (core dumped)"; std::cout << '\n'; } std::cout << argv[0] << ": Restarting " << argv[1] << '\n'; } else { std::perror("wait"); break; } } }
70,234,783
70,234,866
How pointer reference works in C++?
I have 3 pointers: Node* head; Node* temp=head; Node* p=new Node(2); Now I assign: temp->next=p Will the next of head will also be changed? head->next=?
Yes, if head would actually point at some allocated memory, temp would point to the same memory. Example: #include <iostream> struct Node { Node(int X) : x(X) {} int x; Node* next; }; int main() { Node* head = new Node(1); Node* temp = head; // temp points to the same memory as head Node* p = new Node(2); temp->next = p; // head->next is the same as temp->next std::cout << head->next->x << '\n' // prints 2 delete head; delete p; }
70,235,311
70,235,421
Converting string from C++ to Swift
I am trying to use C++ functions in Swift. To do that, I use an Objective-C wrapper. I am not familiar with Objective-C and C++ so much. My wrapper function takes Swift String as a parameter from textField. And inside of C++ I encrypt the passed string and return it. Here is my C++ function: string StringModifier::encryptString(string str) { int i; for(i=0; (i<100 && str[i] != '\n'); i++) { str[i] = str[i] + 2; } return str; } And inside of the wrapper: StringModifier stringModifier; -(NSString*)encryptString:(NSString*)str; { string strng = [str UTF8String]; string finalString = stringModifier.encryptString(strng); NSString *result = [NSString stringWithCString: finalString.c_str() encoding:[NSString defaultCStringEncoding]]; return result; } The output of encryptString("Helloworld") is "Jgnnqyqtnf¬√√0*?" and after a couple of times calling this method, it throws an EXC_BAD_ACCESS error. How can I solve this problem?
You need to check for the null character (\0) in C++. Change your for-loop to this: for(i=0; (i<100 && str[i] != '\n' && str[i] != '\0'); i++) { str[i] = str[i] + 2; } Even better, loop depending on how big the string is: string StringModifier::encryptString(string str) { for (int i = 0; i < str.size() && str[i] != '\n'; i++) { str[i] = str[i] + 2; } return str; }
70,235,514
70,235,560
Template type deduction in container initialisation
I understand that a template type parameter can be defaulted, however, this doesn't work when I attempt to construct a std::vector without supplying the template argument: #include<vector> template <typename Int = int> struct integer{ Int i; }; int main(){ integer num; std::vector<integer> vec; return 0; } This code returns a type value mismatch (compiler explorer link). Is it possible to fix this without writing std::vector<integer<int>>
If you have a function with a default parameter: int foo(int bar=0); To call this function you still have to write: int n=foo(); attempting to write int n=foo; will not work, of course. For the same reason if your template's parameters are defaulted you still have to use integer<> to instantiate the template instead of integer
70,236,472
70,236,883
Lack of type information in structured bindings
I just learned about structured bindings in C++, but one thing I don't like about auto [x, y] = some_func(); is that auto is hiding the types of x and y. I have to look up some_func's declaration to know the types of x and y. Alternatively, I could write T1 x; T2 y; std::tie(x, y) = some_func(); but this only works, if x and y are default constructible and not const. Is there a way to write const auto [x, y] = some_func(); for non-default-constructible types of x and y in a way that makes the types of x and y visible? The compiler should preferably complain when I declare x and y as something incompatible with some_func's return types, i.e. not const auto /* T1, T2 */ [x, y] = some_func();. Clarification. Since the comments below my question seem to revolve around whether or not to use &, and some previous answers misunderstood my question as "which syntax to use to extract the returned pair's data type", I think I need to clarify my question. Assume we have our code distributed in multiple files // // API.cpp // #include <utility> class Foo { public: Foo () {} }; Foo foo; class Bar { private: Bar () {} public: static Bar create () { return Bar(); } }; Bar bar = Bar::create(); std::pair<int, bool> get_values () { return std::make_pair(73, true); } std::pair<Foo&, Bar&> get_objects () { return std::pair<Foo&, Bar&>(foo, bar); } // // Program.cpp // int main (int, char**) { const auto [x, y] = get_values(); const auto& [foo, bar] = get_objects(); /* Do stuff with x, y, foo and bar */ return 0; } At the time of writing this code the declarations of get_values and get_objects are fresh in my mind, so I know their return types. But when looking at Program.cpp one week later I barely remember the code in main let alone the data types of its variables or the return types of get_values and get_objects, so I need to open API.cpp and find get_values and get_objects to know their return types. My question is whether there is a syntax to write the data types of the variables x, y, foo and bar in main into the structured binding? Preferably in a manner that allows the compiler to correct me, if I make mistakes, so no comments. Something along the lines of int main (int, char**) { // Pseudo-Code [const int x, const bool y] = get_values(); [const Foo& foo, const Bar& bar] = get_objects(); /* Do stuff with x, y, foo and bar */ return 0; }
There is no mechanism to state the types of the "variables" in a structured binding declaration. If you want the type names to be visible, you have to forgo the convenience of structured binding declarations. This is important because of how structured binding works. x and y aren't really variables per-se. They're stand-ins for accessing the components of the object that the structured binding statement stored. They're components of the object that was captured by the declaration. There is only one actual variable: the unnamed variable that is auto-deduced. The names you declare are just components of that object. Understanding this, now consider this statement: int i = expr; This code works so long as expr is something that can be converted to an int. If you could put typenames in structured binding declarations, people would have the same expectation. They would expect that if a function returns a tuple<float, int>, they could capture this in an auto [int x, int y]. But they can't, because the object being stored is a tuple<float, int>, and its first member is a float. The compiler would have to invent some new object that contains two ints and do a conversion. But that's dangerous, particularly when dealing with return values that contain references. You can theoretically turn a tuple<float&, int> into a tuple<int, int>. But it wouldn't have the same meaning, since you cannot modify the object being referenced. But again, users expect variable declarations to be able to do such conversions. Users rely on it all the time. Taking that power away would serve only to create confusion in the feature. So the feature doesn't do it.
70,236,765
70,237,127
Cpp create string creation without initialization
I want to read the contents of a file into a string. string contents(size, '\0'); -> size was determined above using the file.seekg and file.tellg. file.read((char*) contents.data(), size); Now, I know that the contents of the string will be overwritten in file.read, so there's no need to initialize the the string to null characters. Is there a way to do so?
You can do this: std::string contents(std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}); But it may not be faster. Either way the initialization is likely to be very fast in comparison to reading from the drive.
70,236,805
70,236,904
What is the best (or standard) way of switching between functions?
The C++ code below is a simplified version of what I want to do, just to display the general structure. In each case of the "primary_function()" the structure is identical: function() + 2 The only thing that changes is the function that is used (function 1, 2, 3, or 4). Is there a more efficient way to do this so that I am not "repeating" code in each case? Thank you. #include <iostream> using namespace std; int function1(int a){ return a; } int function2(int b){ return b*b; } int function3(int c){ return c*c + c; } int function4(int d){ return 5*d; } int primary_function(int x, int selection){ switch(selection){ case(1): return function1(x) + 2; break; case(2): return function2(x) + 2; break; case(3): return function3(x) + 2; break; case(4): return function4(x) + 2; break; } } int main(){ cout << primary_function(6,1) << endl; cout << primary_function(6,2) << endl; cout << primary_function(6,3) << endl; cout << primary_function(6,4) << endl; return 0; }
You can use an array of function pointers as follows: int primary_function(int x, int selection) { using fn_ptr_t = int (*)(int); static fn_ptr_t functions[] = { function1, function2, function3, function4 }; return functions[selection - 1](x) + 2; } You can also use std::function<int(int)> as the item type of the array which would allow you to use lambdas, even with closures, in the array instead of only named functions.
70,236,940
70,237,397
How do I build a program after cloning a repository from github?
I want to take this program: https://github.com/baskiton/Img2STL, open it in visual studio and make an executable. I realize I could get it straight from the release, but I want to learn how to edit it and build myself. When I clone it into visual studio, the folders all have blue padlocks next to them and the build function is grayed out. Thanks!
This repo has a CMakeLists.txt file in its root, hence this project can be generated and built via CMake. Generally you download and install CMake and then you have 2 options: Use GUI. Use your console. For Windows you can use powershell: git clone https://github.com/baskiton/Img2STL cd Img2STL mdkir build cd build cmake ../ CMake uses a Generator to configure your projects. It can be defaulted to use your installed Visual Studio. Or else, you can use Ninja and Visual Studio Code, or Visual Studio with open folder to open your project. This should be enough to get you started.
70,237,210
70,237,384
concept std::equality_comparable_with not working for user-defined equality operator
I'm trying to test at compile time whether two types are equality-comparable, and I've defined operator== for them so they should be. yet, the following code does not compile: #include <string_view> struct A { int n; }; bool operator==(const A& a, const std::string_view s) { return a.n == s.size(); } static_assert(std::equality_comparable_with<A, std::string_view>); (godbolt) I've even tried defining operator== for the opposite order as well, and for A with itself, but it won't work either. of course, something like the following works just fine static_assert(std::equality_comparable_with<std::string, std::string_view>); what am I missing here?
Equality means more than just operator== is valid and returns true. And the standard library concepts require this. equality_comparable defines symmetric comparison (equality comparing between the same type). In terms of syntax, this means that t1==t2 has to be a boolean. But there are also semantic requirements that types are expected to provide. One could define equality between t1 and t2 as follows. If they are equal, then for any (pure) function f which acts on a T, f(t1) == f(t2). But for equality between types, this definition is conceptually insufficient. After all, a function f which takes a T may not take a U. To deal with this fact, C++20 defines equality between T and U in terms of a hypothetical third type C. C could be T, U, or some actual other type. But the main thing C++20 asymmetric equality requires is that there is a type C (which allows symmetric equality testing) to which references to T and U can be implicitly converted. This is the common_reference type. This allows the standard to define asymmetric equality in terms of C. That is, for any function f which takes a C, if t == u, then f(t) == f(u). Consider string and string_view. A string is implicitly convertible to a string_view. As such, when doing asymmetric comparisons, the comparison conceptually acts as if any string were converted to a string_view before doing the comparison. That is, string_view acts as the type C. This provision is here specifically to stop code of the form you're trying to write. Conceptually, your struct A has no equivalence relationship with string_view. A function that takes a string_view couldn't take an A of equal value at all, even if string_view were the common reference between them.
70,237,930
70,238,571
Directshow audio capture filter generates only 1 sample per second
I'm making an small real-time audio-video application using Directshow. I use SampleGrabber to grab samples from Audio Capture filter. The SampleGrabber's callback is called every second and each sample's size is 88200 bytes. I printed the WAVEFORMATEX: WAVE_FORMAT_PCM: true nChannels: 2 nSamplesPerSec: 44100 nAvgBytesPerSec: 176400 nBlockAlign: 4 wBitsPerSample: 16 cbSize: 0 so I have 2 questions: Is 'sample' in Directshow's aspect is different from 'sample' in audio recording? Because as I know, there are 44100 samples per second (each costs 16 bits) while directshow's SampleGrabber only grab 1 sample per second (each costs 88200 bytes). Look like lots of sample are aggregated and put into a 'buffer' ? If lots of audio sample are put into a buffer so the buffer's size should be 176400 bytes per sec. Why it is only 88200 bytes per buffer? Is only 1 channel used?
Directshow "sample" is a term for buffer with data: When a pin delivers media data to another pin, it does not pass a direct pointer to the memory buffer. Instead, it delivers a pointer to a COM object that manages the memory. This object, called a media sample, exposes the IMediaSample interface. Then ... size should be 176400 bytes per sec. Why it is only 88200 bytes per buffer? No it should not. You're seeing the default behavior of capture filter to produce 500 ms buffers. You can use IAMBufferNegotiation interface (related questions and search for other) to override this behavior.
70,238,037
70,238,284
C++: Addressing each byte
Trying to extract each byte in a short I've created. While I can print the second (or first) byte, I can't get both. With my current understanding, this should work. Hoping someone can make it clear to me what the error is here. I'm running this on windows x86, so ILP32 data format. #include <iostream> using namespace std; int main() { short i = 0x1123; short* p = &i; short* p1 = p; p1++; char c = *p; char c1 = *p1; cout << "Short: " << hex << i << '\n' << "p: " << p << '\n' << "p1: " << p1 << '\n' << "c: " << hex << (unsigned int)c << '\n' << "c1: " << hex << (unsigned int)c1 << '\n' ; return 0; } Output: Short: 1123 p: 0041FB58 p1: 0041FB56 c: 23 c1: ffffffcc
Here is the fix: #include <iostream> #include <iomanip> int main() { short i = 0x1123; short* p = &i; char* c = reinterpret_cast<char*>( p ); char* c1 = c + 1; std::cout << "Short: " << std::showbase << std::hex << i << '\n' << "p: " << p << '\n' << "c: " << +( *c ) << '\n' << "c1: " << +( *c1 ) << '\n'; return 0; } There is no need for p1. The problem with p1++ is that it adds 2 to the value of p1 and not 1 as you would expect. And that's because p1 is a pointer to short so when you increment it, it progresses by 2 (short is 2 bytes). You need to cast it to a char* so that each time you increment it, it will add 1 to the value. Also, notice the + operator in +( *c ). Using this operator will make sure that *c won't be printed as a character but instead as its ASCII value or whatever value it has, thus there is no need to cast it to int. Possible output: Short: 0x1123 p: 0xb71f3ffd8e c: 0x23 c1: 0x11
70,238,051
70,238,148
Traversing a binary tree using a vector return type
I am trying to traverse a templated AVLtree with a key value pair and return a vector of all the values. When using a cout statement, I can tell that the function is correctly traversing the tree and it will return all values in the tree. However, when I try to add this to a vector and use it in another part of my program, only the root node has been stored. vector<s> treeTraversal(){ return treeTraversal(root); } vector<s> treeTraversal(AVLNode<t, s> *node ){ vector<s> temp; if(node != nullptr){ treeTraversal(node -> left); treeTraversal(node -> right); temp.push_back(node -> vectorToBe); } return temp; } I am intending to store all the returned values in a vector so I can access them in a later part of my program
I'd try something like this. You'll avoid creating a ton of vector<s>s in the stack. vector<s> treeTraversal(){ vector<s> result; treeTraversal(root, result); return result; } void treeTraversal(AVLNode<t, s> *node, vector<s>& visited ){ if(node != nullptr){ treeTraversal(node -> left, visited); treeTraversal(node -> right, visited); visited.push_back(node->vectorToBe); } }
70,238,430
70,238,654
Choose C++ template at runtime
Is there any way to achieve the functionality of below code without creating the mapping between strings and classes manually? template<class base, typename T> base* f(const std::string &type, T &c) { if(type == "ClassA") return new ClassA(c); else if(type == "ClassB") return new ClassB(c); // many more else if... return nullptr; } All classes looks something like this: class ClassA: public BaseClass { public: std::string label="ClassA"; ... }; And we can use it as: BaseClass *b = f<BaseClass>("ClassA", DifferentObject); Each new class results in a new if else line of code. Is there any way to automate this so f function "updates" itself when new supported class is added? The solution must work for C++11.
A possible macro: #include <memory> #include <string> class BaseClass {}; class ClassA : public BaseClass { public: std::string label = "ClassA"; explicit ClassA(int /*unused*/) {} }; class ClassB : public BaseClass { public: std::string label = "ClassB"; explicit ClassB(int /*unused*/) {} }; template<class base, typename T> auto f(const std::string &type, T c) -> std::unique_ptr<base> { #define CASE(NAME) \ if (type == "NAME") { \ return std::unique_ptr<base>(new NAME(c)); \ } CASE(ClassA) CASE(ClassB) //... #undef CASE return nullptr; // Statement at the end needed for last else! } auto main() -> int { auto b = f<BaseClass>("ClassA", 0); } Also use unique_ptr since memory managing raw pointers are EVIL.
70,238,437
70,239,135
Mysql json binary encoding
Does MySQL use bson for its json-encoding? Or does it have a custom binary encoding? For example: Optimized storage format. JSON documents stored in JSON columns are converted to an internal format that permits quick read access to document elements. When the server later must read a JSON value stored in this binary format, the value need not be parsed from a text representation. The binary format is structured to enable the server to look up subobjects or nested values directly by key or array index without reading all values before or after them in the document. https://dev.mysql.com/doc/refman/8.0/en/json.html
The internal encoding for JSON in MySQL is not literally BSON. https://elephantdolphin.blogspot.com/2019/01/mysql-shell-8014-now-with-bson.html says: The import utility can process documents that use JSON extensions to represent BSON data types, convert them to an identical or compatible MySQL representation, and import the data value using that representation. The message of this blog post is that BSON needs to be converted to be stored in MySQL. But in some ways the binary encoding of MySQL's JSON has similar goals as BSON. MySQL's JSON encoding converts some data types to binary representations instead of strings. Also, objects and arrays each contain a kind of "table of contents" for their keys and values. You can read more about the MySQL JSON encoding in the source here: https://github.com/mysql/mysql-server/blob/8.0/sql/json_binary.h All that said, there's no reason you need to know the encoding of binary JSON extensions in MySQL, because textual JSON is converted into binary on insert, and converted back to text on fetch.
70,238,518
70,247,130
Empty line at the end of the output
So I have a "db.csv" data file. Code reads each value from the file separated by a comma (value1, ...). Unnecessary spacings from the lines are deleted, then the finished line is printed out as desired (one space between values). The problem is that I have to pass the tests on a site called repl.it. And I fail every test, because there is an extra blank line at the end of the output. Any suggestions? I know, that it's probably because of the endl at the cout, but how else do I do it? Minimal reproducible code: #include <iostream> #include <fstream> #include <algorithm> #include <sstream> using namespace std; int main() { fstream file("db.csv", ios::in); string value1, value2, value3, value4, value5, line; cout << "result:" << endl; while (getline(file, line)) { if (line.length() > 1) { istringstream str1(line); while (getline(str1, value1, ','), getline(str1, value2, ','), getline(str1, value3, ','), getline(str1, value4, ','), getline(str1, value5, '\n')) { value1.erase(remove(value1.begin(), value1.end(), ' '), value1.end()); value2.erase(remove(value2.begin(), value2.end(), ' '), value2.end()); value3.erase(remove(value3.begin(), value3.end(), ' '), value3.end()); value4.erase(remove(value4.begin(), value4.end(), ' '), value4.end()); value5.erase(remove(value5.begin(), value5.end(), ' '), value5.end()); cout << value1 << " " << value2 << " " << value3 << " " << value4 << " " << value5 << endl; } } } } db.csv file data: Riga,Kraslava,Pr,15:00,11.00 Riga ,Kraslava,Pr ,18:00,11.00 Kraslava,Riga,Pr,08:00,11.00 Kraslava,Daugavpils,Ot ,10:00, 3.00 Ventsplis,8.00,Liepaja,Sv,20:00 Dagda,Sv Rezekne,Riga,Tr,13:00,10.50 Dagda,Kraslava, Ce,18:00, 2.50 Dagda,Kraslava,Ce,18:00,2.50,Sv Riga,Ventspils, Pt,09:00 , 6.70 Liepaja,Ventspils,Pt,17:00,5.50 Output: Riga Kraslava Pr 15:00 11.00 Riga Kraslava Pr 18:00 11.00 Kraslava Riga Pr 08:00 11.00 Kraslava Daugavpils Ot 10:00 3.00 Ventsplis 8.00 Liepaja Sv 20:00 Rezekne Riga Tr 13:00 10.50 Dagda Kraslava Ce 18:00 2.50 Dagda Kraslava Ce 18:00 2.50,Sv Riga Ventspils Pt 09:00 6.70 Liepaja Ventspils Pt 17:00 5.50 *blank line* Desired output: Riga Kraslava Pr 15:00 11.00 Riga Kraslava Pr 18:00 11.00 Kraslava Riga Pr 08:00 11.00 Kraslava Daugavpils Ot 10:00 3.00 Ventsplis 8.00 Liepaja Sv 20:00 Rezekne Riga Tr 13:00 10.50 Dagda Kraslava Ce 18:00 2.50 Dagda Kraslava Ce 18:00 2.50,Sv Riga Ventspils Pt 09:00 6.70 Liepaja Ventspils Pt 17:00 5.50
The fix for this is adding line.erase(remove(line.begin(), line.end(), '\r'), line.end()); to the code. But just to be sure (it probably is an overkill) I added this as I did with the spacing removal - this line for every value (value1, ..., value5). This fixed the issue right away. From what I understood from google, this prevents moving the cursor at the start of a new line.
70,239,191
70,239,261
"&" and ">>" number operator in C++?
I am trying to make a raycaster game in Javascript, and to do so, I am following this tutorial, which is written in C++. My problem stems from trying to convert the following two lines to javascript: int tx = (int)(texWidth * (floorX - cellX)) & (texWidth - 1); color = (color >> 1) & 8355711; // make a bit darker I don't know what the "&" and ">>" mean in those two lines. Is there an equivalent in Javascript?
The code directly translates to JS with the removal of the (int) typecast and the replacement of int with let/var/const. let tx = (texWidth * (floorX - cellX)) & (texWidth - 1); color = (color >> 1) & 8355711; // make a bit darker & is the bitwise and, >> is the bitshift right, explained well here.
70,239,523
70,239,550
Function that takes templated length parameter
I have a custom array class template <typename T, unsigned L> class Array { T m_buff[L]; }; My goal is to declare a function that would take a copy of the Array class and use its values to return a sum of all elements. The problem is that the code compiles only for a function defined as int sum(Array<int, 3> a) and not for a function defined as int sum(Array<int> a).
not for a function defined as int sum(Array a). That's because Array<int> is not a valid type. Your Array template requires two parameters, not one. What you are looking for, simply, is just another template function: template<unsigned size> int sum(const Array<int, size> &a) { // Function code here: } As far how to code it: simply think of what your code needs to be, in case of your Array<int, 3>, or, maybe, Array<int, 100000> and replace 3 or 100000 with size/
70,239,556
70,241,268
For mouse click ray casting a line, why aren't my starting rays updating to my camera position after I move my camera?
When camera is moved around, why are my starting rays are still stuck at origin 0, 0, 0 even though the camera position has been updated? It works fine if I start the program and my camera position is at default 0, 0, 0. But once I move my camera for instance pan to the right and click some more, the lines are still coming from 0 0 0 when it should be starting from wherever the camera is. Am I doing something terribly wrong? I've checked to make sure they're being updated in the main loop. I've used this code snippit below referenced from: picking in 3D with ray-tracing using NinevehGL or OpenGL i-phone // 1. Get mouse coordinates then normalize float x = (2.0f * lastX) / width - 1.0f; float y = 1.0f - (2.0f * lastY) / height; // 2. Move from clip space to world space glm::mat4 inverseWorldMatrix = glm::inverse(proj * view); glm::vec4 near_vec = glm::vec4(x, y, -1.0f, 1.0f); glm::vec4 far_vec = glm::vec4(x, y, 1.0f, 1.0f); glm::vec4 startRay = inverseWorldMatrix * near_vec; glm::vec4 endRay = inverseWorldMatrix * far_vec; // perspective divide startR /= startR.w; endR /= endR.w; glm::vec3 direction = glm::vec3(endR - startR); // start the ray points from the camera position glm::vec3 startPos = glm::vec3(camera.GetPosition()); glm::vec3 endPos = glm::vec3(startPos + direction * someLength); The first screenshot I click some rays, the 2nd I move my camera to the right and click some more but the initial starting rays are still at 0, 0, 0. What I'm looking for is for the rays to come out wherever the camera position is in the 3rd image, ie the red rays sorry for the confusion, the red lines are supposed to shoot out and into the distance not up. // and these are my matrices // projection glm::mat4 proj = glm::perspective(glm::radians(camera.GetFov()), (float)width / height, 0.1f, 100.0f); // view glm::mat4 view = camera.GetViewMatrix(); // This returns glm::lookAt(this->Position, this->Position + this->Front, this->Up); // model glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
Its hard to tell where in the code the problem lies. But, I use this function for ray casting that is adapted from code from scratch-a-pixel and learnopengl: vec3 rayCast(double xpos, double ypos, mat4 projection, mat4 view) { // converts a position from the 2d xpos, ypos to a normalized 3d direction float x = (2.0f * xpos) / WIDTH - 1.0f; float y = 1.0f - (2.0f * ypos) / HEIGHT; float z = 1.0f; vec3 ray_nds = vec3(x, y, z); vec4 ray_clip = vec4(ray_nds.x, ray_nds.y, -1.0f, 1.0f); // eye space to clip we would multiply by projection so // clip space to eye space is the inverse projection vec4 ray_eye = inverse(projection) * ray_clip; // convert point to forwards ray_eye = vec4(ray_eye.x, ray_eye.y, -1.0f, 0.0f); // world space to eye space is usually multiply by view so // eye space to world space is inverse view vec4 inv_ray_wor = (inverse(view) * ray_eye); vec3 ray_wor = vec3(inv_ray_wor.x, inv_ray_wor.y, inv_ray_wor.z); ray_wor = normalize(ray_wor); return ray_wor; } where you can draw your line with startPos = camera.Position and endPos = camera.Position + rayCast(...) * scalar_amount.
70,239,646
70,239,989
Why can I pass a reference to an uninitialized element in c++?
Why does the following code compile? class Demo { public: Demo() : a(this->a){} int& a; }; int main() { Demo d; } In this case, a is a reference to an integer. However, when I initialize Demo, I pass a reference to a reference of an integer which has not yet been initialized. Why does this compile? This still compiles even if instead of int, I use a reference to a class which has a private default constructor. Why is this allowed?
Why does this compile? Because it is syntactically valid. C++ is not a safe programming language. There are several features that make it easy to do the right thing, but preventing someone from doing the wrong thing is not a priority. If you are determined to do something foolish, nothing will stop you. As long as you follow the syntax, you can try to do whatever you want, no matter how ludicrous the semantics. Keep that in mind: compiling is about syntax, not semantics.* That being said, the people who write compilers are not without pity. They know the common mistakes (probably from personal experience), and they recognize that your compiler is in a good position to spot certain kinds of semantic mistakes. Hence, most compilers will emit warnings when you do certain things (not all things) that do not make sense. That is why you should always enable compiler warnings. Warnings do not catch all logical errors, but for the ones they do catch (such as warning: 'Demo::a' is initialized with itself and warning: '*this.Demo::a' is used uninitialized), you've saved yourself a ton of debugging time. * OK, there are some semantics involved in compiling, such as giving a meaning to identifiers. When I say compiling is not about semantics, I am referring to a higher level of semantics, such as the intended behavior.