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,966 questions

51,908 answers

573 users

How to sort each row from a two-dimensional vector in C++

1 Answer

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

// Function to sort each row of a 2D vector
void sortRows(std::vector<std::vector<int>>& vec2D) {
    for (auto& row : vec2D) {
        std::sort(row.begin(), row.end());
    }
}

// Function to print a 2D vector
void print2DVector(const std::vector<std::vector<int>>& vec2D) {
    for (const auto& row : vec2D) {
        for (int num : row) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    // Define a 2D vector
    std::vector<std::vector<int>> vec2D = {
        {4, 2, 1, 3},
        {8, 6, 5, 7},
        {12, 10, 11, 9}
    };

    sortRows(vec2D);

    print2DVector(vec2D);

    return 0;
}


 
/*
run:

1 2 3 4 
5 6 7 8 
9 10 11 12 
 
*/

 



answered Mar 16, 2025 by avibootz
...