attn cpp coders

Hello and i hope that you are having a good day.

I am beginning my c++ journey. I have a dozen books and an iso specification, plus i am using the cppreference website for further research.

I have a question (which requires a bit of a description) for any cpp coders in the forum. I cannot find an exact answer to my question, so i am hoping for some guidance. I am a php coder and i use dynamic arrays and dynamic associative arrays to store dynamic/unknown data. For example, i wrote a jpeg marker and exif data scanner in php. Upload jpeg and i use the temporary file on the server to read the file. I initalize arrays to hold markers and their position in the file. I use many arrays to hold jpeg data and create associations of data so that i can display this data to the user after scanning. I am used to this dynamic data handling method in php. However, i do not yet see how this is done using cpp.

I wonder how do you handle dynamic data in cpp? if a cpp program requires a different method of storing dynamic data, then please advise. Along with this php dynamic array usage, i also have the pleasure of using string indexes to identify data easily (like a lookup table). Example: being userdata['name'] = post_name and userdata['email'] = post_email etc. Then, i can simply echo/print/printf Hello $userdata['username']. Does cpp also support string indexes somehow?

so far i've read about struct and std::vector and std::map. Any tips?
 
You can mimic PHP and javascript but at the expense of some performance.

Using your example above, a plain class or struct will do.

Code:
#include <string>
#include <iostream>

struct Userdata
{
    std::string Name;
    std::string Email;
}
user;

std::cout << user.Name << std::endl;

The advantage is the compiler knows the byte offset of these two data members. It does not need to do a lookup to retrieve them. The following is closer to what you've used in the past.

Code:
#include <string>
#include <map>
#include <iostream>

std::map<std::string, std::string> hash;

hash["name"] = "johnjohn";
hash["email"] = "john@example.com";

auto it = hash.find("name");
if (it != hash.end())
    std::cout << it->second.c_str() << std::endl;
 
Hello elephant, Thank you for the info and the example code is perfect! bravo! I appreciate you very much. Your reply is a major step in the right direction. cpp has a ton of data for me to process and sort out mentally. As you allready know, the tools in the toolbox and learning how to use the tools is everything in programming. Your examples have helped me understand this process in cpp much better than yesterday.

Thank you time a googolplex :)
 
This chart is helpful for determining which container to use in which situation.

G70oT.png
 
My advice is get solid on the basics.
C++ doesn't have garbage collection so you need to pay attention to memory allocation and deallocation.
This is where understanding classes, constructors and destructors can help.
There is a lot of stuff in the STL, don't try and memorize everything, just before you write something, just look to see if you have to.
cppreference is a great place to learn from.
 
eternal_noob that is a great contribution. Thank you for taking time out of your day to help a beginner. :)

mer yes, the lack of garbage collection is something very important for me to remember coming from php and i am aware of memory management and the dangers/criticism associate with it. Good tip and reminder! also, that cppreference site is amazing. I am happy that it exists. :)

this forum has alot of nice and helpful members. Thank you all very much (even those not in this thread).
 
I am beginning my c++ journey.
Why?

If you are trying to solve one relatively simple problem, and don't know C++ yet, the most likely learning C++ and all its complexity is not an good way to go about it. These days, the only advantage of C++ over other programming languages is runtime CPU efficiency, and even there other languages (such as Java) are within small factors. Memory management in C++ is hard. And C++ is a highly complex language; modern techniques (such as ref counting pointers, move semantics, and auto typing) that make programming easier are usually not reflected in instructional materials, and have limitations and edge cases. My advice would be: Use a better programming language.

On the other hand, if you are trying to learn C++ for the sake of learning it, I would not start with a problem that requires lots of dynamic data.
 
Memory management in C++ is hard. And C++ is a highly complex language; modern techniques (such as ref counting pointers, move semantics, and auto typing) that make programming easier are usually not reflected in instructional materials, and have limitations and edge cases. My advice would be: Use a better programming language.
The problem is then you shift the effort into searching for, maintaining and generally juggling bindings and other dependencies. And that is a worthless task. At least memory management is a transferrable skill.

