私は2次元ベクトルを使っています:
std::vector<std::vector<int> *> hp;
私はhpベクトルを初期化し、同じものの特定のインデックスからデータを取得したい。
for eg,
Getting the values from hp[2][2];
助けてください
回答:
回答№1は1ご了承ください
std::vector<std::vector<int>*> hp
型のオブジェクトへのポインタを含むstd :: vectorを定義する
std::vector<int>
raviが言及したように、あなたはおそらく
std::vector<std::vector<int>> hp;
しかし、ポインタ付きのベクトルを持つことを主張するならば、
std::vector<std::vector<int>*> hp;
(*hp[2])[2] // retrieves third value from third std::vector<int>
備考:C ++ 11(C ++ 0xとも呼ばれます)では、 ">"の間にスペーシングが必要ありません(例で書いたように)。
回答№2の場合は1
以下を試してください
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int> *> hp =
{
new std::vector<int> { 1, 2, 3 },
new std::vector<int> { 4, 5, 6 }
};
for ( std::vector<std::vector<int> *>::size_type i = 0;
i < hp.size(); i++ )
{
for ( std::vector<int>::size_type j = 0; j < hp[i]->size(); j++ )
{
std::cout << ( *hp[i] )[j] << " ";
// std::cout << hp[i]->operator[]( j ) << " ";
}
std::cout << std::endl;
}
for ( auto &v : hp ) delete v;
return 0;
}
内部ループ内のコメントされたステートメントとコメントアウトされていないステートメントの場合、プログラムの出力は同じになります
1 2 3
4 5 6
回答№3の場合は0
これらが他の場所で所有されているベクターへのポインタである場合は、
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
// Create owning vector
std::vector<std::vector<int>> h = {{0,1,2},{3,4,5},{6,7,8}};
// Create vector of pointers
std::vector<std::vector<int>*> hp(h.size());
//auto get_pointer = [](std::vector<int>& v){return &v;}; // C++11
auto get_pointer = [](auto& v){return &v;}; // C++14
std::transform(h.begin(), h.end(), hp.begin(), get_pointer);
// Output value in third column of third row
std::cout << (*hp[2])[2];
}