Coder Profile - Show off your skills, get a coder profile.
 
 
 
  
Posted: 4.47 Years Ago 

Cinjection
Canada
Contrib Level: 11
Total Posts: 1,587
Hey guys.

I thought that this might be a good idea. Every day, I'll try to post a tip about C++. A lot of you are more qualified to give out tips than me, so if you have a tip, just PM it to me and I'll be sure to give you credit. Thanks guys.

I want to keep all the posts coming from one person, so that's why I want to do the PM system. Enjoy.

C++ Programming Tip 1: Use vectors instead of arrays.

The C++ STL library defines a vector class which gives you a pre-made generic vector. You can use it in the same way as you would a regular array, only a vector is safer to use and more sophisticated.

Creating one is simple:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. #include <vector>
  2. using namespace std;
  3.  
  4. vector<int> myVector;
You have now created a vector to hold integers. One of the best things about vectors is that memory for them is dynamically allocated. This is perfect for occasions when you do not know the exact number of elements you may need at compile time. Here's an example:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. #include <vector>
  2. using namespace std;
  3.  
  4. vector<int> myVector;
  5.  
  6. myVector.push_back(42);
  7. myVector.push_back(34);
Note that I never explicitly tell the compiler how large my vector is. At this point in time, it contains 2 elements, but I can easily add another element to the back of the vector. If I need to get the number of elements in the vector, I can simply use the size() member of the vector object.

There are several ways to retrieve values from the vector, including the standard iterator approach supported for all STL classes. The most common way to accomplish this task is subscripting, which is identical to subscripting arrays:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. for(int i(0); i < myVector.size(); ++i)
  2. {
  3.        std::cout<< myVector[i] <<endl;
  4. }
As you can see getting values from the vector is simple. Clearing the vector is a simple one step process of calling the .clear() member.

Furthermore, vectors allow you to easily insert elements in the middle of them using simple iterator manipulations and the insert() member.

At the end of the day, vectors provide the programmer a sophisticated container. Prefer using vectors to arrays when you have the option.

Although vectors are great, I should mention that they are slower and larger than regular arrays. Most of the time, it is well worth the trade off, but always use discretion when using them. Sometimes arrays are suffice and the situation does not benefit from using vectors. In these cases, you should use arrays, but there are a lot more situations where vectors can make a programmers job easier and safer.

This is only a small overview of how vectors work and by no means comprehensive. If you plan on using them, make sure you look up a few more details about them. They really aren't hard to learn, and it will really help your C++ programming experience.

For a full list of the methods in the vector class, check out the link below.
http://www.cppreference.com/cppvector/index.html
Posted: 4.47 Years Ago 

VBAssassin
United Kingdom
Contrib Level: 17
Total Posts: 5,730
I think thats more worthy of an article though you may leave it here for the time being until i add comments to the articles section

Very nice though    i prefer vectors over arrays since i find vectors much more dynamic and a hell of a lot easier to work with when you are not 100% sure on the size.

Kind regards,
Scott
Posted: 4.47 Years Ago 

Izzmo
United States
Contrib Level: 12
Total Posts: 1,982
Definitely article worthy.

I don't know C++ very well, so hopefully reading your articles will help me infer from C# to C++ a little better.

The differences are quite noticable, but hopefully I can soon start coding some easy programs with C++.

