Search results
Top results related to what is the structure of a program written in c++?
Top Answer
Answered Apr 01, 2010 · 12 votes
You could implement a binary search tree by first defining a Node struct:
struct Node{ void *nodeData; Node *leftChild; Node *rightChild;}
Then, you could define a root of the tree with another Node *rootNode;
The Wikipedia entry on Binary Search Tree has a pretty good example of how to implement an insert method, so I would also recommend checking that out.
In terms of duplicates, they are generally not allowed in sets, so you could either just discard that input, throw an exception, etc, depending on your specification.
Other Answers
Answered Feb 26, 2020 · 47 votes
Step debug into g++
6.4 stdlibc++ source
Did you know that on Ubuntu's 16.04 default g++-6 package or a GCC 6.4 build from source you can step into the C++ library without any further setup?
By doing that we easily conclude that a Red-black tree used in this implementation.
This makes sense, since std::set can be traversed in order, which would not be efficient in if a hash map were used.
main.cpp
#include <cassert>#include <set>-int main() { std::set<int> s; s.insert(1); s.insert(2); assert(s.find(1) != s.end()); assert(s.find(2) != s.end()); assert(s.find(3) == s3.end());}
Compile and debug:
g++ -g -std=c++11 -O0 -o main.out main.cppgdb -ex 'start' -q --args main.out-
Now, if you step into s.insert(1) you immediately reach /usr/include/c++/6/bits/stl_set.h:
487 #if __cplusplus >= 201103L488 std::pair<iterator, bool>489 insert(value_type&& __x)490 {491 std::pair<typename _Rep_type::iterator, bool> __p =492 _M_t._M_insert_unique(std::move(__x));493 return std::pair<iterator, bool>(__p.first, __p.second);494 }495 #endif
which clearly just forwards to _M_t._M_insert_unique.
So we open the source file in vim and find the definition of _M_t:
typedef _Rb_tree<key_type, value_type, _Identity<value_type>, key_compare, _Key_alloc_type> _Rep_type; _Rep_type _M_t; // Red-black tree representing set.-
So _M_t is of type _Rep_type and _Rep_type is a _Rb_tree.
OK, now that is enough evidence for me. If you don't believe that _Rb_tree is a Black-red tree, step a bit further and read the algorithm.
unordered_set
uses hash table
Same procedure, but replace set with unordered_set on the code.
This makes sense, since std::unordered_set cannot be traversed in order, so the standard library chose hash map instead of Red-black tree, since hash map has a better amortized insert time complexity.
Stepping into insert leads to /usr/include/c++/6/bits/unordered_set.h:
415 std::pair<iterator, bool>416 insert(value_type&& __x)417 { return _M_h.insert(std::move(__x)); }-
So we open the source file in vim and search for _M_h:
typedef __uset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h;-
So hash table it is.
std::map
and std::unordered_map
</b>
Analogous for std::set vs std:unordered_set: What data structure is inside std::map in C++?
Performance characteristics
You could also infer the data structure used by timing them:
Graph generation procedure and Heap vs BST analysis and at: Heap vs Binary Search Tree (BST)
We clearly see for:
- [" std::set ",", a logarithmic insertion time"]
- [" std::unordered_set , a more complex hashmap pattern:",""," ","on the non-zoomed plot, we clearly see the backing dynamic array doubling on huge one off linearly increasing spikes","on the zoomed plot, we see that the times are basically constant and going towards 250ns, therefore much faster than the std::map , except for very small map sizes","","Several strips are clearly visible, and their inclination becomes smaller whenever the array doubles.","","I believe this is due to average linearly increasing linked list walks withing each bin. Then when the array doubles, we have more bins, so shorter walks.",""]
Other Answers
Answered Aug 16, 2017 · 32 votes
As KTC said, how std::set is implemented can vary -- the C++ standard simply specifies an abstract data type. In other words, the standard does not specify how a container should be implemented, just what operations it is required to support. However, most implementations of the STL do, as far as I am aware, use red-black trees or other balanced binary search trees of some kind (GNU libstdc++, for instance, uses red-black trees).
While you could theoretically implement a set as a hash table and get faster asymptotic performance (amortized O(key length) versus O(log n) for lookup and insert), that would require having the user supply a hash function for whatever type they wanted to store (see Wikipedia's entry on hash tables for a good explanation of how they work). As for an implementation of a binary search tree, you wouldn't want to use an array -- as Raul mentioned, you would want some kind of Node data structure.
1/5
Top Answer
Answered Dec 26, 2015 · 57 votes
So, here the address of function and the address of first variable in function is not same. Why so?
Why it would be so? A function pointer is a pointer that points to the function. It does not point to the first variable inside the function, anyway.
To elaborate, a function (or subroutine) is a collection of instructions (including variable definition and different statements/ operations) that performs a specific job, mostly multiple times, as required. It is not just a pointer to the elements present inside the function.
The variables, defined inside the function are not stored in the same memory area as that of the executable machine code. Based on the storage type, the variables which are present inside the function are located in some other part of the memory of the executing program.
When a program is built (compiled into an object file), different part of the program gets organized in a different manner.
- Usually, the function (executable code), resides in a separate segment called code segment, usually a read-only memory location.
- The compile time allocated variable, OTOH, are stored into the data segment.
- The function local variables, usually are populated onto the stack memory, as and when needed.
So, there is no such relation that a function pointer will yield the address of the first variable present in the function, as seen in the source code.
In this regard, to quote the wiki article,
Instead of referring to data values, a function pointer points to executable code within memory.
So, TL;DR, the address of a function is a memory location inside the code (text) segment where the executable instructions reside.
Other Answers
Answered Feb 26, 2020 · 47 votes
Step debug into g++
6.4 stdlibc++ source
Did you know that on Ubuntu's 16.04 default g++-6 package or a GCC 6.4 build from source you can step into the C++ library without any further setup?
By doing that we easily conclude that a Red-black tree used in this implementation.
This makes sense, since std::set can be traversed in order, which would not be efficient in if a hash map were used.
main.cpp
#include <cassert>#include <set>int main() { std::set<int> s; s.insert(1); s.insert(2); assert(s.find(1) != s.end()); assert(s.find(2) != s.end()); assert(s.find(3) == s3.end());}
Compile and debug:
g++ -g -std=c++11 -O0 -o main.out main.cppgdb -ex 'start' -q --args main.out
Now, if you step into s.insert(1) you immediately reach /usr/include/c++/6/bits/stl_set.h:
487 #if __cplusplus >= 201103L488 std::pair<iterator, bool>489 insert(value_type&& __x)490 {491 std::pair<typename _Rep_type::iterator, bool> __p =492 _M_t._M_insert_unique(std::move(__x));493 return std::pair<iterator, bool>(__p.first, __p.second);494 }495 #endif
which clearly just forwards to _M_t._M_insert_unique.
So we open the source file in vim and find the definition of _M_t:
typedef _Rb_tree<key_type, value_type, _Identity<value_type>, key_compare, _Key_alloc_type> _Rep_type; _Rep_type _M_t; // Red-black tree representing set.
So _M_t is of type _Rep_type and _Rep_type is a _Rb_tree.
OK, now that is enough evidence for me. If you don't believe that _Rb_tree is a Black-red tree, step a bit further and read the algorithm.
unordered_set
uses hash table
Same procedure, but replace set with unordered_set on the code.
This makes sense, since std::unordered_set cannot be traversed in order, so the standard library chose hash map instead of Red-black tree, since hash map has a better amortized insert time complexity.
Stepping into insert leads to /usr/include/c++/6/bits/unordered_set.h:
415 std::pair<iterator, bool>416 insert(value_type&& __x)417 { return _M_h.insert(std::move(__x)); }
So we open the source file in vim and search for _M_h:
typedef __uset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h;
So hash table it is.
std::map
and std::unordered_map
</b>
Analogous for std::set vs std:unordered_set: What data structure is inside std::map in C++?
Performance characteristics
You could also infer the data structure used by timing them:
Graph generation procedure and Heap vs BST analysis and at: Heap vs Binary Search Tree (BST)
We clearly see for:
- [" std::set ",", a logarithmic insertion time"]
- [" std::unordered_set , a more complex hashmap pattern:",""," ","on the non-zoomed plot, we clearly see the backing dynamic array doubling on huge one off linearly increasing spikes","on the zoomed plot, we see that the times are basically constant and going towards 250ns, therefore much faster than the std::map , except for very small map sizes","","Several strips are clearly visible, and their inclination becomes smaller whenever the array doubles.","","I believe this is due to average linearly increasing linked list walks withing each bin. Then when the array doubles, we have more bins, so shorter walks.",""]
Other Answers
Answered Aug 16, 2017 · 32 votes
As KTC said, how std::set is implemented can vary -- the C++ standard simply specifies an abstract data type. In other words, the standard does not specify how a container should be implemented, just what operations it is required to support. However, most implementations of the STL do, as far as I am aware, use red-black trees or other balanced binary search trees of some kind (GNU libstdc++, for instance, uses red-black trees).
While you could theoretically implement a set as a hash table and get faster asymptotic performance (amortized O(key length) versus O(log n) for lookup and insert), that would require having the user supply a hash function for whatever type they wanted to store (see Wikipedia's entry on hash tables for a good explanation of how they work). As for an implementation of a binary search tree, you wouldn't want to use an array -- as Raul mentioned, you would want some kind of Node data structure.
2/5
Top Answer
Answered May 03, 2011 · 19 votes
Virtual tables in C++ is an implementation detail. One possible implementation is shown on the diagram below.
Two instances of the class (A and B) exists. Each instance has two vtbl pointers and the vtbl contains pointers to actual code.
In your example there is no instance data, but I have for illustrative purposes assumed that each class contains some instance data.
When a pointer to Tester is cast to a pointer to IFoo the pointer is adjusted as shown on the diagram. Instead of pointing to the start of the instance data it points to the IFoo part of the instance data.
The neat thing is that a caller using an IFoo pointer doesn't have any knowledge about the data surrounding the IFoo part of the class. The same can be said of for a caller using an IPlugin pointer. This pointer happens to point to the start of the instance data also pointed to by a Tester pointer but only a caller using a Tester pointer knows the entire layout of the instance data.
Using dynamic_cast requires RTTI (Run-Time Type Information) which is not on the diagram. The vtbl will contain additional type information that given a say IFoo pointer to an instance of Tester allows the code at run-time to discover the actual type of object pointed by the pointer and use that to downcast the pointer.
3/5
Top Answer
Answered Mar 22, 2011 · 4 votes
There's probably no 'cost', assuming that the two compilers are of equivalent quality. The traditional objection to this is that C++ is much more complex and so it's more likely that a C++ compiler will have bugs in it.
Realistically, this is much less of a problem that it used to be, and I tend to do most of my embedded stuff now as a sort of horrible C/C++ hybrid - taking advantage of stronger typing and easier variable declaration rules, without incurring RTTI or exception handling overheads. If you're taking a given compiler (GCC, etc) and switching it from C to C++ mode, then much of what you have to worry about is common to the two languages anyway.
Other Answers
Answered Feb 26, 2020 · 47 votes
Step debug into g++
6.4 stdlibc++ source
Did you know that on Ubuntu's 16.04 default g++-6 package or a GCC 6.4 build from source you can step into the C++ library without any further setup?
By doing that we easily conclude that a Red-black tree used in this implementation.
This makes sense, since std::set can be traversed in order, which would not be efficient in if a hash map were used.
main.cpp
#include <cassert>#include <set>-int main() { std::set<int> s; s.insert(1); s.insert(2); assert(s.find(1) != s.end()); assert(s.find(2) != s.end()); assert(s.find(3) == s3.end());}
Compile and debug:
g++ -g -std=c++11 -O0 -o main.out main.cppgdb -ex 'start' -q --args main.out-
Now, if you step into s.insert(1) you immediately reach /usr/include/c++/6/bits/stl_set.h:
487 #if __cplusplus >= 201103L488 std::pair<iterator, bool>489 insert(value_type&& __x)490 {491 std::pair<typename _Rep_type::iterator, bool> __p =492 _M_t._M_insert_unique(std::move(__x));493 return std::pair<iterator, bool>(__p.first, __p.second);494 }495 #endif
which clearly just forwards to _M_t._M_insert_unique.
So we open the source file in vim and find the definition of _M_t:
typedef _Rb_tree<key_type, value_type, _Identity<value_type>, key_compare, _Key_alloc_type> _Rep_type; _Rep_type _M_t; // Red-black tree representing set.
So _M_t is of type _Rep_type and _Rep_type is a _Rb_tree.
OK, now that is enough evidence for me. If you don't believe that _Rb_tree is a Black-red tree, step a bit further and read the algorithm.
unordered_set
uses hash table
Same procedure, but replace set with unordered_set on the code.
This makes sense, since std::unordered_set cannot be traversed in order, so the standard library chose hash map instead of Red-black tree, since hash map has a better amortized insert time complexity.
Stepping into insert leads to /usr/include/c++/6/bits/unordered_set.h:
415 std::pair<iterator, bool>416 insert(value_type&& __x)417 { return _M_h.insert(std::move(__x)); }
So we open the source file in vim and search for _M_h:
typedef __uset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h;-
So hash table it is.
std::map
and std::unordered_map
</b>
Analogous for std::set vs std:unordered_set: What data structure is inside std::map in C++?
Performance characteristics
You could also infer the data structure used by timing them:
Graph generation procedure and Heap vs BST analysis and at: Heap vs Binary Search Tree (BST)
We clearly see for:
- [" std::set ",", a logarithmic insertion time"]
- [" std::unordered_set , a more complex hashmap pattern:",""," ","on the non-zoomed plot, we clearly see the backing dynamic array doubling on huge one off linearly increasing spikes","on the zoomed plot, we see that the times are basically constant and going towards 250ns, therefore much faster than the std::map , except for very small map sizes","","Several strips are clearly visible, and their inclination becomes smaller whenever the array doubles.","","I believe this is due to average linearly increasing linked list walks withing each bin. Then when the array doubles, we have more bins, so shorter walks.",""]
Other Answers
Answered Aug 16, 2017 · 32 votes
As KTC said, how std::set is implemented can vary -- the C++ standard simply specifies an abstract data type. In other words, the standard does not specify how a container should be implemented, just what operations it is required to support. However, most implementations of the STL do, as far as I am aware, use red-black trees or other balanced binary search trees of some kind (GNU libstdc++, for instance, uses red-black trees).
While you could theoretically implement a set as a hash table and get faster asymptotic performance (amortized O(key length) versus O(log n) for lookup and insert), that would require having the user supply a hash function for whatever type they wanted to store (see Wikipedia's entry on hash tables for a good explanation of how they work). As for an implementation of a binary search tree, you wouldn't want to use an array -- as Raul mentioned, you would want some kind of Node data structure.
4/5
Top Answer
Answered Sep 14, 2023 · 2 votes
TL:DR: This probably makes no difference, and no easily-predictable difference
CPUs run machine code, not C++ source. In machine code we only have "goto" (jumps) and if()goto conditional branches. This else doesn't make a difference to the actual program logic and thus you'd expect either version would compile to the same machine code. (And if it doesn't, the worse one is a missed-optimization compiler defect.)
But source-code structure (such as hiding something behind an else vs. on the main path after an if) might or might not affect the compiler's heuristics for guessing which path is more often taken and thus laying out that as the fast path with fewer taken branches, in the absence of [[likely]] / [[unlikely]] decorators or profile-guided optimization info. Compilers have various heuristics for guessing whether to optimize for the case where an if is normally taken or normally not taken, e.g. looking at the condition and whether it's comparing a variable to a small or large number, especially if it has any value-range info on the variable being compared.
See Ciro's answer showing the effect on branch layout. Note that this is unrelated to runtime branch prediction except on older CPUs where static prediction (forward-taken / backwards not-taken) is sometimes used when dynamic predictors are cold. With IT-TAGE predictors (at least in Intel since Haswell), that doesn't happen, they always predict something. Taken branches in machine code are a bit less efficient than fall-through (e.g. into an if body) because the front-end isn't just fetching contiguous code.
But there's no direct or simple connection between source layout and machine-code layout; it's the compiler's job optimize branch layout, not just transliterate C into asm, so you're going to have to look at the asm (e.g. on https://godbolt.org/) if you want to know what the compiler did. See also How to remove "noise" from GCC/clang assembly output?
If you're interested in micro-optimizations, see What considerations go into predicting latency for operations on modern superscalar processors and how can I calculate them by hand? and read up on details of recent CPUs, like Chips & Cheese's write-up of Zen 4. https://chipsandcheese.com/2022/11/05/amds-zen-4-part-1-frontend-and-execution-engine/ And older articles like David Kanter's excellent deep dives into Sandybridge and Haswell. Also links in https://stackoverflow.com/tags/x86/info such as Agner Fog's excellent microarchitecture guides: https://www.agner.org/optimize/
For basics, see Modern Microprocessors A 90-Minute Guide!
5/5
www.geeksforgeeks.org › structure-of-cpp-programStructure of C++ Program - GeeksforGeeks
www.geeksforgeeks.org › structure-of-cpp-programNov 2, 2023 · The structure of the program written in C++ language is as follows: Documentation Section: This section comes first and is used to document the logic of the program that the programmer going to code. It can be also used to write for purpose of the program.
- 8 min
cplusplus.com › doc › tutorialStructure of a program - C++ Users
cplusplus.com › doc › tutorialStructure of a program The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which simply prints "Hello World" to your computer screen.
Code sample
int main () {std::cout << "Hello World! ";std::cout << "I'm a C++ program";}www.learncpp.com › cpp-tutorial › statements-and-the1.1 — Statements and the structure of a program – Learn C++
www.learncpp.com › cpp-tutorial › statements-and-theFeb 2, 2024 · When we want to convey an idea to another person, we typically write or speak in sentences (not in random words or syllables). In C++, when we want to have our program do something, we typically write statements. Most (but not all) statements in C++ end in a semicolon.
cplusplus.com › doc › oldtutorialStructure of a program - C++ Users
cplusplus.com › doc › oldtutorialStructure of a program. Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program: // my first program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } Hello World! Edit & run on cpp.sh.
ornl-training.github.io › cpp-novice › 01-structureIntroduction to C++: Structure of a Program
ornl-training.github.io › cpp-novice › 01-structureWhat are the basic elements of a C++ program? How do I use comments in C++? What are namespaces? Objectives. Learn the basic structure of a C++ program. Let’s start with the simple “Hello World” program, and look at it in more detail: 1 // My first Hello World program. 2 #include <iostream> 3. 4 int main() . 5 { 6 std::cout << "Hello World!"
www.programtopia.net › cplusplus › docsStructure and Sections of a C++ Program - Programtopia
www.programtopia.net › cplusplus › docsA C++ program can structurally be divided into different sections. Most sections are present by convention for developers to better understand a program. But there are some, which need to be followed in the order given.
www.cs.odu.edu › cppProgramStructure › indexThe Structure of a C++ Program - ODU
www.cs.odu.edu › cppProgramStructure › indexSep 5, 2017 · The Structure of a C++ Program. Steven Zeil. Last modified: Sep 5, 2017. Contents: 1 Separate Compilation. 1.1 The Files of a C++ Program. 1.2 How C++ Code is Compiled. 1.3 Pre-processing. 1.4 Other Pre-processing Commands. 2 Declarations and Definitions. 2.1 Declarations. 2.2 Definitions. 2.3 Decls&Defs: Variables. 2.4 Decls&Defs: Functions.
Searches related to What is the structure of a program written in C++?