siloan
siloan

Reputation: 89

Vectors of vectors string issue

i'm in a situation with a declaration of vector<vector<string>>. On windows it's ok i can declare this in a struct like vector<vector<string>>v={{"me","you"}} but on a linux machine..only errors so i must declare it after the struct initialization but how because mystruct.vec[0]={"me","you"} gives me a segmentation fault. Any sugestions please?

Upvotes: 1

Views: 180

Answers (2)

Omnifarious
Omnifarious

Reputation: 56038

This program on gcc 4.7.2 works just fine:

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

using ::std::vector;
using ::std::string;
using ::std::move;

vector<vector<string>> foo()
{
   vector<vector<string>>v={{"me","you"}};
   return move(v);
}

int main()
{
   using ::std::cout;

   cout << "{\n";
   for (auto &i: foo()) {
      cout << "   {\n";
      for (auto &o: i) {
         cout << "      \"" << o << "\",\n";
      }
      cout << "   },\n";
   }
   cout << "}\n";
   return 0;
}

It produces this output:

$ /tmp/a.out 
{
   {
      "me",
      "you",
   },
}

I think your problem is either an old compiler or that you have some other problem in some other place in your code.

I used this command line to compile:

$ g++ -std=gnu++0x -march=native -mtune=native -Ofast -Wall -Wextra vvstr.cpp

And my g++ gives this as a version:

$ g++ --version
g++ (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

This page tells you which version of gcc has which C++ feature:

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227390

If you are using GCC, them you need a version that supports this C++11 initialization feature, and then you need to tell the compiler to compile in C++11 mode by passing it the -std=c++0x flag (or =std=c++11 for the 4.7 series). See this demo, compiled with GCC 4.7.2:

#include <vector> 
#include <string>   
int main() 
{   
  std::vector<std::vector<std::string>> v = {{"me","you"}}; 
}

Upvotes: 2

Related Questions