1

Suppose I need this be done

I have a function, such as:

int dbs_access(chat* name, char* sql, void* outbuf, unsigned int buflen, int* outresutl)
{ do some query here and output result}

I want to get some data from DBS, so I need get some buffer and call the function above, since I don't know how many records in tables, so I can't use array, I don't want want to use new or malloc to get some memory either, because releasing memory could be a problem here. Therefore I want to use vector. But I am not sure this would be guaranteed by c++ standard ,any view?

unsigned int count;

dbs_access(...,"select count(*) from..",&count,sizeof(count),...)
std::vector records[count];
assert(records.size()==count)
dbs_access(...,"select from..",&records[0],records.size(),...)
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • You'll probably want `std::vector` there - you need to give it a type, and for flexibility for UTF16 characters, etc, `records.size()*sizeof(records[0])`, as `size()` gives the number of elements, not the total size. – Ken Y-N Jul 23 '19 at 04:04
  • You are right, that is a error. – zhangxiaoguo Jul 23 '19 at 04:28
  • 1
    a side note: if the number of records is very large the above approach using a vector may cause you problems since a vector is guaranteed to be in a continuous block. in that case maybe a list or deque would be a better choice. disclaimer: without knowing exactly your requirements & constraints. – AndersK Jul 23 '19 at 04:37

2 Answers2

2

records.data() will give you the pointer, and yes it's acceptable to use vector here, although you might want to initialise the size like so:

 std::vector records(count); 

(Rather than creating an array of vectors)

robthebloke
  • 9,331
  • 9
  • 12
1

EDIT: stop the press! I failed to notice that you probably don't want &records[0]. That doesn't do what I thought it did because I didn't notice this line:

std::vector records[count];

That line is probably not what you want anyway, so change it to this instead:

std::vector records(count);

and then you will have what you likely actually want, and my below answer will apply again.


std::vector stores data in a continuous space after C++0x:

From the n2798 (draft of C++0x)::

23.2.6 Class template vector [vector]

1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and >>erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it >>obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

So, something like &records[0] should be okay, although some consider it not the best. std::vector::data() (or records.data() in your case) is usually preferred, as long as you are in C++11 or greater.