Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to reverse subvector of a vector in C++

1 Answer

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

void reverseSubarray(std::vector<int> &v, int start, int end) {
	if (end > v.size()) {
		std::wcout << L"End index out of range";
		return;
	}

	int mid_sub = (end - start + 1) / 2;

	for (int i = 0; i < mid_sub; i++) {
		int tmp = v[start + i];
		v[start + i] = v[end - i];
		v[end - i] = tmp;
	}
}

int main() {
	std::vector<int> v = {1, 4, 8, 0, 7, 3, 9, 5, 6, 2};

	int start = 2, end = 6;

	reverseSubarray(v, start, end);

    for (auto const &n: v) {
        std::cout << n << " ";
    }
}



/*
run:
  
1 4 9 3 7 0 8 5 6 2 
 
*/

 



answered Jul 8, 2022 by avibootz
...