问题描述
我认为下面的代码片段是完全合法的(它建立在MS Visual Studio 2008,C + +)。
I think the following code snippet is perfectly legal (it builds anyway on MS Visual Studio 2008, C++).
我使用它链接到第三方库。但我认为,因为我传递一个向量元素的指针,而不是第三方库函数期望的常规指针,我得到运行时错误
I use it to link to a 3rd party library. But I think because I am passing a pointer to a vector element instead of a regular pointer that the 3rd party library function expects, I get a run-time error
我在这里做什么?
std::vector<int> vec_ints(27,0);
std::vector<double> vec_doub(27, 0.);
for(int i = 0; i < n; ++i) {
//-Based on my understanding when i >=27, STL vectors automatically reallocate additional space (twice).
vec_ints[i] = ...;
vec_doub[i] = ...;
}
const int* int_ptr = &vec_ints[0];
const double* doub_ptr = &vec_doub[0];
//-Func is the 3rd party library function that expects a const int* and const double* in the last 2 arguments.
func(...,...,int_ptr,doub_ptr);
但是在MS Visual Studio 2008(Windows Vista)上构建之后运行此操作会导致运行时错误如上所述,
But running this after building on MS Visual Studio 2008 (Windows Vista), leads to run-time error as mentioned above, viz.,
在Linux上还没有测试过,我确定要避免将向量的内容复制到一个数组中。任何想法是怎么回事?
Haven't tested this on Linux yet and I sure would like to avoid copying the contents of the vector into an array just for this. Any ideas what is going on?
进一步编辑以确认使用Nick和Chris的推荐,并继续与Vlad等人进行讨论;这里是一个代码片段:
Further edit to confirm usage of Nick and Chris' recommendation and to continue discussion with Vlad et al; here's a code snippet:
#include <iostream>
#include <vector>
int main() {
for(int i=2; i<6; ++i) {
int isq = i*i;
std::vector<int> v;
v.reserve(4);
for(int j=0; j<isq; ++j) {
v.push_back(j);
}
std::cout << "Vector v: size = " << v.size() << " capacity = " << v.capacity()
<< "\n";
std::cout << "Elements: \n";
for(int k=0; k<v.size(); ++k) {
std::cout << v.at(k) << " ";
}
std::cout << "\n\n";
}
return 0;
}
提供输出:
Vector v: size = 4 capacity = 4
Elements:
0 1 2 3
Vector v: size = 9 capacity = 16
Elements:
0 1 2 3 4 5 6 7 8
Vector v: size = 16 capacity = 16
Elements:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Vector v: size = 25 capacity = 32
Elements:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24
推荐答案
<$
std::vector<int> vec_ints;
vec_ints.reserve(27);
std::vector<double> vec_doub;
vec_doub.reserve(27);
for(int i = 0; i < n; ++i) {
vec_ints.push_back(...);
vec_doub.push_back(...);
}
const int* int_ptr = &vec_ints[0];
const double* doub_ptr = &vec_doub[0];
func(...,...,int_ptr,doub_ptr);
你想要的东西
这篇关于C ++将指针传递给向量元素而不是数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!