User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 427,940 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,673 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser: Programming Forums
Dec 11th, 2004
Views: 23,223
The Standard Template Library (STL) vector is tempting. The burden of dimensioning an array is removed, and there are many wonderful functions to explore. The learning curve is a little steep, it will make your head swell, but in the end it's all worthwhile. Take a look at some of the code that is supposed to make programming easier.
Last edited : Oct 2nd, 2006.
cplusplus Syntax | 4 stars
  1. // Testing the Standard Template Library (STL) vector ...
  2. // a vector forms an expandable array that can be reversed, sorted,
  3. // partitioned, copied, searched, shuffled, unequaled and much more
  4. // a Dev-C++ tested console application by vegaseat 10dec2004
  5.  
  6. #include <iostream>
  7. #include <algorithm> // check stl_algo.h for details
  8. #include <vector> // vector header
  9. #include <iomanip> // setw()
  10. #include <iterator> // ostream_iterator
  11. #include <functional> // bind2nd
  12. #include <string> // string output
  13.  
  14. using namespace std; // std::cout etc.
  15.  
  16. int main()
  17. {
  18. int k;
  19. const int N = 10;
  20. // this is how an array can be initialized
  21. int ar[N] = { 12, 45, 234, 64, 99, 35, 63, 23, 17, 55 };
  22. // it was too simple for the folks who created the vector,
  23. // but you can use the array to initialize the vector, note
  24. // (ar, ar+N) dimensions vector iV and loads it with N elements
  25. vector<int> iV(ar, ar+N);
  26. cout << "vector initialized with an array:\n";
  27. // display it, similar to the array
  28. for(k = 0; k < iV.size(); k++)
  29. {
  30. cout << setw(5) << iV[k];
  31. }
  32. cout << endl;
  33.  
  34. // a more intuitive method with a loop like the display loop
  35. // you can use this method because vector iV is dimensioned
  36. for(k = 0; k < iV.size(); k++)
  37. {
  38. iV[k] = ar[k];
  39. }
  40. cout << "vector loop-initialized with an array:\n";
  41. // should give the same display
  42. for(k = 0; k < iV.size(); k++)
  43. {
  44. cout << setw(5) << iV[k];
  45. }
  46. cout << endl;
  47.  
  48. // you can initialize a vector with an existing vector
  49. vector<int> iV3 = iV;
  50. cout << "one vector initialized with another vector:\n";
  51. // display it, similar to the array
  52. for(k = 0; k < iV3.size(); k++)
  53. {
  54. cout << setw(5) << iV3[k];
  55. }
  56. cout << endl;
  57.  
  58. // find the value 99 in the vector
  59. vector<int>::iterator iter = find(iV.begin(), iV.end(), 99);
  60. if (iter == iV.end())
  61. {
  62. cout << "99 not found\n";
  63. }
  64. else
  65. {
  66. cout << "found 99 at element " << iter - iV.begin() << " (starts at 0)\n";
  67. }
  68. // advance the iterator 4 positions
  69. advance(iter, 4);
  70. cout << "element " << iter - iV.begin() << " has value of " << *iter;
  71. cout << endl;
  72.  
  73. // another way to load a vector ...
  74. vector<char> cV(50, '-');
  75. cout << "this vector has 50 char - :\n";
  76. for(k = 0; k < cV.size(); k++)
  77. {
  78. cout << cV[k];
  79. }
  80. cout << endl;
  81.  
  82. // insert some additional elements
  83. cout << "inserted 10 char c starting with element 25:\n";
  84. cV.insert(cV.begin() + 25, 10, 'c');
  85. for(k = 0; k < cV.size(); k++)
  86. {
  87. cout << cV[k];
  88. }
  89. cout << endl;
  90.  
  91. // take the character vector and shuffle the characters
  92. cout << "let's shuffle the thing ...\n";
  93. random_shuffle(cV.rbegin(), cV.rend());
  94. for(k = 0; k < cV.size(); k++)
  95. {
  96. cout << cV[k];
  97. }
  98. cout << endl;
  99.  
  100. // how many elements can a vector hold?
  101. // a huge number, actually until memory runs out!
  102. // well, let's test it to a million elements ...
  103. vector<int> kV;
  104. cout << "loading an integer vector with numbers 0 to 999999 ...\n";
  105. for(k = 0; k < 1000000; k++)
  106. {
  107. kV.push_back(k);
  108. }
  109. cout << "content of element 123456 = " << kV[123456] << endl;
  110. cout << "content of element 999999 = " << kV[999999] << endl;
  111.  
  112. // create a vector for doubles
  113. vector<double> dV;
  114. double d;
  115. // load a vector from the keyboard
  116. cout << "Enter some floating point numbers (q to quit)\n";
  117. // actually, any non-numeric char will exit the loop
  118. while(cin >> d)
  119. {
  120. // push_back() appends the vector dV and also expands dV
  121. // so you don't have to predimension the vector!!!!
  122. dV.push_back(d);
  123. }
  124.  
  125. // number of elements in the vector
  126. cout << "counted " << dV.size() << " elements\n";
  127.  
  128. if (dV.empty())
  129. {
  130. cout << "... cannot process an empty vector so I made one up:\n";
  131. dV.push_back(99.9);
  132. dV.push_back(7.1);
  133. dV.push_back(39.4);
  134. dV.push_back(72.0);
  135. }
  136.  
  137. cout << "elements in the order they were entered:\n";
  138. // display the entered elements
  139. for(k = 0; k < dV.size(); k++)
  140. {
  141. cout << dV[k] << '\n';
  142. }
  143. cout << "elements in reverse order:\n";
  144. reverse(dV.begin(), dV.end());
  145. // display the reversed order elements
  146. for(k = 0; k < dV.size(); k++)
  147. {
  148. cout << dV[k] << '\n';
  149. }
  150.  
  151. // find min and max values
  152. cout << "Min val is " << *min_element(dV.begin(), dV.end()) << endl;
  153. cout << "Max val is " << *max_element(dV.begin(), dV.end()) << endl;
  154.  
  155. cout << "elements sorted:\n";
  156. sort(dV.begin(), dV.end());
  157. // display the sorted elements
  158. for(k = 0; k < dV.size(); k++)
  159. {
  160. cout << dV[k] << '\n';
  161. }
  162. cout << "could have picked min/max=begin/end from the sorted vector:\n";
  163. cout << "Min val is " << dV.front() << endl;
  164. cout << "Max val is " << dV.back() << endl;
  165.  
  166. // create a vector for integers
  167. vector<int> iV1;
  168. // load the vector with 20 random integers (0 - 200)
  169. for(k = 0; k < 20; k++)
  170. {
  171. iV1.push_back(rand() % 200);
  172. }
  173. cout << "20 random integers:\n";
  174. // display the random integer elements
  175. for(k = 0; k < iV1.size(); k++)
  176. {
  177. cout << setw(8) << iV1[k];
  178. }
  179. cout << endl;
  180.  
  181. // extract values less than 100 from vector iV using partition()
  182. // create an iterator (pointer) for an integer vector
  183. vector<int>::iterator itpV;
  184. cout << "partition elements with value < 100 :\n";
  185. // move all values < 100 to the front and point to partition end
  186. // bind2nd() converts a binary function to a unary function
  187. itpV = partition(iV1.begin(), iV1.end(), bind2nd(less<int>(),100));
  188. // display the partitioned vector
  189. for(k = 0; k < iV1.size(); k++)
  190. {
  191. cout << setw(8) << iV1[k];
  192. }
  193. cout << endl;
  194. // create a second vector to hold partioned elements
  195. vector<int> iV2;
  196. cout << "copy partioned elements to a new vector:\n";
  197. // copy partitioned elements to the new vector iV2
  198. copy(iV1.begin(), itpV, back_inserter(iV2));
  199. // display the new vector with the values < 100
  200. for(k = 0; k < iV2.size(); k++)
  201. {
  202. cout << setw(8) << iV2[k];
  203. }
  204. cout << endl << endl;
  205.  
  206. // load another integer vector with an array
  207. cout << "load a vector with an array:\n";
  208. int b[] = {0, 1, 2, 3, 4, 3, 4, 5, 6, 4};
  209. // using (array, array + NumberOfElements)
  210. vector<int> iV4(b, b + sizeof(b)/sizeof(int));
  211. cout << "number of elements = " << sizeof(b)/sizeof(int) << endl;
  212. for(k = 0; k < iV4.size(); k++)
  213. {
  214. cout << setw(8) << iV4[k];
  215. }
  216. cout << endl;
  217.  
  218. // remove the duplicates with sort(), erase() and unique()
  219. cout << "removed the duplicate elements:\n";
  220. sort( iV4.begin(), iV4.end() );
  221. iV4.erase( unique( iV4.begin(), iV4.end() ), iV4.end() );
  222. for(k = 0; k < iV4.size(); k++)
  223. {
  224. cout << setw(8) << iV4[k];
  225. }
  226. cout << endl;
  227.  
  228. // Now on to a string vector
  229. // Just an example of a dimensioned vector (space for 4 strings),
  230. // later followed by expansion.
  231. // Don't get confused here ...
  232. // if you don't want to dimension the vector, use vector<string> sV
  233. // and load with sV.push_back() from the beginning
  234. //
  235. vector<string> sV(4);
  236. // load it ...
  237. sV[0] = "red";
  238. sV[1] = "green";
  239. sV[2] = "yellow";
  240. sV[3] = "blue";
  241. // you will exceed 4 strings, push_back() takes care of this!
  242. sV.push_back("purple");
  243. sV.push_back("bisque");
  244. cout << "display vector elements via ostream_iterator:\n";
  245. // just a different way to write out the elements
  246. // pipe to std::cout or, if you want, to a file
  247. copy(sV.begin(), sV.end(), ostream_iterator<string>(cout," "));
  248. cout << endl << endl;
  249.  
  250. // create an iterator (pointer) for a string vector
  251. vector<string>::iterator itsV;
  252. cout << "searching the vector for blue (elements start with 0)\n";
  253. // you can use +=, --, -=, ++ operators, and comparison
  254. // operators <, <=, >, >=, ==, != with vector iterators
  255. for(itsV = sV.begin(); itsV < sV.end(); itsV++)
  256. {
  257. // search using comparison operators
  258. if (*itsV == "blue")
  259. {
  260. cout << "found blue in element " << itsV - sV.begin() << "\n\n";
  261. }
  262. }
  263. // remove those remaining \n char, thanks to ~s.o.s~
  264. cin.clear();
  265. cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
  266. cin.get(); // console keypress wait
  267.  
  268. return 0;
  269. }
Comments (Newest First)
vegaseat | Kickbutt Moderator | Oct 2nd, 2006
Thanks keithr, for making the code work with VisualStudio.Net (2003). Looks like different compilers have somewhat different header requirements. Oh the joy of C++ headers!!!
keithr | Unverified User | Jan 9th, 2006
I got the code to compile, I think all that is necessary is to add the following headers;

#include <functional> // bind2nd
#include <string> // string output
keithr | Unverified User | Jan 9th, 2006
vegaseat, the code does not compile with VisualStudio.Net (2003).
vegaseat | Kickbutt Moderator | Mar 10th, 2005
The code field has a tendency to eat indentations, so I went through the code and added lots of {} around single statements in for/if/while.
Post Comment

Only community members can submit or comment on code snippets. You must register or log in to contribute.

DaniWeb Marketplace (Sponsored Links)
All times are GMT -4. The time now is 6:44 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC