1

I want to access the string in the first entry in the vector inside the first entry in another vector. My code:

typedef std::vector<std::string> DatabaseRow;
std::vector<DatabaseRow*> data;

//getting data from database 
//(dont need this for this example)

//then print first entry out
printf("%s.\n",dbresult.data[0][0].c_str());

But then I get error:

error: ‘class std::vector, std::allocator >, std::allocator, std::allocator > > >’ has no member named ‘c_str’

Any insight please?

A. Cloete
  • 69
  • 6

2 Answers2

6

You are storing pointers to databases:

std::vector<DatabaseRow*> data;
                       ^ Pointer

So you will have to access it like:

(*dbresult.data[0])[0].c_str()

1. (*dbresult.data[0])  // Dereference the pointer
2. [0]                  // Access the internal Vector   
3. .c_str()             // Use the string

Or, do the better thing and don't make it a pointer, use it as an actual object the way it is supposed to be:

 std::vector<DatabaseRow> data;
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • Thank you so much! Your solution is working perfectly! I agree to rather not make it a pointer, but I am working on existing code base that I can't change. – A. Cloete May 25 '18 at 15:01
3
  • dbresult.data[0]: this is a std::vector<std::string>*.
  • *dbresult.data[0]: this is a std::vector<std::string>.
  • (*dbresult.data[0])[0]: this is a std::string.

Here you go:

(*dbresult.data[0])[0]

But ask yourself:

  • Am I sure I want to store pointers to vectors?
  • Am I sure I want to have a 2D array instead of a nice Matrix-like linearized array?
  • AM I sure I want to stick to C-like functions (std::printf) instead of the type-strong C++ equivalent (std::cout et al.)?
YSC
  • 38,212
  • 9
  • 96
  • 149