STL Vectors C++

STL Vectors C++

The STL vector class is a template class of sequence containers that arrange elements of a given type in a linear arrangement and allow fast random access to any element. They should be the preferred container for a sequence when random-access performance is at a premium.

In C++, vectors are one type of dynamically-allocated container from the standard template library (STL). They are capable of storing multiple elements of any defined data type, and do so in a contiguous block of memory. Unlike raw arrays, vectors are access-safe as long as you use the built in access methods associated with them. Thus, overrunning the end of a vector will throw an exception rather than crashing the program. For quickly writing access-safe code that requires very little in the way of programmer intervention for memory management, they are hard to beat. There are reasons to use other containers from the standard template library (such as lists or double-ended queues), but vectors are generally the first choice of most programmers for their versatility and speed A vector is an object that contains a sequence of other objects inside it.

Declare vectors in C++


vector <vectorType> vectorName;

STL Vectors operations C++

 

 Declaration vector<type> vector_name;
 Accessors vec.empty(), vec.size(), vec.front(), vec.back()
 Mutators vec.push_back(value), vec.pop_back()
 Operators vec[int], vec.at(int), vec1=vec2;, vec1==vec2

STL Vector member functions reference

· assign

· at

· back
· begin
· capacity
· clear
· empty
· end
· erase
· front
· get_allocator
· insert
· max_size
· operator=
· operator[]
· pop_back
· push_back
· rbegin
· rend
· reserve
· resize
· size
· swap


#include <iostream>
 #include <vector>
 using namespace std;

typedef int vector_type;

/*
 * print_info prints vector size and vector contant
 */

void print_info(vector<vector_type> v, string name) {

 vector<vector_type>::iterator it;
 cout<< "vector " << name << " contains: ";

 for (it=v.begin() ;it != v.end(); it++)
 cout << " " << *it; cout << endl;
 cout << "vector " << name << " has size: " << (int)(v.size())<< endl;

 }//end of print_info

int main () {

 vector<vector_type> vec1;
 vector<vector_type> vec2;
 vector<vector_type> vec3;
 vector<vector_type>::iterator it;

/*
 * assign operation
 */

//assign repetition of value
 vec1.assign (4,25);
 print_info(vec1,"vec1");

 //assign from conainer
 int arr[] = {3,5,8};
 vec1.assign(arr,arr+3);
 print_info(vec1,"vec1");

/*
 * back
 */

cout<< "last element in vector vec1 is: "<< vec1.back()<<endl;

/*
 * begin
 */
 it=vec1.begin();
 cout << "first element of vector vec1 is: "<< *it<< endl ;

/*
 * capacity
 */

cout << "capacity of vec1 is: " << vec1.capacity() << endl;

/*
 * empty()
 */

if( vec1.empty() )
 cout<< "vector vec1 is empty"<< endl;
 else
 cout<< "vector vec1 is not empty"<< endl;

/*
 * end()
 */

it=vec1.end();
 cout << "last element of vector vec1 is: "<< *it<< endl ;
/*
 * front()
 */

cout << "first element of vec1 is " << vec1.front() << endl;

/*
 * max_size
 */

cout << "max size of vec1 is: " << (int) vec1.max_size() << "\n";

/*
 * operator=
 */

cout << "make vec1 = vec2 " <<endl;
 vec2= vec1;
 print_info(vec1,"vec1");
 print_info(vec2,"vec2");

/*
 * pop_back
 */

 cout << "remove the last element in vec1 " <<endl;
 vec1.pop_back();

/*
 * push_back
 */

cout << "add elements to the back of vec1 " <<endl;
 vec1.push_back(20);
 vec1.push_back(15);
 vec1.push_back(26);
 vec1.push_back(10);
 vec1.push_back(6);
 print_info(vec1,"vec1");

/*
 * erase
 */

 cout << "erasing elements of vec1 " <<endl;
 // erase the 3rd element
 vec1.erase (vec1.begin()+3);
 // erase the first 2 elements:
 vec1.erase (vec1.begin(),vec1.begin()+2);
 print_info(vec1,"vec1");

/*
 * rbegin
 */

cout << "print in reverse " <<endl;
 vector<int>::reverse_iterator rit;
 for ( rit=vec1.rbegin() ; rit < vec1.rend(); ++rit )
 cout << " " << *rit;
 cout << endl;

/*
 * rend
 */

 cout << "print in reverse " <<endl;
 for ( rit=vec1.rbegin() ; rit < vec1.rend(); ++rit )
 cout << " " << *rit;
 cout << endl;

/*
 * reserve
 */

cout << "capacity of vec2 befor: " << (int) vec2.capacity() << endl;
 int my_capacity= 20;

 vec2.reserve(my_capacity);
 cout << "capacity of vec2 after: " << (int) vec2.capacity() << endl;

/*
 * resize
 */

cout << "size of vec2 befor: " << (int) vec2.size() << endl;
 int my_size= 20;

 vec2.resize(my_size);
 cout << "size of vec2 after: " << (int) vec2.size() << endl;

/*
 * size
 */

cout << "size of vec3 is : " << (int) vec3.size() << endl;

/*
 * swap
 */

print_info(vec2,"vec2");
print_info(vec3,"vec3");
vec2.swap(vec3);
print_info(vec2,"vec2");
print_info(vec3,"vec3");

/*
 * clear
 */

cout<< "clearing vector vec1 now... "<< endl;
 vec1.clear();

cout<< "clearing vector vec2 now... "<< endl;
 vec2.clear();

cout<< "clearing vector vec3 now... "<< endl;
 vec3.clear();

return 0;
}//end of main

