0

Hi
The following my code snippet

void main() { vector<vector<string> > edge_set_test; [B]edge_set_test[0][0]="1"; edge_set_test[0][1]="0";[/B] cout<<"\nTesting values "<<edge_set_test[0][0]<<" "<<edge_set_test[0][1]; }

While assiging the values to the vector it throws runtime error what can be the reason for this..[code=c++]

void main()
{
vector<vector<string> > edge_set_test;
edge_set_test[0][0]="1";
edge_set_test[0][1]="0";

cout<<"\nTesting values "<<edge_set_test[0][0]<<" "<<edge_set_test[0][1];
}

While assiging the values to the vector it throws runtime error what can be the reason for this..

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by Narue
1

Your vector doesn't have any elements to assign to. You need to set the initial capacity, or insert new elements with push_back:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  vector<vector<string> > edge_set_test ( 1, vector<string> ( 2 ) );

  edge_set_test[0][0] = "1";
  edge_set_test[0][1] = "0";

  cout<<"\nTesting values "<<edge_set_test[0][0]<<" "<<edge_set_test[0][1];
}
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  vector<vector<string> > edge_set_test;

  edge_set_test.push_back ( vector<string>() );
  edge_set_test[0].push_back ( "1" );
  edge_set_test[0].push_back ( "0" );

  cout<<"\nTesting values "<<edge_set_test[0][0]<<" "<<edge_set_test[0][1];
}

Alternatively, you can combine the two:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  vector<vector<string> > edge_set_test;

  edge_set_test.push_back ( vector<string> ( 2 ) );
  edge_set_test[0][0] = "1";
  edge_set_test[0][1] = "0";

  cout<<"\nTesting values "<<edge_set_test[0][0]<<" "<<edge_set_test[0][1];
}
Votes + Comments
Nicely Explained
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.