About Me

About Me : I have been working as a Software Engineer for various international companies for four years.Currently, I am working as a full stack Javascript developer in Petronas(Malaysia).

Skills

Skills • Javascript •Typescript •Python •C •Java •ReactJs • Redux • VueJs • NestJs • React Testing Library • Django• PostgreSQL • MySQL • NodeJs • Git • Docker • Jira • Visual Studio Code • Slack

মঙ্গলবার, ৭ জুলাই, ২০১৫

C++ - std::vector add, insert, remove, process, erase, swap, sort, clear



Here is some examples of how to use std::vector with string for most of the common operations that can be performed on std::vector.

The following example assume the following has been declared



1
std::vector<std::string> vec;


Adding Items

1
2
3
4
5
vec.push_back("Item 1");
vec.push_back("Item 2");
vec.push_back("Item 3");
vec.push_back("Item 4");
vec.push_back("Item 5");

Adding Items to front

1
2
vec.insert(vec.begin(), "Front 2");
vec.insert(vec.begin(), "Front 1");

Remove Last Item

1
vec.pop_back();



Remove First Item

1
vec.erase(vec.begin());


Process All Items

1
2
3
4
for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
  printf("%s\n", it->c_str());
}

Process All Items

1
2
3
4
for(size_t i = 0; i < vec.size(); i++)
{
  printf("%s\n", vec[i].c_str());
}

Reverse The Order - Note you can also just run the above backwards instead.

1
2
3
4
5
6
for(size_t i = 0; i < vec.size() / 2; i++)
{
  std::string tmp = vec[i];
  vec[i] = vec[vec.size() - i - 1];
  vec[vec.size() - i - 1] = tmp;
}

Sorting

1
std::sort(vec.begin(), vec.end());

Find and Remove an item

1
2
3
4
5
6
7
8
for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
  if (*it == "Item 2")
  {
    vec.erase(it);
    break//it is now invalud must break!
  }
}

Clear All Items

1
vec.clear();

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন