C++ Questions

Pages: 1... 10111213
Use the VS wizards to create a Desktop WinAPI app and even the bare-bones is a bloated mess.

Use the VS wizards to create a Console app, and 80% of the file is chock full of comments as if the user had NEVER done any programming before.

I haven't done much work with DLLs or static LIB files, I don't remember the code files for those type of projects as being excessive and bloated.
I haven't done much work with DLLs or static LIB files

I have, but I don’t think I have ever started one in VS. Just Notepad++.
The type of stuff I do is definitely programming hobbyist things. Write a lot of sample test code for various aspects of learning new C++ features, new to me that is, mucking around with tweaking old and antiquated code so a modern computer OS won't weep or sneer at it, etc.

DLLs and static LIBs just haven't been part of what I've been doing lately. ::shrug::
A lot of what I have done is to create libraries over the years.

For example, I wrote a joystick reader to be used by Tcl/Tk, which required a stubs-enabled DLL. Not particularly difficult, but does require a different way of looking at how the code is used and how to prepare it to compile properly on Windows (and *nixen, but Windows is where linkage stuff is weird).

But that’s just where my interests have led me. Nothing professional ever led me to it. If you ever needed to do it you’d pick it up easy, there’s a ton of example code out there and it never really gets old.
I've dinked around with the MS Learn tutorials for creating DLLs and LIBs.

https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-170

https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-static-library-cpp?view=msvc-170

These online examples show the utility of solutions containing multiple projects in the VS IDE.

Petzold's Programming Windows 5th Edition book shows an example of creating a data only DLL IIRC.

So I ain't all that unfamiliar with the process, what I do as a normal programming flow just doesn't require doing the DLL/LIB two-step.
The "project" that I had to build in Windows back then had actually split the program into executable and (multiple) shared objects. For additional fun some of the lib*.so's were explicitly linked (and also unlinked) during runtime. Some call those "plugins". This was way before Qt had abstraction layer for such things.

The only thing I learned about Windows platform was to dislike it; more was not required for getting the job done.
seeplus wrote:
Well you'll really like APL. This one line of code removes HTML tags from txt:
{⍵ /⍨ ~{⍵∨≠\⍵}⍵∊'<>'} txt


Pardon me for posting off-topic but you inspired me to do some studying. Since you posted I've been working my way through this free book:
https://www.dyalog.com/mastering-dyalog-apl.htm
I'm about a third of the way through. I'm not at the point where I can make standalone programs with APL, but it comes with a very nice REPL, and it's been enjoyable so far, and a lot easier than expected.

So far I've been really surprised with how similar it "feels" to programming the STL. I knew that std::iota nods to , but it seems that the influence is much deeper. Example: the backslash above is already in C++ as std::inclusive_scan (and one of its arguments is ≠, aka std::not_equal_to).

Don't take my word for it, but as @seeplus knows, that program is super neat, and could be translated to C++ without too much work.
Last edited on
I don't like the unreadable symbolic heavy 'children of perl' stuff but I have long wanted to see limited unicode univeral symbols like that not-equals sign added to most languages. The <> or != and similar crap was a necessary evil in 1975, but its time to move past that now. And having greek letters for variable names in math... would be pure joy.
jonnin wrote:
And having greek letters for variable names in math... would be pure joy.


I am sure this can be done. I am not on my personal laptop atm, but will have a go later after work.

https://en.cppreference.com/w/cpp/language/identifiers

Edit:

@jonnin

Maybe you could just try it in your environment, or have a go on Compiler Explorer?

Edit2:

Just for fun, it may be possible to create an operator ≠
Last edited on
I am sure this can be done. I am not on my personal laptop atm, but will have a go later after work.

Some editors can display e.g. ≠ as a visual substitute for !=, or «nodiscard» for [[nodiscard]]. For instance Emacs has been able to do this with a built-in feature since 2014. The way this is designed, the file always contains the correct C++, but the screen displays whatever you want.

Admittedly this is different from having Greek letters in variable names. I don't use this feature because it tends to alter apparent line lengths and the alignment of stuff on different lines. It just doesn't work for me, even though I wish it would. YMMV.
Last edited on
Using Unicode letters in variable names has been part of the standard for a while now. You need UTF-8 input files and a compiler that accepts it, though.
https://en.cppreference.com/w/cpp/language/identifiers

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

constexpr double π = 3.14159265;

