How to swap elements of vector of strings in C++

1 Answer

0 votes
#include <iostream>  
#include <vector>  
#include <string>  

int main()
{
	std::vector<std::string> vec_str;

	vec_str.reserve(4);

	vec_str.push_back("c++");
	vec_str.push_back("c");
	vec_str.push_back("java");
	vec_str.push_back("python");

	for (auto elem : vec_str) {
		std::cout << elem << ' ';
	}
	std::cout << std::endl;

	swap(vec_str[1], vec_str[3]);

	for (auto elem : vec_str) {
		std::cout << elem << ' ';
	}
	std::cout << std::endl;

	return 0;
}

/*
run:

c++ c java python
c++ python java c

*/

 



answered Jan 3, 2018 by avibootz

Related questions

1 answer 112 views
112 views asked Nov 22, 2022 by avibootz
1 answer 110 views
1 answer 182 views
1 answer 125 views
125 views asked Sep 23, 2021 by avibootz
1 answer 91 views
...