list of char*

closed account (EwCjE3v7)
Hello there, I was wondering how I could make a list of char* pointers to C-style character strings.

I need to assign that to a vector of strings using the ::assign() function.
vector::assign will accept InputIterators, so you should be able to pass it a range of C-style strings.

1
2
3
  vector<string> vstr;
  const char * cstrs[] = {"one", "two", "three" };
  vstr.assign (cstrs,cstrs+3);   // assigning from array. 


C++11 version of vector::assign also supports an initialization list.


closed account (EwCjE3v7)
Sorry, its an exercise from my book
Write a program to assign the elements from a list of char* pointers to C-style character strings to a vector of strings


So I will have to use a list<const char*>
Wasn't sure how literally you meant "list". Suggestion: always use std::list when referring to the container to avoid confusion with a generic list.

std::list supports iterators, so creating creating the vector simply becomes:
1
2
3
4
5
 
  std::list<const char *> mylist = { "one", "two", "three" };  // Assumes C++11
  // If not C++11, use mylist.push_back() for each element
  vector<string> vstr;
  vstr.assign (mylist.begin(), mylist.end());   // assigning from array.  

For fun:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// http://ideone.com/OSQ5eF
#include <list>
#include <vector>
#include <string>
#include <set>
#include <iostream>
#include <iterator>
#include <functional>

template <typename C1, typename C2>
void assign(C1& target, const C2& source)
{
    using std::begin; using std::end;
    target.assign(begin(source), end(source));
}

template <typename C>
void print(const C& c)
{
    for (auto& e : c)
        std::cout << e << '\n';

    std::cout << '\n';
}

int main()
{
    std::vector<std::string> v;
    std::list<const char*> list = { "aaa", "bbb", "ccc" };
    std::set<const char*, std::less<std::string>> set = { "one", "two", "three", "four" };
    const char* array[] = { "one", "two", "three", "four" };

    assign(v, list);
    print(v);

    assign(v, set);
    print(v);

    assign(v, array);
    print(v);
}
closed account (EwCjE3v7)
Thank you guys, Got it

And yes I will start using std::list when talking about the container
Topic archived. No new replies allowed.