If I type the exact same code in the main function without specifying a function it works fine
Nope. You would have exactly the same problem.
[...] the invector should be the 2D Vector [...]
It isn't. std::vector<float> invector
is a vector of float
s not a 2D vector of any kind.
You get the error, because invector[i]
is a float
and float
s have no operator[]
.
Other minor issues in your code:
Don't pass big vectors by value. Pass by reference instead to avoid a unnecessary copy.
int vsize = (int) invector.size() * column;
Don't use c-style casts ((int)
). If you want to cast use static_cast
. Though you don't need to cast here at all. The type to use for container sizes is size_t
. It is unsigned. int
is signed, but a container size cannot be negative. Actually, don't pass column
. Once you make invector
2D it knows its dimensions (see below), no need to pass that along with the vector.
Further, keeping track of the index k
is error prone and not really necessary. The loops are easier when written as range based for loops.
Assuming all inner vectors are of same size, and minimal changes applied to your code, it could look like this:
using my1Dvector = std::vector<float>;
using my2Dvector = std::vector<my1Dvector>;
my1Dvector onelinevector(const my2Dvector& invector){
my1Dvector v1d;
if (invector.size() == 0) return v1d;
v1d.reserve(invector.size() * invector.front().size());
for (auto& innervector : invector) {
for (auto& element : innervector) {
v1d.push_back(element);
}
}
return v1d;
}
Almost last but not least, instead of pushing the element manually, you can use insert
(see here):
my1Dvector onelinevector(const my2Dvector& invector){
my1Dvector v1d;
if (invector.size() == 0) return v1d;
v1d.reserve(invector.size() * invector.front().size());
for (auto& innervector : invector) {
v1d.insert(v1d.end(),innervector.begin(),innervector.end());
}
return v1d;
}
Last but not least, such transformation smells like doing unnecessary work. If you want the data stored in a flat vector, you better store it in a flat vector in the first place. On the other hand, you could keep it in the 2D vector and emulate 1D access by transforming the index only.