2 doubts about vectors and strings

Hey. I'm learning about errors.
Why does this not produce an error?
I'm assuming string is an array of char. This string has 9 chars. The loop runs from 0 to 11. Will not referring to s[11] be an error?
 
string s = "Success!\n"; for (int i=0; i<12; ++i) cout << s[i];

Secondly, why is
vector<char> v = "Hello";
an error? I get this ( g++ ) :
"conversion from ‘const char [6]’ to non-scalar type ‘Vector<char>’ requested"
What does it mean?
Last edited on
> Why does this not produce an error?
> This string has 9 chars. The loop runs from 0 to 11. Will not referring to s[11] be an error?

Referring to s[11] is an error when s.size() is less than 11; it is undefined behaviour.
Attempting to modify s[11] is an error when s.size() is less than 12; this too is undefined behaviour.
(Undefined behaviour need not be diagnosed.)

For bounds checked access to characters in a string, use the member function at(). http://en.cppreference.com/w/cpp/string/basic_string/at
s.at(11) would throw an object of type std::out_of_range if s.size() is less than 11.


> why is vector<char> v = "Hello"; an error?

Unlike std::string, std::vector<char> does not have a constructor which accepts a c-style string.
http://en.cppreference.com/w/cpp/container/vector/vector

These would be fine:
1
2
3
4
std::vector<char> v = { 'h', 'e', 'l', 'l', 'o' } ;

const char cstr[] = "hello" ;
std::vector<char> v1 { cstr, cstr+sizeof(cstr)-1 } ; // -1: exclude the terminating null character 
Thanks very much!
So s.size() is not 9? (I tried catching runtime_error, it didnt catch any)
closed account (E0p9LyTq)
ephraimr wrote:
So s.size() is not 9?

Why not find out?

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>

int main()
{
   std::string s = "Success!\n";

   std::cout << s.size() << "\n";
}


I'll give you a hint: yes, s.size() is 9.
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
#include <iostream>
#include <string>
#include <iomanip>
#include <typeinfo>

int main()
{
    std::string str = "Success!!";
    std::cout << "string: " << std::quoted(str) << "  size: " << str.size() << "\n\n" ;

    for( std::size_t i = 0 ; i <= str.size() ; ++i )
    {
        std::cout << "try to access char at str[" << i << "]: " ;
        if( str[i] != 0 ) std::cout << str[i] << '\n' ;
        else std::cout << "<null>\n\n" ;
    }

    for( std::size_t i = 0 ; i <= str.size() ; ++i )
    {
        std::cout << "try to access char at str.at(" << i << "): " ;
        try { std::cout << str.at(i) << '\n' ; }
        catch( const std::exception& e ) { std::cout << "*** error: " << typeid(e).name() << '\n' ; }
    }

    // str[ str.size() + 1 ] ; // *** undefined behaviour
    // str.at( str.size() + 1 ) // *** throw std::out_of_range
}

http://coliru.stacked-crooked.com/a/73a41a5559c9774f

Gory details: http://www.cplusplus.com/forum/beginner/157585/5/
Last edited on
Topic archived. No new replies allowed.