int main()
{
	double r;
	std::cout << "radius? ";
	std::cin >> r;
	std::cout 
		<< "area          = " << (π * r * r) << "\n"
		<< "circumference = " << (2 * π * r) << "\n";
}

If you install FiraCode (https://github.com/tonsky/FiraCode) you can get things like != to look like , etc. This is just a trick, though, and there are people who despise it for that reason.

I’m still trying to figure out what I need to do to get it to work on Linux with Notepad++. (Though, IIRC, it would require me to do something odd to my system and I said ‘nah’.)

EDIT
Checked again. IDK what I haven’t done right, but I can’t seem to get FiraCode to work on my Mint Box.
Last edited on
You fellas have some fascinating stories and have lead some interesting tech-savvy lives. Do you feel that you know most of the offerings around C++ and can accomplish anything given time?

Or is it more of a humbling experience given how much is out there and you will need considerable effort from going from a database/data analysis to graphical design (movies/entertainment/games) or to something like AI? Would you feel like a fish out of water when going from one to another for an involved effort?

Speaking of AI, once quantum computing becomes standardized and this meets further advances in AI, this will invalidate humans as programmers for the most part. Then I foresee the majority of programmers being MIT-type and working on the AI that will build their designs through iterative processes. Sort of a digital EVOLUTION but on a grandiose scale and betwixt know-how and trial and error. End goal will be iterative, evolving, with live updates (latter not for all industries). This will achieve further exponential growth on compute power and "energy" solutions that are on the pipeline (i.e. photonic or graphene (epigraphene) cpu's & fusion).

Researchers Claim First Functioning Graphene-Based Chip
https://spectrum.ieee.org/graphene-semiconductor
epigraphene—boasts enhanced electron mobility compared with that of traditional silicon, allowing electrons to traverse with significantly less resistance. The outcome is transistors capable of operating at terahertz frequencies, offering speeds 10 times as fast as that of the silicon-based transistors used in current chips.


Human programmers may exist more on directing the AI and linking various nodes based on needs. And even these programmers will become fewer as AI will build the AI of the future industries (AI building the AI)... not immediately but on the horizon.

For it or against, when these realities are met I would imagine one would rather have the AI generate the code and test it, rather than a human? Things will become too massive and not only would we want but NEED the AI to.
You overestimate AI. AI isn’t smart. It just handles patterns. It may very well be possible in time to automate some very simple and/or repetitive programming tasks with AI, but even with quantum computing I do not think computers are likely to solve the Halting Problem any time soon.

As far as C++, every three years they throw a wrench in what I know. I’m comfortable with C++17, and haven’t bothered give do more than a passing looking look at C++20/23/etc. But it is something that would be relatively easy to learn. I know C++ (and a number of other programming languages) very well.

What is humbling is that the application of computer technologies to the world around us is so vast that no one human today could know it all in a measly lifetime.

Knowing how the machine works is the key. Understanding that makes learning stuff it is used for dependent only on being able to learn domain knowledge for the target application.
Currently "dumb" and not as "smart" as people might think, yes. But one can make the argument that these systems can outwit us in chess, grammar, lightning fast aerospace calculations...etc.

Once we make the leap into new compute power and energy, and couple that with cyclical trials, we end up with something like a brain with various specialized parts. If we think this is going fast, wait until we set AI to design and trial itself. So not just creation, but testing the creation to improve on itself non-stop.

If I picked up a handful of dirt and said to you this will pretty much become a walking and thinking brain, you would call me crazy. But that is pretty much what has happened to life on earth via trials and coercion. Once these converging technologies meet we should be able to replicate what took millions of years into years and decades, and with other fields centuries.

I see intelligence as chemistry driving electricity. The chemistry can easily be reproduced with routines and subroutines and the human brain can already be "hacked" with various drugs. Chemistry is already hacking your consciousness when in sleep mode with the ability to turn on/off your own cpu. One can make the argument that the sum total of our experiences IS THE CONSCIOUSNESS and that it is a simulation onto itself (brain acting as the simulator to the reality around you).

Even humans operate on an AI scale, where we need the input and knowledge to be able to interpret, re-interpret and arrange. The more input we have the more we are able to output and arrange. What drives one to arrange a program vs musical arrangements vs a theory of everything is boiled down to environmental and chemistry, which again can be hacked in a digital world.

The real question is can a collection of electricity in particular arrangement have consciousness? But it already has in us. Personally, I don't think there will be a fundamental difference once we experiment and bench test these AI collections. I think it will just lend itself to consciousness as human evolution did for us, gradually but on a much, much faster scale. Yes, not immediately but given time...remains to be seen.

Training AI to program C++ is a more immediate task and I think improvements will happen sooner than we expect.

Have you seen newcomers into the industry being turned off by the advent of AI or has that not been disruptive as yet?
You have to pay attention to which AI people talk about. The "AI" in current headlines is "just" latest generation of number crunching methods that is possible by current (GPGPU) compute resources and big data.

If a model is trained by same "sample data" as students of C++, then the result is not very good ...



The "AI" as in "as idiotic as humans" is something quite different. You "cyclical trials" sounds biblical -- "god" tried something, was not happy and killed practically everything, and repeat.
Last edited on
Duthomhas wrote:
It may very well be possible in time to automate some very simple and/or repetitive programming tasks with AI, ...


ChatGPT is already capable of writing code in a number of languages, and I have heard of developers using it to do simple and/or repetitive programming tasks.

So I had a go, it took a few attempts to get what I wanted:


asksChatGPT wrote:
Please write C++ code for the resection using Tienstra's barycentric coordinate method with the formulae shown here: https://en.wikipedia.org/wiki/Tienstra_formula


asksChatGPT wrote:
With reference to the last answer, it is not using the formulae mentioned in the web page. Those formulae use the cot function. What method was being used in the last answer?


ChatGPT wrote:
You're correct; the method used in the last answer was not directly implementing the formulae mentioned on the Wikipedia page for Tienstra's formula. Instead, it appeared to use a method based on solving a system of linear equations derived from the given angles and known points.

Tienstra's formula involves the use of the cotangent function and barycentric coordinates to compute the coordinates of the computed point. Let me correct that and provide an implementation using Tienstra's formula:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cmath>

struct Point3D {
    double x;
    double y;
    double z;
};

class Resection {
private:
    Point3D points[3];
    double angles[3];

public:
    Resection(Point3D p1, Point3D p2, Point3D p3, double ang1, double ang2, double ang3)
        : points{p1, p2, p3}, angles{ang1, ang2, ang3} {}

    Point3D computePoint() {
        double cot_alpha = 1 / tan(degToRad(angles[0]));
        double cot_beta = 1 / tan(degToRad(angles[1]));
        double cot_gamma = 1 / tan(degToRad(angles[2]));

        double sum_cots = cot_alpha + cot_beta + cot_gamma;

        double x = (cot_alpha * points[0].x + cot_beta * points[1].x + cot_gamma * points[2].x) / sum_cots;
        double y = (cot_alpha * points[0].y + cot_beta * points[1].y + cot_gamma * points[2].y) / sum_cots;
        double z = (cot_alpha * points[0].z + cot_beta * points[1].z + cot_gamma * points[2].z) / sum_cots;

        Point3D computedPoint;
        computedPoint.x = x;
        computedPoint.y = y;
        computedPoint.z = z;
        return computedPoint;
    }

private:
    double degToRad(double degrees) {
        return degrees * M_PI / 180.0;
    }
};

int main() {
    Point3D p1 = {10, 20, 0};
    Point3D p2 = {30, 15, 0};
    Point3D p3 = {25, 30, 0};
    double ang1 = 45.0;
    double ang2 = 60.0;
    double ang3 = 75.0;

    Resection resection(p1, p2, p3, ang1, ang2, ang3);
    Point3D computedPoint = resection.computePoint();

    std::cout << "Computed Point: (" << computedPoint.x << ", " << computedPoint.y << ", " << computedPoint.z << ")" << std::endl;

    return 0;
}


The code compiled and ran, but I haven't checked it to see if it is actually correct.

ChatGPT seems to be capable of writing code in a bunch of languages:

asksChatGPT wrote:
What computing languages can ChatGPT produce code for?


ChatGPT can generate code for a wide range of programming languages, including but not limited to:

Python
JavaScript
C++
Java
C#
Ruby
Swift
Go
PHP
TypeScript
Kotlin
Rust
MATLAB
R
Shell Scripting (Bash)
HTML/CSS
SQL
and more!

If you have a specific language in mind, feel free to ask, and I'll do my best to generate code in that language for you!


Written in Pascal, a program to produce formatted Pascal code from unformatted Pascal code.
I played with ChatGPT and C++ back in Dec and asked it to make snippets of code for writing and reading to files. It worked just fine.

One can use it to make various classes/structs to make a larger program, so I believe it.
In the interest of honesty, the chatGPT code I posted earlier, is not anywhere close to being right. Note to self: don't post unchecked code late at night !

I found that for non trivial problems, it is quite tough to be explicit enough in asking the question, in order to get it to do what one wants exactly. It probably would have been quicker to write the code from scratch, rather than repeatedly refining the question. Although I guess that one could try doing it piecemeal as SubZeroWins has mentioned.

With the code above, the main problem is that it conflates the angles of the triangle with the observed angles alpha, beta, gamma. There were also problems with it wanting to "keep things simple" by ignoring minutes and seconds in the angles :+| In the past I have had problems with generating template code that didn't compile.

Anyway, my motivation for posting was to say that chatGPT can generate code in lots of languages.

Code that does work correctly is shown in the next post.

So this code is full of poor man's debugging std::cout , today I was using vim and gdb, std::cout was easier than gdb. Could have used VSCode, but it's fun to use vim every now and then.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>

struct Radian {
	double rad;
};

// Structure to represent degrees, minutes, and seconds of an angle
struct Angle {
    int degrees;
    int minutes;
    double seconds;
    double radians;


    //copy constructor
    Angle(const Angle& other) {
	degrees = other.degrees;
	minutes = other.minutes;
	seconds = other.seconds;
	radians = other.radians;
    }

    // Constructor to initialize the angle and calculate radians
    Angle(int _degrees, int _minutes, double _seconds)
        : degrees(_degrees), minutes(_minutes), seconds(_seconds) {
        // Calculate radians using degreesToRadians function
        radians = degreesToRadians(degrees, minutes, seconds);
    }

    // Constructor using decimal degrees
    Angle(double DecimalDeg) {
	    	decimalToDMS(DecimalDeg, degrees, minutes, seconds);
        	radians = degreesToRadians(degrees, minutes, seconds);
    }

    // Constructor using radians
    Angle (Radian radiansIn) {
	    //std::cout << "M_PI is "<< M_PI <<"\n";
	radians = radiansIn.rad;
	double DecimalDeg = radians * 180.0 / M_PI;
	decimalToDMS(DecimalDeg, degrees, minutes, seconds);
    }


    // Function to convert degrees, minutes, and seconds to radians
    static double degreesToRadians(int degrees,  int minutes, double seconds) {
        double totalDegrees = degrees + (double)minutes / 60.0 + seconds / 3600.0;
        return totalDegrees * M_PI / 180.0;
    }

    // Function to convert decimal degrees to unsigned int degrees, unsigned int minutes, and double seconds
void decimalToDMS(double decimalDegrees, int& degrees, int& minutes, double& seconds) {

    // Extract degrees
    degrees = static_cast<unsigned int>(decimalDegrees);

    // Calculate remaining decimal part (minutes and seconds)
    double remainder = std::abs(decimalDegrees - static_cast<double>(degrees)) * 60.0;

    // Extract minutes
    minutes = static_cast<unsigned int>(remainder);

    // Calculate remaining decimal part (seconds)
    seconds = (remainder - static_cast<double>(minutes)) * 60.0;
}

};

// Structure to represent a 2D point
struct Point {
    double x, y;

    Point() = default;

    Point(double _x, double _y) : x(_x), y(_y) {}
    Point(const Point& other) {
	x = other.x;
	y = other.y;
    }
};

class Resection {
private:
    std::vector<Point> TrianglePoints;
    std::vector<Angle> ObservedAngles;

    std::vector<Angle> TriangleAngles;
    std::vector<double> Kvalues;
    double TotalKvalues = 0.0;
    Point OccupiedPt;

public:
    Resection(const std::vector<Point>& TrianglePointsIn, 
	      const std::vector<Angle>& ObservedAnglesIn)
       
	{

	 TrianglePoints = TrianglePointsIn;
	ObservedAngles = ObservedAnglesIn;

	calculateTriangleAngles();
	calcKvalues();
	TotalK();
	}

private:

    // Function to calculate the angles of the triangle in radians
    void calculateTriangleAngles() {
        // Clear existing triangle angles if any
        TriangleAngles.clear();

        // Calculate angles for each vertex of the triangle
        for (size_t i = 0; i < TrianglePoints.size(); ++i) {
            // Indices for the current point and observed angle
            size_t next = (i + 1) % TrianglePoints.size(); // Next point index (wraps around)
            size_t prev = (i == 0) ? TrianglePoints.size() - 1 : i - 1; // Previous point index

            // Calculate vectors for the sides of the triangle
            double vx1 = TrianglePoints[prev].x - TrianglePoints[i].x;
            double vy1 = TrianglePoints[prev].y - TrianglePoints[i].y;
            double vx2 = TrianglePoints[next].x - TrianglePoints[i].x;
            double vy2 = TrianglePoints[next].y - TrianglePoints[i].y;

	    std::cout << "vx1 is " << vx1 << "\n";
	    std::cout << "vy1 is " << vy1 << "\n";
	    std::cout << "vx2 is " << vx2 << "\n";
	    std::cout << "vy2 is " << vy2 << "\n";
comments

            // Calculate angle using dot product and cross product
            double crossProduct = vx1 * vy2 - vy1 * vx2;
            double dotProduct = vx1 * vx2 + vy1 * vy2;

	    std::cout << "crossProduct is " << crossProduct << "\n";
	    std::cout << "dotProduct is " << dotProduct << "\n"; 

            Radian AngleRadians;
	    //Radian AngleRadians2;
	    AngleRadians.rad = atan2(crossProduct, dotProduct);
		std::cout << "AngleRadians.rad is " << AngleRadians.rad << "\n";



            // Create Angle object and add to TriangleAngles
            TriangleAngles.push_back(Angle(AngleRadians));
        }
    }

    double cot(const double angle) {
	return 1.0 / std::tan(angle);
    }
	//Calculate K values
	
void calcKvalues() {
	for(std::size_t i = 0; const auto&  Ang : TriangleAngles ) {
		double Kvalue = 1.0 /  ( cot(Ang.radians)- cot(ObservedAngles[i].radians)  );
		Kvalues.push_back(Kvalue);
		i++;
	}
	for(std::size_t i =0; const auto& K : Kvalues) {
		std::cout << "Kvalue" << i << " " << K << "\n";
		i++;
	}
}

void TotalK() {

	//std::cout << "TotalK is " << TotalKvalues << "\n";
	for(const  auto K  : Kvalues) {
		TotalKvalues += K ;

	}
	std::cout << "TotalK is " << TotalKvalues << "\n";
}

public:

	Point getOccupiedPt() const  {
		return OccupiedPt;
	}
    // Function to calculate occupied point using the Tienstra formula
	void calculateOccupiedPoint() {
		std::cout << "Entering calculateOccupiedPoint\n";


    	double SumKE = 0.0;
	for(int i =0; const auto& ThePoint : TrianglePoints ) {
		 SumKE += Kvalues[i] * ThePoint.x;
		 i++;
	}

	std::cout << "SumKE is " << SumKE << "\n";
	OccupiedPt.x = SumKE / TotalKvalues;

	double SumKN = 0.0; // sum of Kvlaue * North Ordinate for each point
	for(int i =0 ; const auto& ThePoint : TrianglePoints) {
		SumKN += Kvalues[i] * ThePoint.y;
		i++;
	}

	std::cout << "SumKN is " << SumKN << "\n";
	OccupiedPt.y = SumKN / TotalKvalues;
    }

    // Function to calculate distance between two points
    double calculateDistance(const Point& p1, const Point& p2) const {
        return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
    }
    // Function to perform the resection calculation and display results
    void performResection() {
        // Calculate occupied point
        calculateOccupiedPoint();
    }
}; // End of resection class

int main() {


	    std::cout << std::fixed;
	    std::cout << std::setprecision(16);

    // Define triangle vertices (PtA, PtB, PtC) and observed angles (alpha, beta, gamma) in degrees
    const std::vector<Point> TrianglePointsIn = { Point(0.0, 0.0), Point(500.0, 866.0254037844386), Point(1000.0, 0.0) };
    const std::vector<Angle> ObservedAnglesIn = { Angle(120, 0, 0.0), Angle(120, 0, 0.0), Angle(120, 0, 0.0) };

    // Create a Resection object with the triangle vertices and observed angles
    Resection resection(TrianglePointsIn, ObservedAnglesIn);

    // Perform resection calculation and display results
    resection.performResection();
	Point result = resection.getOccupiedPt();
    std::cout << "Occupied Point is " << result.x << " " << result.y << "\n";

        // Calculate distances to each triangle vertex
	
        for (size_t i = 0; i < TrianglePointsIn.size(); ++i) {
            double dist = resection.calculateDistance(TrianglePointsIn[i], resection.getOccupiedPt() );
            std::cout << "Distance to Pt" << static_cast<char>('A' + i) << ": " << dist << " units\n";
        }

return 0;
}
Pages: 1... 10111213