Vectors

Well, I'm a newbie to programming & a self-learner. So, vector confused me a good bit. I want to know the use of vector, its applications in programming. Why we use vector & what's its use. Everything was going on well, but I'm little bit of struck in vector. I want to clear every bit of vector so that it doesn't reate any confusion for me in the future. So, kindly help me to get a sense of vector.

PS.: Please don't use any technical language or hard-core c++ stuffs. Just explain where & how we use vector in programming. Give me a sense of it in the easiest way.

Thanks.
Last edited on
read the book "C How to Program" written by P.J.Deitel and H.M.Deitel
@flussadl How's C++ Primer by Stanley Lippman? Is it a good book?
Last edited on
@JLBorges Thanks for recommendation of the links. I think they'll help me understanding vectors better.
> How's C++ Primer by Stanley Lippman? Is it a good book?

Yes. One of the best. If you are going for it, get the latest edition (fifth).

You may want to have a look at this list (Beginners Introductory):
http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list

Bruce Eckel's book (somewhat dated) is also available for free download:
http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html
Last edited on
vectors are dynamic allocated arrays pretty much. It is just a class object.

http://www.cplusplus.com/reference/vector/vector/ talks about them at the top of the page plus has all the stuff in the vector class.
i have something to give for a self-learner (i really love those guys), here's all i know about vectors:

as giblit said, they are dynamic arrays, means : a vector acts like an array, but it can extend in size at runtime, that makes it a flixible array.

vectors actually have one little problem, if you're going to extend it often, it can really reduce performance, i suggest that you use them in places where you don't need to extend them often, or when you make big extensions but in low frequency.
this way you can make the best use of vectors without considerable loss in performance.

where does this loss in performance come from:

vectors allocate contiguous memory addresses, so when you want to extend it, it might need to allocate a totally other memory space, then copy the old contents and put the new elements then deallocate the old memory space, this is a lot of overhead, that's why you shouldn't extend them often.

maybe 20-30 extend operations is not really bad, but i'm talking about 1000 operations or more when using object vectors... that will surely cause loss in performance.

other data structures don't need contiguous memory space to use, they can avoid this overhead, but they have other properties, you really should learn about a data structure and its properties before using it.

this was a practical information based on my personal and modest understanding of vectors.
i wish i could remember that great article about vectors, i think it was in stackoverflow.com or something.

hope that was useful.
@Rechard3 Thanks for this information. It helped me understand vector better. But I want to put some questions: Where's vector used? What's its use in C++ programming? As far as I've learned, you can just print out elements of a vector either by iterators or subscripting, & that's it. Is there any practical application of vector?

Thanks.
basically you can replace all arrays with vectors

int arr[100] = {0}; <=> std::vector<int> arr(100,0);

int arr[] = {0,1,2,3,4,5,6}; <=> std::vector<int> arr = {0,1,2,3,4,5,6}; //C++11


1
2
3
4
5
6
7
8
9
10
11
int* arr = NULL;
arr = new int[100];

for (int i=0; i<100; ++i)
  arr[i] = i*i;

for (int i=0; i<100; ++i)
  std::cout << arr[i] << " ";
std::cout << "\n";

delete [] arr; //you have to 'clean' arr 
<=>
1
2
3
4
5
6
7
8
9
10
11
12
vector<int> arr;
arr.resize(100);

//same code with arr above
for (int i=0; i<100; ++i)  //or you can replace 100 with arr.size()
  arr[i] = i*i;

for (int i=0; i<100; ++i)
  std::cout << arr[i] << " ";
std::cout << "\n";

//you DON'T have to 'clean' arr 


another example, a Tetris shape has 4 pieces, type of piece is Coord, so I can use a static array Coord data[4]; to store my Tetris shape's pieces, or better, use vector<Coord> data; since I can extend my Tetris shape to have 6, 5, 3, 2, or 1 piece(s).


for Snake game, because the body can grow, I will choose vector<Coord> body; as the body of the snake, instead of using dynamic array, with a Coord pointer and dealing with allocating memory each time the snake eats.

Hey guys,

Here's a problem of vector that I think I've solved:

Write a program to read a sequence of ints from cin and store those values in a vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Write a program to read a sequence of ints from cin and store those values in a vector.

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

int main()
{ 
    int number;                //number declared
    while (cin>>number) {      //read the input "number"
    vector<int> number;        //store the input in the vector
    }
    system ("pause");
    return 0;
}


The program compiler successfully. So, I think I succeeded. But as there's no output operation for this one, I'm not sure, if I wrote the program correct. So, I want you C++ experts to review the same & comment if things are correct or it needs some improvement.

Thanks.
ok, i can see you're missing something here, i won't try to compile this code, because it has a major flaw:
the number that is inside the while loop is a totally different identifier than the one outside it.
use this code to understand what is happening in your program:
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
#include <iostream>
#include <vector>
using namespace std;
using std::vector;

int main()
{ 
    int number;                //number declared
	int temp;	// i will use this for my own purpose.    rechard3 comment
    while (cin>>number) {      //read the input "number"
		temp = number;
		cout<<"the number entered is "<<number<<endl;	//this is the int, not the vector.    rechard3 comment
		vector<int> number;        //store the input in the vector

		if( temp == 0 )		//this will print the vector.    rechard3 comment
		{
			cout<<"=================================\n\nthe contents of your vector are:\n\n";
			for (int i=0; i<number.size() ; i++)	//number here refers to the vector.    rechard3 comment
			{
				cout<<number[i]<<' ';
			}
			cout<<"\n\n";
			if ( number.empty() )
				cout<<"Oops, looks like the vector is empty.\n\n";
			break;	//go out of the loop.    rechard3 comment
		}

    }

    return 0;
}


maybe the output of this program can demonstrate something about scopes, just insert some numbers then insert 0, and see the result.
you should consider using these functions with vector:

push back():
http://www.cplusplus.com/reference/vector/vector/push_back/

resize():
http://www.cplusplus.com/reference/vector/vector/resize/
you don't need resize. After you push back it automatically resizes.
> Write a program to read a sequence of ints from cin and store those values in a vector.

An then print them out at the end:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> sequence ;

    int number ;
    while( std::cin >> number ) sequence.push_back(number) ;

    for( int v : sequence ) std::cout << v << ' ' ; 

    // or C++98: 
    // for( std::size_t i = 0 ; i < sequence.size() ; ++i ) 
           // std::cout << sequence[i] << ' ' ;

    std::cout << '\n' ;
}
Topic archived. No new replies allowed.