C++ is a gross language but one that will serve anyone well for years to come because it allows you to become resilient.

But I do suppose it depends on how far the OP wants to go? johnjohn is this just for a hobby and to organise your music collection or do you want to go much further than that?
 
Hello and i hope that you are having a good day.

I am beginning my c++ journey. I have a dozen books and an iso specification, plus i am using the cppreference website for further research.

I have a question (which requires a bit of a description) for any cpp coders in the forum. I cannot find an exact answer to my question, so i am hoping for some guidance. I am a php coder and i use dynamic arrays and dynamic associative arrays to store dynamic/unknown data. For example, i wrote a jpeg marker and exif data scanner in php. Upload jpeg and i use the temporary file on the server to read the file. I initalize arrays to hold markers and their position in the file. I use many arrays to hold jpeg data and create associations of data so that i can display this data to the user after scanning. I am used to this dynamic data handling method in php. However, i do not yet see how this is done using cpp.

I wonder how do you handle dynamic data in cpp? if a cpp program requires a different method of storing dynamic data, then please advise. Along with this php dynamic array usage, i also have the pleasure of using string indexes to identify data easily (like a lookup table). Example: being userdata['name'] = post_name and userdata['email'] = post_email etc. Then, i can simply echo/print/printf Hello $userdata['username']. Does cpp also support string indexes somehow?

so far i've read about struct and std::vector and std::map. Any tips?

None of this require manually using new() or malloc(3). You are not in *actual* dynamic memory management.

What you need before you tackle the C++ collection classes is some theory. Which kind of collection data structure is good for what, and what can they do, what can they hold? You want to at least cover lists, arrays and associative arrays (hashtables). Scripting languages often mesh several of these together into one construct. You need to unlearn that.

The diagram posted above is good but overkill for a complete beginner.
 
Why?

If you are trying to solve one relatively simple problem, and don't know C++ yet, the most likely learning C++ and all its complexity is not an good way to go about it. These days, the only advantage of C++ over other programming languages is runtime CPU efficiency, and even there other languages (such as Java) are within small factors. Memory management in C++ is hard. And C++ is a highly complex language; modern techniques (such as ref counting pointers, move semantics, and auto typing) that make programming easier are usually not reflected in instructional materials, and have limitations and edge cases. My advice would be: Use a better programming language.

On the other hand, if you are trying to learn C++ for the sake of learning it, I would not start with a problem that requires lots of dynamic data.
I don't have to justify my will to learn C++ :) you seem quite determined to discourage beginners but i am set on C++. I do not worry about the problems described with the language. One cannot expect a beginner to do any better or worse than seasoned vets. Pros have memory issues, so why should i be held at a different standard?i will learn and that requires time, patience and a splash of tenacity. I remember whenever i began learning php. Alot of people recommended 'other languages' but php has everything that i need to accomplish my tasks. I also program advanced php concepts.
 
But I do suppose it depends on how far the OP wants to go? johnjohn is this just for a hobby and to organise your music collection or do you want to go much further than that?
Hello kpedersen, i actually use html, css and javascript to organize my music collection. I can launch mp3 files with a single click into vlc for playback from my external hdd.

i am interested in building more useful programs. I do not wish to discuss my plans in public (asking for more discouragement or criticism) but an example project that i would like to bring into reality using C++ is nature related. I started studying insects and spiders several years ago. I taught myself how to dissect and identify species based upon genitalia. I've recorded a few first records for Germany along the way. I'd like to create an insect and spider identification app. I have my own keys designed and i'd like to start by creating a key based identification app. Eventually, i'd like to get into computer vision, machine learning territory and be able to scan an image and identify insects and spiders by photo submission (when possible). I could use php for alot of this but not the vision part. I have lots of image processing and image vision docs from research gate. I think it would be pretty cool to build an Avengers movie inspired Jarvis for insect and spider identification. "Jarvis, which fly is this?" "Hello John, it appears to be a Lucilia and most likely sericata based upon ...." "Thank you, Jarvis" :)
 
I just want to point something out about PHP and C/C++: they are very similar at times. Like family. I feel comfortable on the C/C++, Java, JavaScript, PHP side of the tracks. I believe that PHP is written in C language, so i guess that the question should be learn C or C++?

Code:
if elseif else in php (www.php.net/manual/en/control-structures.elseif.php)

if ($x === 1) {
  //then do something
} elseif ($x === 2) {
  //then do something about that too
} else {
  //do something else not covered above
}

C++ (code snippet from en.cppreference.com/w/cpp/language/if.html)
extern int x; // no definition of x required
 
int f()
{
    if constexpr (true)
        return 0;
    else if (x)
        return x;
    else
        return -x;
}

Code:
switch in PHP (www.php.net/manual/en/control-structures.switch.php)

switch ($_SERVER['REQUEST_METHOD'] {
  case 'GET':
    //run some code here and single line comment
  break;
  case 'POST':
    /* run some code and this also serves
       as a multi-line comment */
  break;
  default:
    echo 'invalid server Request Method';
}

C++ (code snippet from en.cppreference.com/w/cpp/language/switch.html)
#include <iostream>
 
int main()
{
    const int i = 2;
    switch (i)
    {
        case 1:
            std::cout << '1';
        case 2:              // execution starts at this case label
            std::cout << '2';
        case 3:
            std::cout << '3';
            [[fallthrough]]; // C++17 attribute to silent the warning on fallthrough
        case 5:
            std::cout << "45";
            break;           // execution of subsequent statements is terminated
        case 6:
            std::cout << '6';
    }
 
    std::cout << '\n';
 
    switch (i)
    {
        case 4:
            std::cout << 'a';
        default:
            std::cout << 'd'; // there are no applicable constant expressions
                              // therefore default is executed
    }

regarding Computer Vision mentioned in my last post, i am aware of OpenCV and that Python is recommended but elif? match case? really? Python is too lefty for a righty if that makes any sense to you. Python is weird to me. I almost get a headache when i see Python source code, so i have a tendency to stay away from Python. I simply have no interest at this time.
 
I am beginning my c++ journey.
You might want to ask on more appropriate C++ specific forums than this freebsd one. A general advice for any language is to study carefully some existing programs in it and try to modify the. As well as write toy programs to explore specific features. Then for larger useful programs, where you may be faced with having to make multiple decisions, you have some experience now as to what feature to pick. Another suggestion is to avoid premature optimization. Pick the simplest data structures & algorithms to build a prototype that implements minimum key features, then profile it and work on speeding up hotspots as necessary. I often start with a hello world program and then add features one at a time so that my prototype always builds and passes all tests.

Like ralphbsz I can’t resist adding that if you’re starting on C++ now, your time may be better spent learning simpler & newer languages (go, rust, zig, lisp, etc). But if your heart is set on C++, don’t let anyone discourage you!
 
I'd like to create an insect and spider identification app
Sounds very cool!

So quick middleware requirements for example:
  • CV (OpenCV)
  • Image processing (stb_image, lodepng, etc)
  • ML (Tensorflow? PyTorch)
  • Database (Sqlite)
  • UI (Qt/Gtk/Fltk/etc)
This isn't too strenuous for any specific language. The most complex, OpenCV is native C++ but has pretty good bindings for Python, etc.
The machine learning part tends to be larger. It is generally all C++ in the lower layers but by far most of the ecosystem is Python.

Homogeneous C++ will result in a tighter program (less extra dependencies) but leveraging the existing "1st party" python bindings and perhaps using TkInter could be a decent compromise if you did want to explore a higher level language.
 
Sounds very cool!

So quick middleware requirements for example:
  • CV (OpenCV)
  • Image processing (stb_image, lodepng, etc)
  • ML (Tensorflow? PyTorch)
  • Database (Sqlite)
  • UI (Qt/Gtk/Fltk/etc)
This isn't too strenuous for any specific language. The most complex, OpenCV is native C++ but has pretty good bindings for Python, etc.
The machine learning part tends to be larger. It is generally all C++ in the lower layers but by far most of the ecosystem is Python.

Homogeneous C++ will result in a tighter program (less extra dependencies) but leveraging the existing "1st party" python bindings and perhaps using TkInter could be a decent compromise if you did want to explore a higher level language.
I don't see added value mixing languages...
 
This isn't too strenuous for any specific language. The most complex, OpenCV is native C++ but has pretty good bindings for Python, etc.
The machine learning part tends to be larger. It is generally all C++ in the lower layers but by far most of the ecosystem is Python.

Homogeneous C++ will result in a tighter program (less extra dependencies) but leveraging the existing "1st party" python bindings and perhaps using TkInter could be a decent compromise if you did want to explore a higher level language.
Hello kpedersen Thank you for taking time to reply :)

so do you think that i should be learning Python? and work on C++ as a hobby? I really do want to create this software. I also have a need for this concept to exist. I want to pour my on knowledge into the software (AI). I am happy to know that someone else likes the idea. And when i think about cryptic species, we could add dna sequencing databases for dna matching as well. I have a deep desire to bring this dream to reality and php is probably not the answer here.
 
Hello Alain De Vos, Thank you for taking time out of your day to reply and offer advice. I will get some books on Python and do a mental reset before i begin reading. I have to mentally separate php from other languages but i am used to organizing info mentally. I will work on C++ on the side too, like you. I am off to do some research on Python... :)
 
Hello kpedersen Thank you for taking time to reply :)

so do you think that i should be learning Python? and work on C++ as a hobby? I really do want to create this software. I also have a need for this concept to exist. I want to pour my on knowledge into the software (AI).

I would do a quick experiment with both (C++ and Python). Make a very simple program that reads pixels in from OpenCV and displays them on a simple GUI window. This is useful because it gives you a taster of setting the project up and how dependencies will be handled for each.

  • If you find the effort comparable, then I would go with C++. As mentioned it may be a bit slower to get started with but the quality of output will be higher and more resilient.

  • If you find yourself struggling, then I would stick with Python. You don't want to get bogged down with some of the nonsense C++ creates when your purpose is to make the program itself.
 
& if you like python , there is NIM ,creating binary executables , using almost the same syntax. Very good QT6 & postgresql bindings.
Classes , nice type system. Garbage collection, (reference counting alike)
Ruby ok, for rails then, but even then , i prefer python for sessions etc...
Crystal, like ruby but compiling to exe. More niche.
[ Me i must spend more time with racket :) ]
 
I think Python is gross, but I'm just a weak-minded Java programmer. I can probably be ignored safely.

I recently ran into something like this at work:
Python:
def __getattr__(self, name: str):
        # If class is extened, or name doesn't start with query_by_
        if self.__class__ is not DatabaseTable or not name.startswith("query_by_") or not name[9:]:
            raise AttributeError(f"{name} not found")
        bin = name[9:]
        schema: DatabaseSchema = self.__dict__.get("schema")  # type: ignore
        if bin not in schema.index_keys:
            raise AttributeError(f"Index not found for attribute {bin}")

        def func(
            value: str | int | None = None,
            modifier: Callable[[Query], None] | None = None,
            policy: dict | None = None
        ) -> Iterable[DatabaseResponse]:
            return self.query(bin=bin, value=value, modifier=modifier, policy=policy)
        return func

Maybe you're smarter than me and what this does is intuitively obvious to you.
 
So if you search for stupid things in languages , you will always be able to find them. And this is an interesting exercise. But nobody told you to use them, and most manuals will not tell you how avoid them.
 
I think Python is gross, ...

I recently ran into something like this at work: ...
Fortunately, C code is usually clean, clear, readable and understandable. For example, it should be obvious that the following (valid) C program ...
C:
define _ -F<00||--F-OO--;
int F=00,OO=00;
main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO()
{
            _-_-_-_
       _-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
        _-_-_-_-_-_-_-_
            _-_-_-_
}
... calculates pi.
 
Back
Top