Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate records in std::array

I am creating a 2D std::array, and want to iterate the 2D std::array record by record(not by indexes)

    std::array<std::array<int, 2>, 6> m_setSockarr;
    m_setSockarr = {{{0,1},{1,2},{2,3},{4,5},
                        {5,6},{6,7}}};
    for(auto i=m_setSockarr.begin();i !=m_setSockarr.end();i++)
    {
            //code here to print record wise.
    }

I want to print values in record wise, not index wise(not using another loop and finally printing m_setScokarr[i][j]).

In std::Map we can use it->first and it->second to print record by record(Map is associative container)

Tried printing in different ways, like a new index increment, etc.. but no progress.

I wanted the output like using iterator of std::array in one for loop

0,1
1,2
2,3
4,5
5,6
6,7

Would like to know if we could use std::array(Sequence containers) to print record wise, similar we use for std::map.

like image 552
Santosh Sahu Avatar asked Jan 20 '26 15:01

Santosh Sahu


1 Answers

In C++11:

for (const auto& record : m_setSockarr)
{
    std::cout << record[0] << ", " << record[1] << '\n';
}

In C++17:

for (const auto& [k, v] : m_setSockarr)
{
    std::cout << k << ", " << v << '\n';
}
like image 113
Vittorio Romeo Avatar answered Jan 23 '26 16:01

Vittorio Romeo