I know how to get min and max value in a vector through iterators as shown below, But how about getting a min and max value of a matrix table in vectors of vector: for example i have:

vector<vector<float> > vec;
the above vector has a matrix (my program reads data from csv file and enters into these vectors of vector as a matrix) , such that i want to check a specific column in the vector of vector and find the min and max values in that particular column, keeping in mind that finding min and max from a specific column of a vector specified.

normal way to find min and max value in a single vector is :

int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

but what if the vector has another vector like vector<vector<float> > vec;

When dealing with a 2d vector/array the first dimension is the row and the second dimension is the column. If you wanted to go through all of the elements you would need two loops, one for the number of rows and one for the number of columns. Putting that together you get:

std::vector<std::vector<int>> vec;
// load vec
for (std::vector::size_type i = 0; i < vec.size(); ++i)
    for (std::vector::size_type j = 0; j < vec[i].size(); ++j)
        std::cout << vec[i][j] << " ";

Now if you only want to get the values from one column you can see that the second loop is useless since "j" would never change. The code to get just the column then would be

std::vector<std::vector<int>> vec;
// load vec
for (std::vector::size_type i = 0; i < vec.size(); ++i)
    std::cout << vec[i][columnNumber] << " ";

You should be able to get it from there.

IS there a way to implement min_element algorithm in 2d vectors like we do in a vector, and how to use it through iterators?

There exist at least a way to implement min_element, but it could be slightly different when you deal with more dimension. The worse case is always that you go through all elements in your vector(s). The iteration approach is already mentioned in NathanOliver post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.