2017-07-21 10 views
3
#include<bits/stdc++.h> 
using namespace std; 
main() 
{ 
    vector<vector<int> > v; 
    for(int i = 0;i < 3;i++) 
    { 
     vector<int> temp; 
     for(int j = 0;j < 3;j++) 
     { 
      temp.push_back(j); 
     } 
     //cout<<typeid(temp).name()<<endl; 
     v[i].push_back(temp); 
    } 
} 

2次元ベクトルに割り当てようとしています。私は、次のエラーを取得2次元ベクトルをC++に代入する

No matching function for call to 
std ::vector<int>::push_back(std::vector<int> &) 
+4

'v.push_back(...) ' –

+1

' v [i] 'は範囲外にアクセスします。ベクトルにはエントリがありません –

+0

'v.push_back(vector)'と 'v [i] .push_back(int)' –

答えて

6

問題います:。あなたのベクトルvがまだ空で、あなたが、V内の任意のベクトルを押さずにv[i]にアクセスすることはできません

ソリューション:と声明v[i].push_back(temp);を交換してくださいv.push_back(temp);

4
v[i].push_back(temp); 

する必要があります10
v.push_back(temp); 

vv[i]あなたは、このプロセスに従うことができstd::vector<int>

4

の一種で、std::vector<vector<int>>のタイプです:

#include<bits/stdc++.h> 
using namespace std; 
int main() 
{ 
    vector<vector<int> > v; 
    for(int i = 0;i < 3;i++) 
    { 
     vector<int> temp; 
     for(int j = 0;j < 3;j++) 
     { 
      temp.push_back(j); 

     } 
     //cout<<typeid(temp).name()<<endl; 
     v.push_back(temp); 
    } 
    for(int i = 0; i < 3; i++){ 
     for(int j = 0; j < 3; j++){ 
      cout << v[i][j] << " "; 
     } 
     cout << endl; 
    } 
} 
4

あなたが代わりにv[i]vを使用する必要があります。

for(int i = 0; i < 3; i++){ 
    vector <vector <int> > v; 
    vector <int> temp; 
    v.push_back(temp); 
    v.at(COLUMN).push_back(i); 
} 

次に、あなたがそれを介してアクセスできます:(C++ 11)

#include <iostream> 
#include <vector> 

using namespace std; 

int main(int argc, char* argv[]) 
{ 
    vector<vector<int> > v; 
    for(int i = 0;i < 3;i++) 
    { 
     vector<int> temp; 
     for(int j = 0;j < 3;j++) 
     { 
      temp.push_back(j); 
     } 

     v.push_back(temp); 
    } 

    for (auto element: v) { 
     for (auto atom: element) { 
      cout << atom << " "; 
     } 
     cout << "\n"; 
    } 

    return 0; 
} 
5

v[0]はあなたがこのエラーを回避するためにatアプローチを使用することができv.push_back(temp);

を使用する必要があり、空である

v.at(COLUMN).at(ROWS) = value; 
3

このように考えると、「どのようにvaリラブル温度タイプTの私のベクトルにstd::vector<T>? "あなたのケースでは、次のとおりです。

v.push_back(temp); 

T自体はベクトルという違いはありません。そして、あなたは2つのforのループを使用することができます(ベクトルの)あなたのベクトルをプリントアウトします...ちょうどそれを行う

for (std::size_t i = 0; i < v.size(); i++){ 
    for (std::size_t j = 0; j < v[i].size(); j++){ 
     std::cout << v[i][j] << ' '; 
    } 
    std::cout << std::endl; 
} 
0

#include<bits/stdc++.h> 
using namespace std; 
int main() 
{ 
vector<vector<int> > v; 
for(int i = 0; i < 3; i++) 
{ 
    vector<int> temp; 
    for(int j = 0; j < 3; j++) 
    { 
     temp.push_back(j); 
    } 
    v.push_back(temp);//use v instead of v[i]; 
} 

}

関連する問題