Working with strings and vectors

I have a vector<string> and a string "hello,world". I want the vector to end up containing {"hello," , "world"}. I know enough about string member functions to make these two strings, but I'm confused about how to initialize this vector.

If the vector were a string:
1
2
 string str = "hello,world", piece;
piece.assign(str, 0, str.find_first_of(',')); // (I think thats about right) 


How do I assign an element of the vector if the vector doesn't have any elements in it to begin with? I'm looking for something like vct.push_back(string between these two positions). Even if the vector was an array of strings, I still have issues.



Thanks
Last edited on
Maybe split the strings first, with strtok or something, and then put them into the vector?
I'm looking for something like vct.push_back

push_back is exactly what you need, then (or emplace_back, where supported):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <vector>
#include <iostream>
int main()
{
    std::string str = "hello,world";
    std::vector<std::string> vct;
    std::size_t pos = str.find(',');
    if(pos != std::string::npos)
    {
        ++pos;
        vct.push_back(str.substr(0, pos));
        vct.push_back(str.substr(pos));
        std::cout << vct[0] << '\n' << vct[1] << '\n';
    }
    else
    {
        std::cout << "No commas in your string\n";
    }
}

online demo: http://ideone.com/CXAZh

granted, manually parsing string like that is not the best practice, there are many ways to split strings into tokens. boost library in particular has a lot.
Topic archived. No new replies allowed.