Question: So, the main difference between vectors and arrays is that memory for vectors is dynamically allocated, and arrays is not? Also, in C++, can arrays have an unset size as well? (C# can, so I'm assuming yes.)
Posted: 4.47 Years Ago 

Cinjection
Canada
Contrib Level: 11
Total Posts: 1,587
Post Quote - Direct Reference
No. Arrays are static by nature and thus have a set size. When you get comments in the article section, I'll port them over there. Until then, I'll post them here for discussion. The next one will come a little later today.
Posted: 4.47 Years Ago 

Cinjection
Canada
Contrib Level: 11
Total Posts: 1,587
C++ Programming Tip 2: Do not use C-style strings in C++.

In C, if you ever wanted to use strings, you would need to use a null-terminated array of characters. It was ugly, unsophisticated, and very susceptible to buffer overflows. C++ and it's STL gives you a much better solution; the string class.

Making a string is easy:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. #include <string>
  2. using namespace std;
  3. string firstName("Oleksi");
  4. string lastName;
  5. lastName = "Derkatch";
Simple, as you can see. Strings keep track of their own size using the length() member:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. string name("Oleksi");
  2. name.length(); //Returns 6
  3. name = "ma";
  4. name.length(); //Returns 2
As you can see, changing the string value is simple as well. If you need to access individual characters of the string, you can treat the string as a character array in C. That is, you can easily do something like this:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. string name("Jack");
  2. for (int i(0); i < name.length(); ++i)
  3. {
  4. cout << name[i] ;
  5. }
C++ overloads the extraction operator to work with strings so you can easily use it read in information from the cin stream:
CODE: Copy / Restore  ::  Remove Scroll Bars
  1. string name;
  2. cout<<"Enter your name: ";
  3. cin>>name;
Note that if you want to read in more than one word, you will need to use the getline function as opposed to simply using cin like that.

If you want to use C++ strings, but you need to use a C library or something and need C-style string, you can still use the string class. It offers a method called c_str(), which returns the C version of the string defined in that string object. Handy.

Using the find method, you can easily search for substrings inside of the string. This makes a lot of lexical jobs much easier.

One can use the + operator to append a string and the == operator to compare to strings. A lot of the other operators are supported.

These are just a few features of the C++ string. Clearly it is much better than character arrays and you should avoid character arrays in almost all cases when you have the option of using C++ strings. They are a lot safer to use and to be frank, C-style strings are insane.

For more information about C++ strings, check out this link:
http://www.cppreference.com/cppstring/all.html
Posted: 4.47 Years Ago 

Izzmo
United States
Contrib Level: 12
Total Posts: 1,982
You should post these in seperate topics.
Posted: 4.47 Years Ago 

Cinjection
Canada
Contrib Level: 11
Total Posts: 1,587
Post Quote - Direct Reference
Hmm. I think that they'd be too scattered if I do that. I'm not to sure how I would port all these over to articles.
Posted: 4.47 Years Ago 

Coding_Guy
Canada
Contrib Level: 11
Total Posts: 1,400
copy, paste?
yeah man those tips are nice, how about creating referance variables tip, when to use it or when not to use it
Posted: 4.47 Years Ago 

Cinjection
Canada
Contrib Level: 11
Total Posts: 1,587
C++ programming tip 3: Make your destructors virtual.
This tip is from closure.

When you make a virtual method in a class, you flag it to be overloaded down the inheritance chain. This is also true for the destructor of a class.

If you allocate memory in a subclass, it can become easy to forget to free that memory. Making the base class' destructor virtual forces you to explicitly create a destructor for your subclasses, thus helping you keep track of all the memory you should be deallocating.

@Gleb: I'll be alternating between closure's tips and mine daily. The next one is probably going to regard the use of const and references/pointers, so that should satisfy your request. Just wait until tomorrow.
Posted: 4.47 Years Ago 

Coding_Guy
Canada
Contrib Level: 11
Total Posts: 1,400
yep, but both of you guys are talking in a hard core langugae, wich not everyone can nderstand
Posted: 4.47 Years Ago 

Cinjection
Canada
Contrib Level: 11
Total Posts: 1,587
Post Quote - Direct Reference
I don't think that any of the points thus far have been very complicated. The last one may have been a little hard to understand if you don't know about virtual functions and destructors. It's okay. It's a great way to learn and pick up thing.
Page of 5 :: Next Page >>
 
 
Latest News About Coder Profile
Coder Profile Poll
If you made money from keeping your profile up to date, say $30 and up, per month. What extra time would you spend on your profile?

No extra time
A few hours at weekends
A whole day each week
Every minute i can get free


please login to cast your vote
and see the results of this poll
Latest Coder Profile Changes
Coder Profile was last updated
3.49 Years Ago
Official Blog :: Make A Donation :: Credits :: Contact Me
Terms & Conditions :: Privacy Policy :: Documents :: Wallpapers
Version 1.46.00
Copyright © 2007 - 2012, Scott Thompson, All Rights Reserved