What should I know about Vectors in C++?

  1. A vector is an object that contains a sequence of other objects inside it.
  2. The objects inside must all take up the same amount of storage.
  3. They are numbered starting with 0.
  4. If the whole vector is called v then the items in it are written vec[0], vec[1], vec[2], …
  5. The last item is vec[v.size()-1] NOT v[vec.size()].
  6. New items can be “pushed” onto the end of the vector.
  7. The last item can be “popped” off of a vector.
  8. Vectors can therefore change size.
  9. We can find out the current size of a vector: vec.size()
  10. Vectors can be empty. If so vec.empty() is true.
  11. If a vector is empty then vec[i] and vec.pop…. crash.
  12. Vectors are empty. by default, when created.
  13. Vectors shouls be passed by reference whenever possible.

The library cctype contains a number of useful predicate functions for returning information about char data, for example:

  1. isupper(ch) returns true if ch is upper case
  2. islower(ch) returns true if ch is lower case
  3. isdigit(ch) returns true if ch is a digit
  4. isalpha(ch) returns true if ch is a letter

IF you have to count specific characters such as spaces, punctuation, digits, words, or letters. If you need to store them, vectors would be not bad choice of data structure to do so.

Examples how to Count spaces, punctuation, digits, words, and letters.


#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

/*
 Count spaces, punctionation, digits, words, and letters.
 */

struct count
 {
 int words,letters,spaces,punct,digits;
 }count_info;

int main() {

 const char *myString = "word1,word2,word3,word4,word5? !";

 cout <<"counting stuff in:" << myString << endl;

 while(*myString)
 { if(isalpha(*myString) )
 { while(isalpha(*myString) )
 {
 myString++;count_info.letters++;
 }//end of while
 count_info.words++;
 }//end of if
 if(isspace(*myString)) count_info.spaces++;
 else if(ispunct(*myString)) count_info.punct++;
 else if(isdigit(*myString)) count_info.digits++;
 myString++;
 }//end of while

 cout << "Words: " << count_info.words << endl;
 cout << "Letters: " << count_info.letters<< endl;
 cout << "Digits: " << count_info.digits << endl;
 cout << "Spaces: " << count_info.spaces << endl;
 cout << "Punctuation: " << count_info.punct << endl;

 return 0;
}// end main

Example of STL Vectors and strings in C++

/*
 * File: main.cpp
 * Author: Mycodinglab.com
 *
 * Created on June 13, 2011, 2:26 AM
 */

#include <algorithm>
#include <vector>
#include <iostream>
#include <string>

using namespace std;

int main()
{
 //create a vector of strings
 vector<string> vec;

//create vector iterator
 vector<string>::iterator it1;

//add some items to the vector
 vec.push_back("Monday");
 vec.push_back("Tuesday");
 vec.push_back("Wednesday");
 vec.push_back("Thursday");
 vec.push_back("Friday");

// sort the vector
 sort(vec.begin(), vec.end());

//display the vector
 for (it1 = vec.begin(); it1 != vec.end(); it1++)
 cout << *it1 << endl;

// search item
 string str("Monday");

// display whether item was found or not (1 or 0)
 cout << endl << "binary search results: "<<
 binary_search(vec.begin(), vec.end(), str) << endl;

 return 0;
} // end main

You must be logged in to post a comment.

Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com
%d bloggers like this: