fork(1) download
  1. #include <string>
  2. #include <array>
  3. #include <vector>
  4. #include <iostream>
  5.  
  6. int main() {
  7. std::array<std::string, 3> stringarray;
  8. stringarray[0] = "hello";
  9. stringarray[1] = "world";
  10. // stringarray[2] contains an empty string.
  11.  
  12. for (size_t i = 0; i < stringarray.size(); ++i) {
  13. std::cout << "stringarray[" << i << "] = " << stringarray[i] << "\n";
  14. }
  15.  
  16. // Using a vector, which has a variable size.
  17. std::vector<std::string> stringvec;
  18.  
  19. stringvec.push_back("world");
  20. stringvec.insert(stringvec.begin(), "hello");
  21. stringvec.push_back("greetings");
  22. stringvec.push_back("little bird");
  23. std::cout << "size " << stringvec.size()
  24. << "capacity " << stringvec.capacity()
  25. << "empty? " << (stringvec.empty() ? "yes" : "no")
  26. << "\n";
  27.  
  28. // remove the last element
  29. stringvec.pop_back();
  30. std::cout << "size " << stringvec.size()
  31. << "capacity " << stringvec.capacity()
  32. << "empty? " << (stringvec.empty() ? "yes" : "no")
  33. << "\n";
  34.  
  35. std::cout << "stringvec: ";
  36. for (auto& str : stringvec) {
  37. std::cout << "'" << str << "' ";
  38. }
  39. std::cout << "\n";
  40.  
  41. // iterators and string concatenation
  42. std::string greeting = "";
  43. for (auto it = stringvec.begin(); it != stringvec.end(); ++it) {
  44. if (!greeting.empty()) // add a space between words
  45. greeting += ' ';
  46. greeting += *it;
  47. }
  48. std::cout << "stringvec combined :- " << greeting << "\n";
  49. }
  50.  
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
stringarray[0] = hello
stringarray[1] = world
stringarray[2] = 
size 4capacity 4empty? no
size 3capacity 4empty? no
stringvec: 'hello' 'world' 'greetings' 
stringvec combined :- hello world greetings