Pergunta

Apologies if the title is not clear, this is what I am hoping for.

I'm creating a library, where a method accepts an iterator:

template<typename T>
void test(T begin, T end)
{
  for(auto it = begin; (it != end); it++)
  {
    for (auto c = it->begin(); c != it->end(); c++)
    {
      std::cout << *c << std::endl;
    }
  }
}

I can print the contents using this method, however, instead of this, I want to do the following:

I want to know the rows / columns based on the iterator.. E.g.

If the values were: std::vector<std::vector<double>> d = { {1, 1, 1}, {2, 2, 2} } Then it would be a 2x2 vector, so then I could (in the method) size a std::array from this. I'm trying to avoid passing through x/y to the method, basically.

Is this possible? I can't seem to find anything.

Foi útil?

Solução 2

Maybe you did not want to create an std::array but a std::vector you simply can do the following. Maybe I misunderstood your question, but I hope this helps!

#include <iostream>
#include <vector>

using namespace std;

    template<typename T>
vector<T> test(T begin, T end)
{   
    size_t size=0;

    for(auto it = begin; (it != end); it++)
    {   
        size+=it->size();
    }   

    vector<T> ret = vector<T>(size);
    return ret;
}   

int main()
{   
    std::vector<std::vector<double>> d = { {1, 1, 1}, {2, 2, 2} };

    auto ret=test(d.begin(), d.end());
    cout << "Size of returned vector is " << ret.size() << endl;

    return 0;
}  

And if you do not want to pass iterators, you can make it a bit smaller with:

#include <iostream>
#include <vector>

using namespace std;

    template<typename T>
vector<T> test(const T& matrix)
{   
    size_t size=0;

    for( auto it: matrix)
    {   
        size+=it.size();
    }   

    vector<T> ret = vector<T>(size);
    return ret;
}   

int main()
{   
    std::vector<std::vector<double>> d = { {1, 1, 1}, {2, 2, 2} };

    auto ret=test(d);
    cout << "Size of returned vector is " << ret.size() << endl;

    return 0;
}   

Outras dicas

The size of an std::array is a template parameter, so it must be known at compile time. What you want to do involves computing the size at runtime, so it can't be done this way.

It is fine to use a std::vector. Contrary to popular belief, they are not significantly slower than plain arrays or std::arrays, provided that you don't resize them after construction (and that you have a halfway decent compiler).

There is a proposed container called std::dynarray that is sized at runtime but cannot be resized after construction. However, this was voted out of C++14.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top