fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. void vector_przyklad1()
  7. {
  8. vector<int> tab;
  9.  
  10. // podajesz z gory rozmiar elementow, mozesz podac zmienna oczywiscie
  11. tab.resize(10);
  12.  
  13. // wypelniasz
  14. for (int i = 0; i < 10 /* lub i < tab.size() */; i++)
  15. {
  16. tab[i] = i * 2;
  17. }
  18.  
  19. // wypisujesz od tylu
  20. for (int i = tab.size() - 1; i >= 0; i--)
  21. {
  22. cout << "tab[" << i << "] = " << tab[i] << endl;
  23. }
  24. }
  25.  
  26. void vector_przyklad2()
  27. {
  28. vector<int> tab;
  29.  
  30. // nie podajesz ilosci elementow
  31.  
  32. cout << "Podaj ilosc elementow:" << endl;
  33. int n;
  34. cin >> n;
  35.  
  36. // nie zmieniasz rozmiaru vector, opcjonalnie mozesz mu powiedziec ile
  37. // elementow planujesz dodac
  38. // odkomentuj ta linie zeby to zrobic:
  39. // tab.reserve(n);
  40. // nie zmienia ona rozmiaru tablicy, czysta optymalizacja
  41.  
  42. for (int i = 0; i < n; i++)
  43. {
  44. // dodajesz element na koncu tablicy (i zwiekszasz rozmiar)
  45. tab.push_back(1000 - i);
  46.  
  47. // Wypiszmy element i rozmiar tablicy
  48. // indeks tablicy to albo i
  49. // albo tab.size() - 1
  50. cout << "tab[" << tab.size() - 1 << "] = " << tab[i]
  51. << ", tab.size() = " << tab.size() << endl;
  52. }
  53. }
  54.  
  55. void string_przyklad()
  56. {
  57. string s1 = "asd";
  58. string s2;
  59. s2 = "123";
  60.  
  61. string s3 = s1 + s2;
  62.  
  63. s3 += "ggg";
  64.  
  65. string s4 = s1 + "ddd" + s3;
  66.  
  67. // takie cos nie zadziala
  68. // string s5 = "asd" + "def";
  69. // bo dodalbys wskazniki,
  70. // ale juz takie cos zadziala:
  71. string s5 = string("asd") + string("def");
  72.  
  73. cout << "s1 = " << s1 << endl;
  74. cout << "s2 = " << s2 << endl;
  75. cout << "s3 = " << s3 << endl;
  76. cout << "s4 = " << s4 << endl;
  77. cout << "s5 = " << s5 << endl;
  78. }
  79.  
  80. int main()
  81. {
  82. vector_przyklad1();
  83. vector_przyklad2();
  84. string_przyklad();
  85. return 0;
  86. }
Success #stdin #stdout 0s 3484KB
stdin
5
stdout
tab[9] = 18
tab[8] = 16
tab[7] = 14
tab[6] = 12
tab[5] = 10
tab[4] = 8
tab[3] = 6
tab[2] = 4
tab[1] = 2
tab[0] = 0
Podaj ilosc elementow:
tab[0] = 1000, tab.size() = 1
tab[1] = 999, tab.size() = 2
tab[2] = 998, tab.size() = 3
tab[3] = 997, tab.size() = 4
tab[4] = 996, tab.size() = 5
s1 = asd
s2 = 123
s3 = asd123ggg
s4 = asddddasd123ggg
s5 = asddef